@amityco/ts-sdk-react-native 7.9.1 → 7.9.2

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.
Files changed (26) hide show
  1. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/@types/domains/stream.d.ts +1 -0
  2. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/@types/domains/stream.d.ts.map +1 -1
  3. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/@types/domains/stream.js.map +1 -1
  4. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/index.d.ts +1 -0
  5. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/index.d.ts.map +1 -1
  6. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/index.js +1 -0
  7. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/index.js.map +1 -1
  8. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/utils/linkedObject/streamLinkedObject.d.ts +2 -0
  9. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/utils/linkedObject/streamLinkedObject.d.ts.map +1 -1
  10. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/utils/linkedObject/streamLinkedObject.js +5 -1
  11. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/dist/utils/linkedObject/streamLinkedObject.js.map +1 -1
  12. package/.rollup.cache/home/runner/work/AmityReactNativeTypescriptSDK/AmityReactNativeTypescriptSDK/packages/sdk/tsconfig.tsbuildinfo +1 -1
  13. package/dist/@types/domains/stream.d.ts +1 -0
  14. package/dist/@types/domains/stream.d.ts.map +1 -1
  15. package/dist/index.cjs.js +7 -3
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.esm.js +7 -4
  19. package/dist/index.umd.js +2 -2
  20. package/dist/utils/linkedObject/streamLinkedObject.d.ts +2 -0
  21. package/dist/utils/linkedObject/streamLinkedObject.d.ts.map +1 -1
  22. package/package.json +1 -1
  23. package/src/@types/domains/stream.ts +1 -0
  24. package/src/index.ts +2 -0
  25. package/src/utils/linkedObject/streamLinkedObject.ts +7 -0
  26. package/tsconfig.tsbuildinfo +1 -1
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- var Amity=function(e,t,n,r,a,s,o,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,f=h(n),m=h(r),g=h(a),y=h(s),v=h(o),b=h(i),w=h(c),C=h(d),I=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation";const S=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip"}),_=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),O=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var T;e.FileAccessTypeEnum=void 0,(T=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",T.NETWORK="network";const 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}}),R="ONLY_ADMIN_CAN_POST",P=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var M;e.ContentFlagReasonEnum=void 0,(M=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",M.HarassmentOrBullying="Harassment or bullying",M.SelfHarmOrSuicide="Self-harm or suicide",M.ViolenceOrThreateningContent="Violence or threatening content",M.SellingRestrictedItems="Selling and promoting restricted items",M.SexualContentOrNudity="Sexual message or nudity",M.SpamOrScams="Spam or scams",M.FalseInformation="False information or misinformation",M.Others="Others";const j=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),U=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip"});var x,D,q,N,B,L,F,K;e.InvitationTypeEnum=void 0,(x=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",x.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(D=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",D.Approved="approved",D.Rejected="rejected",D.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(q=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",q.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(N=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(B=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",B.Pending="pending",e.FeedDataTypeEnum=void 0,(L=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",L.Video="video",L.Image="image",L.File="file",L.LiveStream="liveStream",L.Clip="clip",L.Poll="poll",e.FeedSortByEnum=void 0,(F=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",F.FirstCreated="firstCreated",F.LastUpdated="lastUpdated",F.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(K=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",K.User="user";const $=function(){try{return"v7.9.1-umd"}catch(e){return"__dev__"}}(),Q=5,z="cache_then_server",V="For using Live Collection feature you need to enable Cache!",H="Observing unsynced object is not supported by Live Object.",J=-5,W=1e3,G=6e5,Y="dead",Z=6e4,X=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})),ee=e=>JSON.parse(e),te=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>te(e[n],t[n])))),ne=e=>[400400,400300].includes(e),re=e=>["skip"].some((t=>t in e)),ae=e=>["after","before","first","last","limit"].some((t=>t in e)),se=e=>"limit"in e,oe=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),ie=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&ae(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},ce=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(re(n))return{after:n.skip,limit:n.limit};if(ae(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},le=e=>"locally"in e,de=e=>"optimistically"in e,ue=e=>le(e)||de(e),he=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),pe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},fe=(e,...t)=>({func:e,args:t}),me=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Z?Z:t},ge=({func:e,args:t},n,r=me("cache_then_server"))=>{let a;const{lifeSpan:s}=me("cache_then_server",r.lifeSpan);if(ue(e)){try{a=de(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ye(void 0,{origin:"local",loading:!1,error:e}))}const r=he(a)&&pe(a,s);if(null==n||n(ye(a,{origin:"local",loading:!(le(e)&&r)})),r)return}else null==n||n(ye(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ye(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ye(void 0,{origin:"server",loading:!1,error:e}))}))};function ye(e,t){return oe(e)||he(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ve={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,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId: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,streamModeration:({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,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e},be=e=>ve[e],we={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",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest"};function Ce(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class Ie 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,Ie)}}class Se extends Ie{constructor(e,t,n){super(e,t,n)}}class _e extends Ie{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ke extends Ie{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Oe extends Ie{constructor(e){super(e,800110,"error")}}let Te=null;const Ee=()=>{if(!Te)throw new Ie("There is no active client",8e5,"fatal");return Te},Ae=e=>{Te=e},Re=e=>{const{log:t,cache:n}=Ee();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=ee(t);return te(e,n)})).map((e=>n.data[e]))},Pe=e=>{const{log:t,cache:n}=Ee();if(!n)return;t("cache/api/pullFromCache",e);const r=X(e);return n.data[r]?n.data[r]:void 0},Me=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const s=X(e);return a.data[s]=Object.assign({key:e,data:t},n),!0},je=(e,t,n)=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const s=Pe(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Me(e,o,n),!0);var i,c},Ue=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Pe(e)?je(e,t,n):Me(e,t,n)},xe=(e,t=!1)=>{const{log:n,cache:r}=Ee();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>ee(e))).filter((t=>te(e,t))).map((e=>xe(e,!0))).every((e=>e));const a=X(e);return a in r.data&&(delete r.data[a],!0)},De=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,qe=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Ne=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Be=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=be("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(r=Pe(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),Le=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=Pe(["feed","get",be("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),Fe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=be("communityUsers")({communityId:e.communityId,userId:n}),s=null===(r=Pe(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),Ke=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const a=null===(r=Pe(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),$e=(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))}))},Qe=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,ze=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ve=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),He=({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(),We=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ge=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ye=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ze=null;const Xe=()=>{if(!Ze)throw new Ie("Connect client first",8e5,"fatal");return Ze},et=e=>{Ze={_id:e._id,userId:e.userId,path:e.path}};let tt,nt=[];const rt=e=>{clearTimeout(tt),nt.push(e),tt=setTimeout((()=>{nt.forEach((e=>e())),nt=[]}),0)},at=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],st=(e,t,n,r)=>{const{log:a,emitter:s}=e,o=Date.now();a(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{a(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},ot=(e,t)=>{const{emitter:n}=Ee();rt((()=>{n.emit(e,t)}))};let it,ct;async function lt(){var e;const{mqtt:t,emitter:n,token:r}=Ee();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",s=Xe();it===a&&ct===s._id||(it=a,ct=s._id,await t.connect({accessToken:it,userId:ct}),((e,t)=>{at.forEach((n=>{null==e||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 dt;e.SubscriptionLevels=void 0,(dt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",dt.POST="post",dt.COMMENT="comment",dt.POST_AND_COMMENT="post_and_comment",dt.USER="user";const ut=(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}},ht=e=>e.path.split("/user/")[0],pt=({path:t},n=e.SubscriptionLevels.USER)=>ut(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),ft=({channelId:e,subChannelId:t})=>{const n=Xe();return`${ht(n)}/marker/channel/${e}/message/${t}`},mt=()=>{const e=Xe();return`${ht(e)}/marker/user/${e._id}`},gt=()=>ht(Xe()),yt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/channels`},vt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messagefeeds`},bt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messages`},wt=()=>{const e=Xe();return`${ht(e)}/videostreaming`};function Ct(e,t){const{mqtt:n}=Ee();return n?(lt(),n.subscribe(e,t)):()=>null}var It;const St="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:_t={}}=St,kt="production"===(null===(It=_t.env)||void 0===It?void 0:It.NODE_ENV),Ot={EU:"eu",SG:"sg",US:"us"},Tt={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Et(e,t){return Tt[e].replace("{region}",t)}class At{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let Rt;var Pt,Mt=()=>(Rt||(Rt=new At),Rt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(Pt||(Pt={}));const jt=new AbortController,Ut=e=>{switch(e){case Pt.UserGlobalBanned:throw new Ie(e,400312,"fatal");case Pt.UserDeleted:throw new Ie(e,400100,"fatal");case Pt.TokenExpired:throw ot("tokenExpired","tokenExpired"),new Ie(e,800403,"fatal");default:throw new Ie("Request Aborted",8e5,"error")}},xt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new y.default(t),httpsAgent:new s.HttpsAgent(t),signal:jt.signal});return n.defaults.withCredentials=!1,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&&(jt.abort(),Ut(Pt.UserGlobalBanned)),r&&(jt.abort(),Ut(Pt.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(jt.abort(Pt.UserDeleted),Ut(Pt.TokenExpired))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const r=(e.config.baseURL||"")+(e.config.url||""),a=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),s={method:a,headers:e.config.headers};return"GET"!==a&&"HEAD"!==a&&(s.body=e.config.data),Mt().setNetworkActivities(new Request(r,s),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&ot("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 _e(e.code);if("error"===e.status)throw new Se(e.message,e.code,"error")})(null==r?void 0:r.data),jt.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 Dt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function qt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Nt(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 Bt={exports:{}};Bt.exports=function(){function e(t,n,r){function a(o,i){if(!n[o]){if(!t[o]){if(!i&&Nt)return Nt(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return a(t[o][1][e]||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var s=Nt,o=0;o<r.length;o++)a(r[o]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,s=e("./store"),o=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"),m=e("xtend"),g=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 S(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&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("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},g("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},g("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},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(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){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("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 T(e){e&&(g("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 E(e,t,n,r){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,s=t;if("publish"===s.cmd&&(s=p(t),a=_(e,s),a))return n&&n(a);e.outgoingStore.put(s,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("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 s,this.incomingStore=t.incomingStore||new s,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?g("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();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let s=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(s=!1)),s?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function s(){if(a.length)y(o);else{const e=r;r=null,e()}}function o(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),o()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_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,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.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(g("_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()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},R.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 a=r.resubscribe;let s=t.pop()||A,o=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof s&&(o=s,s=A);const c=f.validateTopics(r);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||a){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){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=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("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){g("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]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),this},R.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()||A,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=r,r=A);const s=f.validateTopics(n);if(null!==s)return v(r,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof a&&a.properties&&(s.properties=a.properties),e.outgoing[s.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),s()),this)},R.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},R.prototype.reconnect=function(e){g("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 s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_sendPacket :: (%s) :: start",this.options.clientId),n=n||A,t=t||A;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(g("_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 E(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:E(this,e,t,n);break;default:k(this,e,t)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_storePacket :: cb? %s",!!t),n=n||A;let r=e;if("publish"===r.cmd){r=p(e);const n=_(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"))},R.prototype._setupPingTimer=function(){g("_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))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_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)}},R.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)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,s=e.messageId,o=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 g("_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 g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===c.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?o.emit("error",a):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),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: "+C[n]),o.code=n,a(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 s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:s.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,A),r._sendPacket(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_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){g("_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},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}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):g("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",s),r.on("error",(function(e){a(),t._flushStoreProcessingQueue(),t.removeListener("close",s),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?(a(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.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=R}).call(this)}).call(this,e("_process"),void 0!==Dt?Dt:"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"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new a;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 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,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.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)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.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 o=t.my,o.connectSocket({url:r,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),a=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return a("port %d and host %s",n,s),r.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),a=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("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"),a=e("ws"),s=e("debug")("mqttjs:ws"),o=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){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+r),new a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){s("streamBuilder");const n=u(t),r=d(n,e),o=p(e,r,n),i=a.createWebSocketStream(o,n.wsOptions);return i.url=r,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){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>a&&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=o(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),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?g:m}).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"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c;function l(){const e=new a;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 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(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.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);o=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const a=c.destroy;return c.destroy=function(){c.destroy=a;const e=this;setTimeout((function(){o.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"),a=e("readable-stream").Readable,s={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(o,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 a(s),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"),a=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new a(1,e),this.max=e,this.length=0)}s.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},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"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 a(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:a}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),a=e("../store"),s=e("url"),o=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=s.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(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 a=new r(n,t);return a.on("error",(function(){})),a}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=a}).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=m;for(var r=[],a=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)r[i]=o[i],a[o.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),o=r[0],i=r[1],c=new s(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[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,a=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(p(r));return a.join("")}function m(e){for(var t,n=e.length,a=n%3,s=[],o=16383,i=0,c=n-a;i<c;i+=o)s.push(f(e,i,i+o>c?c:i+o));return 1===a?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),a=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,a,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.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}},s.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},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.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)},s.prototype.copy=function(e,t,n,a){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof a||a>this.length)&&(a=this.length),n>=this.length)return e||r.alloc(0);if(a<=0)return e||r.alloc(0);const s=!!e,o=this._offset(n),i=a-n;let c=i,l=s&&t||0,d=o[1];if(0===n&&a===this.length){if(!s)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[o[0]].length-d)return s?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);s||(e=r.allocUnsafe(i));for(let t=o[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},s.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),a=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?a.pop():a[a.length-1]=a[a.length-1].slice(0,r[1]),0!==n[1]&&(a[0]=a[0].slice(n[1])),this._new(a)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.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},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.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},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.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 a=this._offset(t);let s=a[0],o=a[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([s,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([s,o]);if(this._match(t,e))return t;o++}o=0}return-1},s.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]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[a]},t.exports=s},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,a=e("inherits"),s=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}s._init.call(this,e),r.call(this)}a(o,r),Object.assign(o.prototype,s.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 s||o.isBufferList(e)},o.isBufferList=s.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=s},{"./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 a=2147483647;function s(){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>a)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(G(e,ArrayBuffer)||e&&G(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 a=m(e);if(a)return a;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?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(e<0?0:0|g(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=o(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(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 m(e){if(i.isBuffer(e)){var t=0|g(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||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.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)||G(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 a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return J(e).length;default:if(a)return r?-1:z(e).length;t=(""+t).toLowerCase(),a=!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 x(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return j(this,t,n);case"latin1":case"binary":return U(this,t,n);case"base64":return A(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,a){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=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)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,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,a){var s,o=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;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*o}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function _(e,t,n,r){return W(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return W(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return W(J(t),e,n,r)}function E(e,t,n,r){return W(H(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function R(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,c,l=e[a],d=null,u=l>239?4:l>223?3:l>191?2:1;if(a+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[a+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(c=(15&l)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&o)<<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),a+=u}return M(r)}n.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=s(),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(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(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,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];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),a=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.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?R(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,a){if(G(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===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(s,o),l=this.slice(r,a),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],o=d[u];break}return s<o?-1:o<s?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 a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return O(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function M(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 j(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=Q(e[s]);return a}function D(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function q(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,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)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,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,4),r.write(e,t,n,a,23,4),n+4}function F(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,8),r.write(e,t,n,a,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||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||q(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||q(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||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||q(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||q(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||q(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||q(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||q(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.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 a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.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},i.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},i.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},i.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},i.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},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.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},i.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},i.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},i.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},i.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},i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(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 a=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 s=a-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return a},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 a=e.charCodeAt(0);("utf8"===r&&a<128||"latin1"===r)&&(e=a)}}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 s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=i.isBuffer(e)?e:i.from(e,r),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.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;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function V(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,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}function J(e){return t.toByteArray($(e))}function W(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function G(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 a(){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 s(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,a=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(a=r))})),e.splice(a,0,n)}function o(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=s,n.save=o,n.load=i,n.useColors=a,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,s,o=null;function i(...e){if(!i.enabled)return;const n=i,a=Number(new Date),s=a-(t||a);n.diff=s,n.prev=t,n.curr=a,t=a,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,a)=>{if("%%"===t)return"%";o++;const s=r.formatters[a];if("function"==typeof s){const r=e[o];t=s.call(n,r),e.splice(o,1),o--}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=a,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==r.namespaces&&(n=r.namespaces,s=r.enabled(e)),s),set:e=>{o=e}}),"function"==typeof r.init&&r.init(i),i}function a(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),a=n.length;for(t=0;t<a;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(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=o,r.enable=s,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 a=e("readable-stream"),s=e("end-of-stream"),o=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 a.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);a.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(m,a.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.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=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),a=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",a),r()};this._unwrite&&n.nextTick(a),this._writable=e,this._writable.on("drain",a),this._unwrite=o,this.uncork()}else this.end()},m.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=s(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},a=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",a),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",a),this._unread=o,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.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}},m.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)}))},m.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")},m.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()},m.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)}))}))},m.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),a.Writable.prototype.end.call(this,n))},t.exports=m}).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"),a=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},o=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||a);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||m()},m=function(){h=!1,u||c.call(e)},g=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",m)};return s(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),o(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),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||_,a=Object.keys||k,s=Function.prototype.bind||O;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 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?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,a=I(e,r),s=0;s<r;++s)a[s].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].call(n,r)}function p(e,t,n,r,a){if(t)e.call(n,r,a);else for(var s=e.length,o=I(e,s),i=0;i<s;++i)o[i].call(n,r,a)}function f(e,t,n,r,a,s){if(t)e.call(n,r,a,s);else for(var o=e.length,i=I(e,o),c=0;c<o;++c)i[c].call(n,r,a,s)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].apply(n,r)}function g(e,t,n,a){var s,o,i;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),i=o[t]):(o=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=a?[n,i]:[i,n]:a?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){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=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},a=s.call(y,r);return a.listener=n,r.wrapFn=a,a}function b(e,t,n){var r=e._events;if(!r)return[];var a=r[t];return a?"function"==typeof a?n?[a.listener||a]:[a]:n?S(a):I(a,a.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,a=e.length;r<a;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 S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(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 O(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"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}}):o.defaultMaxListeners=c,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 d(this)},o.prototype.emit=function(e){var t,n,r,a,s,o,i="error"===e;if(o=this._events)i=i&&null==o.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=o[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(a=new Array(r-1),s=1;s<r;s++)a[s-1]=arguments[s];m(n,l,this,a)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(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,a,s,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(a=this._events))return this;if(!(n=a[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete a[e],a.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():C(n,s),1===n.length&&(a[e]=n[0]),a.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,s;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,i=a(n);for(s=0;s<i.length;++s)"removeListener"!==(o=i[s])&&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(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);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,a,s,o,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,f=h(n),m=h(r),g=h(a),y=h(s),v=h(o),b=h(i),w=h(c),C=h(d),I=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation";const S=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip"}),_=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),O=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var T;e.FileAccessTypeEnum=void 0,(T=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",T.NETWORK="network";const 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}}),R="ONLY_ADMIN_CAN_POST",P=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var M;e.ContentFlagReasonEnum=void 0,(M=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",M.HarassmentOrBullying="Harassment or bullying",M.SelfHarmOrSuicide="Self-harm or suicide",M.ViolenceOrThreateningContent="Violence or threatening content",M.SellingRestrictedItems="Selling and promoting restricted items",M.SexualContentOrNudity="Sexual message or nudity",M.SpamOrScams="Spam or scams",M.FalseInformation="False information or misinformation",M.Others="Others";const j=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),U=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip"});var x,D,q,N,B,L,F,K;e.InvitationTypeEnum=void 0,(x=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",x.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(D=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",D.Approved="approved",D.Rejected="rejected",D.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(q=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",q.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(N=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(B=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",B.Pending="pending",e.FeedDataTypeEnum=void 0,(L=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",L.Video="video",L.Image="image",L.File="file",L.LiveStream="liveStream",L.Clip="clip",L.Poll="poll",e.FeedSortByEnum=void 0,(F=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",F.FirstCreated="firstCreated",F.LastUpdated="lastUpdated",F.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(K=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",K.User="user";const $=function(){try{return"v7.9.2-umd"}catch(e){return"__dev__"}}(),Q=5,z="cache_then_server",V="For using Live Collection feature you need to enable Cache!",H="Observing unsynced object is not supported by Live Object.",J=-5,W=1e3,G=6e5,Y="dead",Z=6e4,X=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})),ee=e=>JSON.parse(e),te=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>te(e[n],t[n])))),ne=e=>[400400,400300].includes(e),re=e=>["skip"].some((t=>t in e)),ae=e=>["after","before","first","last","limit"].some((t=>t in e)),se=e=>"limit"in e,oe=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),ie=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&ae(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},ce=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(re(n))return{after:n.skip,limit:n.limit};if(ae(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},le=e=>"locally"in e,de=e=>"optimistically"in e,ue=e=>le(e)||de(e),he=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),pe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},fe=(e,...t)=>({func:e,args:t}),me=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Z?Z:t},ge=({func:e,args:t},n,r=me("cache_then_server"))=>{let a;const{lifeSpan:s}=me("cache_then_server",r.lifeSpan);if(ue(e)){try{a=de(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ye(void 0,{origin:"local",loading:!1,error:e}))}const r=he(a)&&pe(a,s);if(null==n||n(ye(a,{origin:"local",loading:!(le(e)&&r)})),r)return}else null==n||n(ye(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ye(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ye(void 0,{origin:"server",loading:!1,error:e}))}))};function ye(e,t){return oe(e)||he(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ve={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,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId: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,streamModeration:({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,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e},be=e=>ve[e],we={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",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest"};function Ce(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class Ie 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,Ie)}}class Se extends Ie{constructor(e,t,n){super(e,t,n)}}class _e extends Ie{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ke extends Ie{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Oe extends Ie{constructor(e){super(e,800110,"error")}}let Te=null;const Ee=()=>{if(!Te)throw new Ie("There is no active client",8e5,"fatal");return Te},Ae=e=>{Te=e},Re=e=>{const{log:t,cache:n}=Ee();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=ee(t);return te(e,n)})).map((e=>n.data[e]))},Pe=e=>{const{log:t,cache:n}=Ee();if(!n)return;t("cache/api/pullFromCache",e);const r=X(e);return n.data[r]?n.data[r]:void 0},Me=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const s=X(e);return a.data[s]=Object.assign({key:e,data:t},n),!0},je=(e,t,n)=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const s=Pe(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Me(e,o,n),!0);var i,c},Ue=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Pe(e)?je(e,t,n):Me(e,t,n)},xe=(e,t=!1)=>{const{log:n,cache:r}=Ee();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>ee(e))).filter((t=>te(e,t))).map((e=>xe(e,!0))).every((e=>e));const a=X(e);return a in r.data&&(delete r.data[a],!0)},De=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,qe=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Ne=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Be=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=be("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(r=Pe(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),Le=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=Pe(["feed","get",be("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),Fe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=be("communityUsers")({communityId:e.communityId,userId:n}),s=null===(r=Pe(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),Ke=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const a=null===(r=Pe(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),$e=(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))}))},Qe=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,ze=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ve=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),He=({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(),We=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ge=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ye=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ze=null;const Xe=()=>{if(!Ze)throw new Ie("Connect client first",8e5,"fatal");return Ze},et=e=>{Ze={_id:e._id,userId:e.userId,path:e.path}};let tt,nt=[];const rt=e=>{clearTimeout(tt),nt.push(e),tt=setTimeout((()=>{nt.forEach((e=>e())),nt=[]}),0)},at=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],st=(e,t,n,r)=>{const{log:a,emitter:s}=e,o=Date.now();a(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{a(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},ot=(e,t)=>{const{emitter:n}=Ee();rt((()=>{n.emit(e,t)}))};let it,ct;async function lt(){var e;const{mqtt:t,emitter:n,token:r}=Ee();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",s=Xe();it===a&&ct===s._id||(it=a,ct=s._id,await t.connect({accessToken:it,userId:ct}),((e,t)=>{at.forEach((n=>{null==e||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 dt;e.SubscriptionLevels=void 0,(dt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",dt.POST="post",dt.COMMENT="comment",dt.POST_AND_COMMENT="post_and_comment",dt.USER="user";const ut=(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}},ht=e=>e.path.split("/user/")[0],pt=({path:t},n=e.SubscriptionLevels.USER)=>ut(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),ft=({channelId:e,subChannelId:t})=>{const n=Xe();return`${ht(n)}/marker/channel/${e}/message/${t}`},mt=()=>{const e=Xe();return`${ht(e)}/marker/user/${e._id}`},gt=()=>ht(Xe()),yt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/channels`},vt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messagefeeds`},bt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messages`},wt=()=>{const e=Xe();return`${ht(e)}/videostreaming`};function Ct(e,t){const{mqtt:n}=Ee();return n?(lt(),n.subscribe(e,t)):()=>null}var It;const St="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:_t={}}=St,kt="production"===(null===(It=_t.env)||void 0===It?void 0:It.NODE_ENV),Ot={EU:"eu",SG:"sg",US:"us"},Tt={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Et(e,t){return Tt[e].replace("{region}",t)}class At{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let Rt;var Pt,Mt=()=>(Rt||(Rt=new At),Rt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(Pt||(Pt={}));const jt=new AbortController,Ut=e=>{switch(e){case Pt.UserGlobalBanned:throw new Ie(e,400312,"fatal");case Pt.UserDeleted:throw new Ie(e,400100,"fatal");case Pt.TokenExpired:throw ot("tokenExpired","tokenExpired"),new Ie(e,800403,"fatal");default:throw new Ie("Request Aborted",8e5,"error")}},xt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new y.default(t),httpsAgent:new s.HttpsAgent(t),signal:jt.signal});return n.defaults.withCredentials=!1,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&&(jt.abort(),Ut(Pt.UserGlobalBanned)),r&&(jt.abort(),Ut(Pt.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(jt.abort(Pt.UserDeleted),Ut(Pt.TokenExpired))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const r=(e.config.baseURL||"")+(e.config.url||""),a=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),s={method:a,headers:e.config.headers};return"GET"!==a&&"HEAD"!==a&&(s.body=e.config.data),Mt().setNetworkActivities(new Request(r,s),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&ot("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 _e(e.code);if("error"===e.status)throw new Se(e.message,e.code,"error")})(null==r?void 0:r.data),jt.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 Dt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function qt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Nt(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 Bt={exports:{}};Bt.exports=function(){function e(t,n,r){function a(o,i){if(!n[o]){if(!t[o]){if(!i&&Nt)return Nt(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return a(t[o][1][e]||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var s=Nt,o=0;o<r.length;o++)a(r[o]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,s=e("./store"),o=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"),m=e("xtend"),g=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 S(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&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("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},g("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},g("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},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(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){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("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 T(e){e&&(g("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 E(e,t,n,r){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,s=t;if("publish"===s.cmd&&(s=p(t),a=_(e,s),a))return n&&n(a);e.outgoingStore.put(s,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("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 s,this.incomingStore=t.incomingStore||new s,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?g("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();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let s=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(s=!1)),s?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function s(){if(a.length)y(o);else{const e=r;r=null,e()}}function o(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),o()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_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,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.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(g("_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()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},R.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 a=r.resubscribe;let s=t.pop()||A,o=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof s&&(o=s,s=A);const c=f.validateTopics(r);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||a){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){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=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("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){g("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]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),this},R.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()||A,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=r,r=A);const s=f.validateTopics(n);if(null!==s)return v(r,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof a&&a.properties&&(s.properties=a.properties),e.outgoing[s.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),s()),this)},R.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},R.prototype.reconnect=function(e){g("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 s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_sendPacket :: (%s) :: start",this.options.clientId),n=n||A,t=t||A;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(g("_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 E(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:E(this,e,t,n);break;default:k(this,e,t)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_storePacket :: cb? %s",!!t),n=n||A;let r=e;if("publish"===r.cmd){r=p(e);const n=_(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"))},R.prototype._setupPingTimer=function(){g("_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))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_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)}},R.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)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,s=e.messageId,o=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 g("_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 g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===c.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?o.emit("error",a):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),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: "+C[n]),o.code=n,a(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 s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:s.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,A),r._sendPacket(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_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){g("_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},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}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):g("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",s),r.on("error",(function(e){a(),t._flushStoreProcessingQueue(),t.removeListener("close",s),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?(a(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.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=R}).call(this)}).call(this,e("_process"),void 0!==Dt?Dt:"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"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new a;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 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,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.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)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.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 o=t.my,o.connectSocket({url:r,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),a=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return a("port %d and host %s",n,s),r.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),a=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("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"),a=e("ws"),s=e("debug")("mqttjs:ws"),o=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){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+r),new a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){s("streamBuilder");const n=u(t),r=d(n,e),o=p(e,r,n),i=a.createWebSocketStream(o,n.wsOptions);return i.url=r,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){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>a&&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=o(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),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?g:m}).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"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c;function l(){const e=new a;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 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(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.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);o=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const a=c.destroy;return c.destroy=function(){c.destroy=a;const e=this;setTimeout((function(){o.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"),a=e("readable-stream").Readable,s={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(o,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 a(s),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"),a=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new a(1,e),this.max=e,this.length=0)}s.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},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"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 a(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:a}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),a=e("../store"),s=e("url"),o=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=s.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(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 a=new r(n,t);return a.on("error",(function(){})),a}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=a}).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=m;for(var r=[],a=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)r[i]=o[i],a[o.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),o=r[0],i=r[1],c=new s(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[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,a=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(p(r));return a.join("")}function m(e){for(var t,n=e.length,a=n%3,s=[],o=16383,i=0,c=n-a;i<c;i+=o)s.push(f(e,i,i+o>c?c:i+o));return 1===a?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),a=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,a,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.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}},s.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},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.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)},s.prototype.copy=function(e,t,n,a){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof a||a>this.length)&&(a=this.length),n>=this.length)return e||r.alloc(0);if(a<=0)return e||r.alloc(0);const s=!!e,o=this._offset(n),i=a-n;let c=i,l=s&&t||0,d=o[1];if(0===n&&a===this.length){if(!s)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[o[0]].length-d)return s?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);s||(e=r.allocUnsafe(i));for(let t=o[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},s.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),a=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?a.pop():a[a.length-1]=a[a.length-1].slice(0,r[1]),0!==n[1]&&(a[0]=a[0].slice(n[1])),this._new(a)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.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},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.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},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.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 a=this._offset(t);let s=a[0],o=a[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([s,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([s,o]);if(this._match(t,e))return t;o++}o=0}return-1},s.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]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[a]},t.exports=s},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,a=e("inherits"),s=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}s._init.call(this,e),r.call(this)}a(o,r),Object.assign(o.prototype,s.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 s||o.isBufferList(e)},o.isBufferList=s.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=s},{"./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 a=2147483647;function s(){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>a)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(G(e,ArrayBuffer)||e&&G(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 a=m(e);if(a)return a;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?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(e<0?0:0|g(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=o(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(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 m(e){if(i.isBuffer(e)){var t=0|g(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||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.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)||G(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 a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return J(e).length;default:if(a)return r?-1:z(e).length;t=(""+t).toLowerCase(),a=!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 x(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return j(this,t,n);case"latin1":case"binary":return U(this,t,n);case"base64":return A(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,a){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=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)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,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,a){var s,o=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;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*o}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function _(e,t,n,r){return W(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return W(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return W(J(t),e,n,r)}function E(e,t,n,r){return W(H(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function R(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,c,l=e[a],d=null,u=l>239?4:l>223?3:l>191?2:1;if(a+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[a+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(c=(15&l)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&o)<<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),a+=u}return M(r)}n.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=s(),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(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(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,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];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),a=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.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?R(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,a){if(G(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===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(s,o),l=this.slice(r,a),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],o=d[u];break}return s<o?-1:o<s?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 a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return O(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function M(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 j(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=Q(e[s]);return a}function D(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function q(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,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)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,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,4),r.write(e,t,n,a,23,4),n+4}function F(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,8),r.write(e,t,n,a,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||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||q(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||q(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||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||q(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||q(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||q(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||q(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||q(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.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 a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.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},i.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},i.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},i.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},i.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},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.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},i.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},i.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},i.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},i.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},i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(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 a=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 s=a-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return a},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 a=e.charCodeAt(0);("utf8"===r&&a<128||"latin1"===r)&&(e=a)}}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 s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=i.isBuffer(e)?e:i.from(e,r),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.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;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function V(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,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}function J(e){return t.toByteArray($(e))}function W(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function G(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 a(){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 s(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,a=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(a=r))})),e.splice(a,0,n)}function o(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=s,n.save=o,n.load=i,n.useColors=a,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,s,o=null;function i(...e){if(!i.enabled)return;const n=i,a=Number(new Date),s=a-(t||a);n.diff=s,n.prev=t,n.curr=a,t=a,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,a)=>{if("%%"===t)return"%";o++;const s=r.formatters[a];if("function"==typeof s){const r=e[o];t=s.call(n,r),e.splice(o,1),o--}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=a,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==r.namespaces&&(n=r.namespaces,s=r.enabled(e)),s),set:e=>{o=e}}),"function"==typeof r.init&&r.init(i),i}function a(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),a=n.length;for(t=0;t<a;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(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=o,r.enable=s,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 a=e("readable-stream"),s=e("end-of-stream"),o=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 a.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);a.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(m,a.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.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=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),a=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",a),r()};this._unwrite&&n.nextTick(a),this._writable=e,this._writable.on("drain",a),this._unwrite=o,this.uncork()}else this.end()},m.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=s(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},a=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",a),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",a),this._unread=o,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.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}},m.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)}))},m.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")},m.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()},m.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)}))}))},m.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),a.Writable.prototype.end.call(this,n))},t.exports=m}).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"),a=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},o=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||a);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||m()},m=function(){h=!1,u||c.call(e)},g=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",m)};return s(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),o(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),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||_,a=Object.keys||k,s=Function.prototype.bind||O;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 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?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,a=I(e,r),s=0;s<r;++s)a[s].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].call(n,r)}function p(e,t,n,r,a){if(t)e.call(n,r,a);else for(var s=e.length,o=I(e,s),i=0;i<s;++i)o[i].call(n,r,a)}function f(e,t,n,r,a,s){if(t)e.call(n,r,a,s);else for(var o=e.length,i=I(e,o),c=0;c<o;++c)i[c].call(n,r,a,s)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].apply(n,r)}function g(e,t,n,a){var s,o,i;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),i=o[t]):(o=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=a?[n,i]:[i,n]:a?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){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=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},a=s.call(y,r);return a.listener=n,r.wrapFn=a,a}function b(e,t,n){var r=e._events;if(!r)return[];var a=r[t];return a?"function"==typeof a?n?[a.listener||a]:[a]:n?S(a):I(a,a.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,a=e.length;r<a;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 S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(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 O(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"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}}):o.defaultMaxListeners=c,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 d(this)},o.prototype.emit=function(e){var t,n,r,a,s,o,i="error"===e;if(o=this._events)i=i&&null==o.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=o[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(a=new Array(r-1),s=1;s<r;s++)a[s-1]=arguments[s];m(n,l,this,a)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(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,a,s,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(a=this._events))return this;if(!(n=a[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete a[e],a.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():C(n,s),1===n.length&&(a[e]=n[0]),a.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,s;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,i=a(n);for(s=0;s<i.length;++s)"removeListener"!==(o=i[s])&&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(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);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){
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  n.read=function(e,t,n,r,a){var s,o,i=8*a-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?a-1:0,h=n?-1:1,p=e[t+u];for(u+=h,s=p&(1<<-d)-1,p>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,r),s-=l}return(p?-1:1)*o*Math.pow(2,s-r)},n.write=function(e,t,n,r,a,s){var o,i,c,l=8*s-a-1,d=(1<<l)-1,u=d>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(i=0,o=d):o+u>=1?(i=(t*c-1)*Math.pow(2,a),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,a),o=0));a>=8;e[n+p]=255&i,p+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+p]=255&o,p+=f,o/=256,l-=8);e[n+p-f]|=128*m}},{}],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 a=r.leftChild,s=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=s,t&&(t.brother=r),this.parent=r,this.brother=s,this.leftChild=n,this.rightChild=a,s&&(s.parent=r,s.brother=this),n&&(n.parent=this,n.brother=a),a&&(a.parent=this,a.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,a=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=a,n.rightChild=this,t&&(t.brother=n),a&&(a.parent=n,a.brother=this),this.parent=n,this.brother=a,this.leftChild=s,this.rightChild=r,s&&(s.parent=this,s.brother=r),r&&(r.parent=this,r.brother=s),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,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function a(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,o=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){s=i=o=c=l=d=0,h.call(this,a.bucketSize),d=0},this.front=function(){return n[s][o]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==i){for(l=o;l<a.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<i;++l)for(var r=0;r<a.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=o;l<=c;++l)e(n[s][l],t++)}};var u=function(e){var t=s*a.bucketSize+o,n=t+e,r=i*a.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/a.bucketSize),curNodePointerIndex:n%a.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,a=t.curNodePointerIndex;return n[r][a]},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*a.sigma,u=Math.max(Math.ceil(r/a.bucketSize),2),h=0;h<u;++h)t.push(new Array(a.bucketSize));var p=Math.ceil(e/a.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),m=f,g=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<a.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){m=f+h,g=y;break}if(this.empty())break}n=t,s=f,o=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===a.bucketSize-1&&h.call(this,this.size()),c<a.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:s<i&&(--i,c=a.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),a=r.curNodeBucketIndex,s=r.curNodePointerIndex;n[a][s]=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 a=[],s=e;s<d;++s)a.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);a.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(s===i){for(var t=o;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=o;t<a.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<i;++t)for(var r=0;r<a.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===s&&0===o&&h.call(this,this.size()),o>0?--o:s>0&&(--s,o=a.bucketSize-1)),++d,n[s][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<a.bucketSize-1?++o:s<i&&(++s,o=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 s=Math.ceil(r/a.bucketSize),o=0;o<s;++o)n.push(new Array(a.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(s!==i)return[3,5];t=o,r.label=1;case 1:return t<=c?[4,n[s][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<a.bucketSize?[4,n[s][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=s+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<a.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=a.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var o=r*a.sigma;l=Math.ceil(o/a.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(a.bucketSize));var d=Math.ceil(r/a.bucketSize);s=Math.floor(l/2)-Math.floor(d/2),i=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),a.sigma=3,a.bucketSize=5e3,Object.freeze(a),n.default=a},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=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 s=e("../LinkList/LinkList"),o=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,s="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var o=a(s),i=o.next();!i.done;i=o.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.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 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,a){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new s.default([{key:l,value:h}])}else if(r instanceof o.default){var p=new s.default,f=new s.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[a]=new o.default(p):p.size()&&(t[a]=p),f.size()>i.untreeifyThreshold?t[a+e]=new o.default(f):f.size()&&(t[a+e]=f)}else{var m=new s.default,g=new s.default;r.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[a]=m),g.size()&&(t[a+e]=g)}d[a].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 s.default){try{for(var m=a(d[p]),g=m.next();!g.done;g=m.next()){var y=g.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new o.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new s.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,s=n(e)&u-1;if(d[s]){if(d[s]instanceof o.default)return d[s].getElementByKey(e);try{for(var i=a(d[s]),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 o.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new s.default(d[c]));else{var p=-1;try{for(var f=a(d[c]),m=f.next();!m.done;m=f.next()){var g=m.value;if(++p,g.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{m&&!m.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,s=n(e)&u-1;if(!d[s])return!1;if(d[s]instanceof o.default)return d[s].find(e);try{for(var i=a(d[s]),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,s,o,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]),o=void 0,t=a(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 s=r.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.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 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,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=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 s=e("../Set/Set"),o=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,a){if(!r.empty()){if(r instanceof o.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new o.default([c])}else if(r instanceof s.default){var l=new o.default,h=new o.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[a]=new s.default(l):l.size()&&(t[a]=l),h.size()>i.untreeifyThreshold?t[a+e]=new s.default(h):h.size()&&(t[a+e]=h)}else{var p=new o.default,f=new o.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[a]=p),f.size()&&(t[a+e]=f)}d[a].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 o.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new s.default(d[t]))}else d[t].insert(e);var a=d[t].size();l+=a-r}else d[t]=new o.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 s.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new o.default(d[t]));var a=d[t].size();l+=a-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,s,o,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]),o=void 0,t=a(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 s=r.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.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 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,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=o=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=s,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=s;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=s;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,a=t.next;a.pre=r,r.next=a,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var r=t.pre,a=t.next;a&&(a.pre=r),r&&(r.next=a),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 a(e);o?(o.next=t,t.pre=o,o=t):s=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(s===o?s=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=s;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=s,i=1;i<e;++i){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 c=o.next;for(n+=r;r--;)o.next=new a(t),o.next.pre=o,o=o.next;o.next=c,c&&(c.pre=o)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=o,r=0;e&&t&&2*r<n;){var a=e.value;e.value=t.value,t.value=a,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=s;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=s;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 a(e);s?(t.next=s,s.pre=t,s=t):s=o=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===o?s=o=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,r=s;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===s)t.pushFront(e),r=s;else{++n;var i=r.pre;i&&(i.next=new a(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=s,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(s),n.default=s},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=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 s=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,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=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 s=a(this),o=s.next();!o.done;o=s.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}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 s=a(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}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!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=s.default.TreeNodeColorType.black},m=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(),--o,i.color=s.default.TreeNodeColorType.black},g=function(e,t){return!(!e||void 0===e.key)&&(!!g(e.leftChild,t)||!!t(e)||g(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;g(i,(function(n){return e===t?(m(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)&&m(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 s.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 s.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!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,v(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),v(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};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,i.key=e,i.value=n,void(i.color=s.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++o,r.key=e,r.value=n,v(r),i.color=s.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,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,a(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(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,a=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var a=n[e];n[e]=n[t],n[t]=a},s=function(e){if(e<0||e>=r)throw new Error("unknown error");var s=2*e+1,o=2*e+2;s<r&&t(n[e],n[s])>0&&a(e,s),o<r&&t(n[e],n[o])>0&&a(e,o)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var s=e,o=2*s+1;o<r;){var i=o+1,c=o;if(i<r&&t(n[o],n[i])>0&&(c=i),t(n[s],n[c])<=0)break;a(s,c),o=2*(s=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 a=r-1;a>0;){var o=Math.floor((a-1)/2);if(t(n[o],e)<=0)break;s(o),a=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var a=0;a<this.size();){var s=2*a+1,o=2*a+2;if(s>=this.size())break;var i=s;if(o<this.size()&&t(n[s],n[o])>0&&(i=o),t(n[i],e)>=0)break;n[a]=n[i],a=i}n[a]=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 a(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(a),n.default=a},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=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 s=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,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=s.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 s=a(this),o=s.next();!o.done;o=s.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}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 s=a(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}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!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=s.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(),--o,i.color=s.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(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=m(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 s.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 s.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!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,f(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),f(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),f(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};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,i.key=e,void(i.color=s.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,f(n),i.color=s.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?m(e.leftChild,n):r>0?m(e.rightChild,n):e}};this.find=function(e){var n=m(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var g=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 g(e.rightChild,n);var a=g(e.leftChild,n);return void 0!==a?a:e.key}};this.lowerBound=function(e){return g(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 a=v(e.rightChild,n);return void 0!==a?a: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,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,a(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(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,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,a,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){a={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(a)throw a.error}}return o},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,a=0,s=t.length;a<s;a++)!r&&a in t||(r||(r=Array.prototype.slice.call(t,0,a)),r[a]=t[a]);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 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,s([e,0],a(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,o(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 a=e("./Stack/Stack");n.Stack=a.default;var s=e("./Queue/Queue");n.Queue=s.default;var o=e("./LinkList/LinkList");n.LinkList=o.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"),a=Symbol("max"),s=Symbol("length"),o=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 m{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[a]=e.max||1/0;const t=e.length||f;if(this[o]="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[a]=e||1/0,v(this)}get max(){return this[a]}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[o]&&(this[o]=e,this[s]=0,this[u].forEach((e=>{e.length=this[o](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[s]}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[s]=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[o](t,e);if(this[h].has(e)){if(i>this[a])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,o.value)),o.now=r,o.maxAge=n,o.value=t,this[s]+=i-o.length,o.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[a]?(this[l]&&this[l](e,t),!1):(this[s]+=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 g(this,e,!0)}peek(e){return g(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],a=r.e||0;if(0===a)this.set(r.k,r.v);else{const e=a-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(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[s]>e[a])for(let t=e[u].tail;e[s]>e[a]&&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[s]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,a){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=a||0}}const C=(e,t,n,r)=>{let a=n.value;y(e,a)&&(b(e,n),e[i]||(a=void 0)),a&&t.call(r,a.value,a.key,e)};t.exports=m},{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((a=>[0,1].map((s=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(a?n.DUP_MASK:0)|r<<n.QOS_SHIFT|s,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"),a=e("events");function s(e,t){const n=new o;return r(e,n,t),n.concat()}class o extends a{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 a,s=0;for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?t[a]=r[a].length:t[a]=n.byteLength(r[a]),e+=t[a];const o=n.allocUnsafe(e);for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?(r[a].copy(o,s),s+=t[a]):(o.write(r[a],s),s+=t[a]);return o}}t.exports=s}).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={},a=e.isBuffer(e.from([1,2]).subarray(0,1));function s(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]=s(e)}function i(t){const n=4;let r=0,s=0;const o=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),o.writeUInt8(r,s++)}while(t>0&&s<n);return t>0&&(s=0),a?o.subarray(0,s):o.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:o,generateNumber:s,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"),a=e("events"),s=e("./packet"),o=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends a{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 s,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=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),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 a={},s=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(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.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(a.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,a.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,a.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,a.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,i("_parseConnect: packet.clientId: %s",s.clientId),a.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,i("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(a.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));s.username=r,i("_parseConnect: packet.username: %s",s.username)}if(a.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,i("_parseConnect: complete"),s}_parseConnack(){i("_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)}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,a,s,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&o.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),a=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=a):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,a=1,s=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++),s+=a*(n&o.VARBYTEINT_MASK),a*=128,0==(n&o.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:s}:s),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=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 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 s,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"),a=n.allocUnsafe(0),s=n.from([0]),o=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=o.cache,d=o.generateNumber,u=o.generateCache,h=o.genBufVariableByteInt,p=o.generate4ByteBuffer;let f=j,m=!0;function g(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),m&&(m=!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 S(e,t,n);case"unsubscribe":return _(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return O(e,t);case"disconnect":return T(e,t,n);case"auth":return E(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,a){const s=e||{},o=s.protocolId||"MQTT";let i=s.protocolVersion||4;const c=s.will;let l=s.clean;const d=s.keepalive||0,u=s.clientId||"",h=s.username,p=s.password,m=s.properties;void 0===l&&(l=!0);let g=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=o.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(g+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))g+=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(g+=2,g+=1,5===i){var y=q(t,m);if(!y)return!1;g+=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(g+=n.byteLength(c.topic)+2,g+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?g+=n.byteLength(c.payload):g+=c.payload.length}var v={};if(5===i){if(!(v=q(t,c.properties)))return!1;g+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,g+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!K(p))return t.emit("error",new Error("Invalid password")),!1;g+=F(p)+2}t.write(r.CONNECT_HEADER),R(t,g),D(t,o),s.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,a){const o=a?a.protocolVersion:4,i=e||{},c=5===o?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===o){if(u=q(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),R(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const o=s?s.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||a,p=i.messageId,m=i.properties;let g=0;if("string"==typeof u)g+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;g+=u.length+2}if(n.isBuffer(h)?g+=h.length:g+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(g+=2);let y=null;if(5===o){if(y=q(t,m),!y)return!1;g+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),R(t,g),f(t,F(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,a){const s=a?a.protocolVersion:4,o=e||{},i=o.cmd||"puback",c=o.messageId,l=o.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=o.reasonCode,h=o.properties;let p=5===s?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let m=null;if(5===s&&"object"==typeof h){if(m=N(t,h,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[i][d][l][0]),R(t,p),f(t,c),5===s&&t.write(n.from([u])),null!==m&&m.write(),!0}function I(e,t,a){c("subscribe: packet: ");const s=a?a.protocolVersion:4,o=e||{},i=o.dup?r.DUP_MASK:0,l=o.messageId,d=o.subscriptions,u=o.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===s){if(p=q(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,a=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof a)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){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]),R(t,h),f(t,l),null!==p&&p.write();let m=!0;for(const e of d){const a=e.topic,o=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,a),d=r.SUBSCRIBE_OPTIONS_QOS[o],5===s&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.granted,l=o.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===s){if(u=N(t,l,a,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),R(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.unsubscriptions,d=o.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===s){if(h=q(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),R(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,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.granted,d=o.properties,u=o.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){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 m=null;if(5===s){if(m=N(t,d,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[u][h][c][0]),R(t,p),f(t,i),null!==m&&m.write(),5===s&&t.write(n.from(l)),!0}function O(e,t,n){return t.write(r.EMPTY[e.cmd])}function T(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0,d=null;if(5===s){if(d=N(t,c,a,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),R(t,l),5===s&&t.write(n.from([i])),null!==d&&d.write(),!0}function E(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,c,a,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),R(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(g,"cacheNumbers",{get:()=>f===j,set(e){e?(l&&0!==Object.keys(l).length||(m=!0),f=j):(m=!1,f=U)}});const A={};function R(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=A[t];return n||(n=h(t),t<16384&&(A[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 M(e,t,n){P(e,t),P(e,n)}function j(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function U(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function x(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 q(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){L(e,{},0)}};let a=0;function s(t,a){let s=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=2;break;case"int8":if("number"!=typeof a||a<0||a>255)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=2;break;case"binary":if(a&&null===a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=1+n.byteLength(a)+2;break;case"int16":if("number"!=typeof a||a<0||a>65535)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=3;break;case"int32":if("number"!=typeof a||a<0||a>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=5;break;case"var":if("number"!=typeof a||a<0||a>268435455)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=1+n.byteLength(h(a));break;case"string":if("string"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=3+n.byteLength(a.toString());break;case"pair":if("object"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=Object.getOwnPropertyNames(a).reduce(((e,t)=>{const r=a[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(a[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${a}`)),!1}return s}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=s(e,o[t]),!r)return!1;n+=r}else{if(r=s(e,o),!r)return!1;n=r}if(!n)return!1;a+=n}return{length:n.byteLength(h(a))+a,write(){L(e,t,a)}}}function N(e,t,n,r){const a=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=q(e,t);if(s)for(;r+o.length>s;){const n=a.shift();if(!n||!t[n])return!1;delete t[n],o=q(e,t)}return o}function B(e,t,a){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+a]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([a]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,a);break;case"int16":e.write(n.from([r.properties[t]])),f(e,a);break;case"int32":e.write(n.from([r.properties[t]])),x(e,a);break;case"var":e.write(n.from([r.properties[t]])),R(e,a);break;case"string":e.write(n.from([r.properties[t]])),P(e,a);break;case"pair":Object.getOwnPropertyNames(a).forEach((s=>{const o=a[s];Array.isArray(o)?o.forEach((a=>{e.write(n.from([r.properties[t]])),M(e,s.toString(),a.toString())})):(e.write(n.from([r.properties[t]])),M(e,s.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${a}`)),!1}}function L(e,t,n){R(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 F(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}t.exports=g}).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,a=60*r,s=60*a,o=24*s,i=7*o,c=365.25*o;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*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;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>=o?Math.round(e/o)+"d":t>=s?Math.round(e/s)+"h":t>=a?Math.round(e/a)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=s?h(e,t,s,"hour"):t>=a?h(e,t,a,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var a=t>=1.5*n;return Math.round(e/n)+" "+r+(a?"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,a=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function o(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))),a("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},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return a("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),a("alloc():"+t),t},i.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),a("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,a("use():"+e),!0;if(n.high===e)return--n.high,a("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new o(r,e-1)),a("use():"+e),!0}return a("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void s("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 s("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)}a("free():"+e)},i.prototype.clear=function(){a("clear()"),this.ss.clear(),this.ss.insert(new o(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 a(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(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(a),t.exports.strict=r(s),a.proto=a((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return a(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,a){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,o,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,a)}));default:for(s=new Array(i-1),o=0;o<s.length;)s[o++]=arguments[o];return e.nextTick((function(){t.apply(null,s)}))}}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,a,s=t.exports={};function o(){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===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 l(e){if(a===clearTimeout)return clearTimeout(e);if((a===i||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(e);try{return a(e)}catch(t){try{return a.call(null,e)}catch(t){return a.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{a="function"==typeof clearTimeout?clearTimeout:i}catch(e){a=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&m())}function m(){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 g(e,t){this.fun=e,this.array=t}function y(){}s.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 g(e,t)),1!==u.length||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var a="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(r=o);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,m=72,g=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,S=Math.floor,_=String.fromCharCode;function k(e){throw new RangeError(C[e])}function O(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function T(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+O((e=e.replace(w,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],a=0,s=e.length;a<s;)(t=e.charCodeAt(a++))>=55296&&t<=56319&&a<s?56320==(64512&(n=e.charCodeAt(a++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),a--):r.push(t);return r}function A(e){return O(e,(function(e){var t="";return e>65535&&(t+=_((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=_(e)})).join("")}function R(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 M(e,t,n){var r=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>I*h>>1;r+=d)e=S(e/I);return S(r+(I+1)*e/(e+p))}function j(e){var t,n,r,a,s,o,i,c,p,f,v=[],b=e.length,w=0,C=g,I=m;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(a=n>0?n+1:0;a<b;){for(s=w,o=1,i=d;a>=b&&k("invalid-input"),((c=R(e.charCodeAt(a++)))>=d||c>S((l-w)/o))&&k("overflow"),w+=c*o,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)o>S(l/(f=d-p))&&k("overflow"),o*=f;I=M(w-s,t=v.length+1,0==s),S(w/t)>l-C&&k("overflow"),C+=S(w/t),w%=t,v.splice(w++,0,C)}return A(v)}function U(e){var t,n,r,a,s,o,i,c,p,f,v,b,w,C,I,O=[];for(b=(e=E(e)).length,t=g,n=0,s=m,o=0;o<b;++o)(v=e[o])<128&&O.push(_(v));for(r=a=O.length,a&&O.push(y);r<b;){for(i=l,o=0;o<b;++o)(v=e[o])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,o=0;o<b;++o)if((v=e[o])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=s?u:p>=s+h?h:p-s));p+=d)I=c-f,C=d-f,O.push(_(P(f+I%C,0))),c=S(I/C);O.push(_(P(c,0))),s=M(n,w,r==a),n=0,++r}++n,++t}return O.join("")}function x(e){return T(e,(function(e){return v.test(e)?j(e.slice(4).toLowerCase()):e}))}function D(e){return T(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:E,encode:A},decode:j,encode:U,toASCII:D,toUnicode:x},a&&s)if(t.exports==a)s.exports=i;else for(c in i)i.hasOwnProperty(c)&&(a[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==Dt?Dt:"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,s){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,m=e[d].replace(i,"%20"),g=m.indexOf(n);g>=0?(u=m.substr(0,g),h=m.substr(g+1)):(u=m,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(o,p)?a(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var a=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?s(o(e),(function(o){var i=encodeURIComponent(r(o))+n;return a(e[o])?s(e[o],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(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 a={};function s(e,t,n){function s(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,s(t,n,r))||this}return r(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,a[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 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)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,a;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))a="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var s=l(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(s," ").concat(r," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=a},{}],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 a=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,a);for(var o=r(s.prototype),i=0;i<o.length;i++){var c=o[i];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);a.call(this,e),s.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=a;var r=e("./_stream_transform");function a(e){if(!(this instanceof a))return new a(e);r.call(this,e)}e("inherits")(a,r),a.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var a;t.exports=E,E.ReadableState=T,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},o=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,m,g=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,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(E,o);var _=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function O(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 T(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.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new g,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 E(t){if(a=a||e("./_stream_duplex"),!(this instanceof E))return new E(t);var n=this instanceof a;this._readableState=new T(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 A(e,t,n,r,a){u("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,x(e,o);else if(a||(s=P(o,t)),s)_(e,s);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)o.endEmitted?_(e,new S):R(e,o,t,!0);else if(o.ended)_(e,new C);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?R(e,o,t,!1):N(e,o)):R(e,o,t,!1)}else r||(o.reading=!1,N(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function R(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)),N(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(E.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=y.destroy,E.prototype._undestroy=y.undestroy,E.prototype._destroy=function(e,t){t(e)},E.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),A(this,e,t,!1,n)},E.prototype.unshift=function(e){return A(this,e,null,!0,!1)},E.prototype.isPaused=function(){return!1===this._readableState.flowing},E.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,a="";null!==r;)a+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==a&&this._readableState.buffer.push(a),this._readableState.length=a.length,this};var M=1073741824;function j(e){return e>=M?e=M:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function U(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=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(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,q(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(q,e))}function q(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,z(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(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function L(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,z(e))}}function F(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 K(e){u("readable nexttick read 0"),e.read(0)}function $(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(Q,e,t))}function Q(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),z(e),t.flowing&&!t.reading&&e.read(0)}function z(e){var t=e._readableState;for(u("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 H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(J,t,e))}function J(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 W(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}E.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=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,a=t.needReadable;return u("need readable",a),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",a=!0),t.ended||t.reading?u("reading or ended",a=!1):a&&(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=U(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&&H(this)),null!==r&&this.emit("data",r),r},E.prototype._read=function(e){_(this,new I("_read()"))},E.prototype.pipe=function(e,t){var r=this,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}a.pipesCount+=1,u("pipe count=%d opts=%j",a.pipesCount,t);var o=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()}a.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",i);var l=L(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),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,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===a.pipesCount&&a.pipes===e||a.pipesCount>1&&-1!==W(a.pipes,e))&&!d&&(u("false write response, pause",a.awaitDrain),a.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===s(e,"error")&&_(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),O(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",r),a.flowing||(u("pipe resume"),r.resume()),e},E.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,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<a;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=W(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},E.prototype.on=function(e,t){var r=o.prototype.on.call(this,e,t),a=this._readableState;return"data"===e?(a.readableListening=this.listenerCount("readable")>0,!1!==a.flowing&&this.resume()):"readable"===e&&(a.endEmitted||a.readableListening||(a.readableListening=a.needReadable=!0,a.flowing=!1,a.emittedReadable=!1,u("on readable",a.length,a.reading),a.length?D(this):a.reading||n.nextTick(K,this))),r},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var r=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(F,this),r},E.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(F,this),t},E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},E.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},E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var a 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(a){u("wrapped data"),n.decoder&&(a=n.decoder.write(a)),n.objectMode&&null==a||(n.objectMode||a&&a.length)&&(t.push(a)||(r=!0,e.pause()))})),e)void 0===this[a]&&"function"==typeof e[a]&&(this[a]=function(t){return function(){return e[t].apply(e,arguments)}}(a));for(var s=0;s<k.length;s++)e.on(k[s],this.emit.bind(this,k[s]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(E.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=V,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(E.from=function(t,n){return void 0===m&&(m=e("./internal/streams/from")),m(E,t,n)})}).call(this)}).call(this,e("_process"),void 0!==Dt?Dt:"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,a=r.ERR_METHOD_NOT_IMPLEMENTED,s=r.ERR_MULTIPLE_CALLBACK,o=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 s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.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 o;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 a("_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 a=this._readableState;(r.needTransform||a.needReadable||a.length<a.highWaterMark)&&this._read(a.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 a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q(t,e)}}var s;t.exports=T,T.WritableState=O;var o={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,m=e("../errors").codes,g=m.ERR_INVALID_ARG_TYPE,y=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_MULTIPLE_CALLBACK,b=m.ERR_STREAM_CANNOT_PIPE,w=m.ERR_STREAM_DESTROYED,C=m.ERR_STREAM_NULL_VALUES,I=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,_=p.errorOrDestroy;function k(){}function O(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.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 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){x(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 a(this)}function T(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(T,this))return new T(t);this._writableState=new O(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 E(e,t){var r=new I;_(e,r),n.nextTick(t,r)}function A(e,t,r,a){var s;return null===r?s=new C:"string"==typeof r||t.objectMode||(s=new g("chunk",["string","Buffer"],r)),!s||(_(e,s),n.nextTick(a,s),!1)}function R(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function P(e,t,n,r,a,s){if(!n){var o=R(t,r,a);r!==o&&(n=!0,a="buffer",r=o)}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:a,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else M(e,t,!1,i,r,a,s);return c}function M(e,t,n,r,a,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(a,t.onwrite):e._write(a,s,t.onwrite),t.sync=!1}function j(e,t,r,a,s){--t.pendingcb,r?(n.nextTick(s,a),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,a)):(s(a),e._writableState.errorEmitted=!0,_(e,a),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,a=r.sync,s=r.writecb;if("function"!=typeof s)throw new v;if(U(r),t)j(e,r,a,t,s);else{var o=B(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||N(e,r),a?n.nextTick(D,e,r,o,s):D(e,r,o,s)}}function D(e,t,n,r){n||q(e,t),t.pendingcb--,r(),K(e,t)}function q(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,s=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var i=0,c=!0;n;)s[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;s.allBuffers=c,M(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(M(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 B(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function L(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function F(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(L,e,t)))}function K(e,t){var n=B(t);if(n&&(F(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 $(e,t,r){t.ending=!0,K(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function Q(e,t,n){var r=e.entry;for(e.entry=null;r;){var a=r.callback;t.pendingcb--,a(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(T,i),O.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(O.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(T,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===T&&e&&e._writableState instanceof O}})):h=function(e){return e instanceof this},T.prototype.pipe=function(){_(this,new b)},T.prototype.write=function(e,t,n){var r=this._writableState,a=!1,s=!r.objectMode&&u(e);return s&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?E(this,n):(s||A(this,r,e,n))&&(r.pendingcb++,a=P(this,r,s,e,t,n)),a},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},T.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 S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),T.prototype._write=function(e,t,n){n(new y("_write()"))},T.prototype._writev=null,T.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||$(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=p.destroy,T.prototype._undestroy=p.undestroy,T.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==Dt?Dt:"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 a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),o=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[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(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((a(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,a=this[d];if(a)r=new Promise(g(a,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(p(s,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),a(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,(a(t={},h,{value:e,writable:!0}),a(t,o,{value:null,writable:!0}),a(t,i,{value:null,writable:!0}),a(t,c,{value:null,writable:!0}),a(t,l,{value:e._readableState.endEmitted,writable:!0}),a(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[o]=null,n[i]=null,e(p(r,!1))):(n[o]=e,n[i]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[o]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[o];null!==r&&(n[d]=null,n[o]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",m.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 a(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){s(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 s(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 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(){o(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 a=t.data,s=e>a.length?a.length:e;if(s===a.length?r+=a:r+=a.slice(0,e),0==(e-=s)){s===a.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=a.slice(s));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 a=n.data,s=e>a.length?a.length:e;if(a.copy(t,t.length-e,0,s),0==(e-=s)){s===a.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(s));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,a({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=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(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?s._writableState?s._writableState.errorEmitted?e.nextTick(a,s):(s._writableState.errorEmitted=!0,e.nextTick(r,s,t)):e.nextTick(r,s,t):n?(e.nextTick(a,s),n(t)):e.nextTick(a,s)})),this)}function r(e,t){o(e,t),a(e)}function a(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){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 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:s,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 a(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];e.apply(this,r)}}}function s(){}function o(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=a(n||s);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)},m=function(t){n.call(e,t)},g=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 o(e)?(e.on("complete",h),e.on("abort",g),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",m),e.on("close",g),function(){e.removeListener("complete",h),e.removeListener("abort",g),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",m),e.removeListener("close",g)}}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 a(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,o=s.ERR_MISSING_ARGS,i=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,s,o){o=a(o);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:s},(function(e){if(e)return o(e);c=!0,o()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(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,a=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var s=t.map((function(e,n){var o=n<t.length-1;return d(e,o,n>0,(function(e){r||(r=e),e&&s.forEach(u),o||(s.forEach(u),a(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 a(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var o=a(t,s,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new r(s?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../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 a(){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=a},{}],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?a(e):e.proto?s:r;function t(e,t){for(var r=Object.keys(e),a=new Array(r.length),s=0;s<r.length;s++){var o=r[s],i=e[o];"object"!=typeof i||null===i?a[o]=i:i instanceof Date?a[o]=new Date(i):ArrayBuffer.isView(i)?a[o]=n(i):a[o]=t(i)}return a}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 a={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var o=e[s];"object"!=typeof o||null===o?a[s]=o:o instanceof Date?a[s]=new Date(o):o instanceof Map?a[s]=new Map(t(Array.from(o),r)):o instanceof Set?a[s]=new Set(t(Array.from(o),r)):ArrayBuffer.isView(o)?a[s]=n(o):a[s]=r(o)}return a}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var r={};for(var a in e){var o=e[a];"object"!=typeof o||null===o?r[a]=o:o instanceof Date?r[a]=new Date(o):o instanceof Map?r[a]=new Map(t(Array.from(o),s)):o instanceof Set?r[a]=new Set(t(Array.from(o),s)):ArrayBuffer.isView(o)?r[a]=n(o):r[a]=s(o)}return r}}function a(e){var t=[],r=[];return e.proto?o:s;function a(e,a){for(var s=Object.keys(e),o=new Array(s.length),i=0;i<s.length;i++){var c=s[i],l=e[c];if("object"!=typeof l||null===l)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=n(l);else{var d=t.indexOf(l);o[c]=-1!==d?r[d]:a(l)}}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return a(e,s);if(e instanceof Map)return new Map(a(Array.from(e),s));if(e instanceof Set)return new Set(a(Array.from(e),s));var o={};for(var i in t.push(e),r.push(o),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)o[i]=c;else if(c instanceof Date)o[i]=new Date(c);else if(c instanceof Map)o[i]=new Map(a(Array.from(c),s));else if(c instanceof Set)o[i]=new Set(a(Array.from(c),s));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?r[l]:s(c)}}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 a(e,o);if(e instanceof Map)return new Map(a(Array.from(e),o));if(e instanceof Set)return new Set(a(Array.from(e),o));var s={};for(var i in t.push(e),r.push(s),e){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(a(Array.from(c),o));else if(c instanceof Set)s[i]=new Set(a(Array.from(c),o));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?r[l]:o(c)}}return t.pop(),r.pop(),s}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
4
4
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
5
- var r=e("buffer"),a=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return a(e,t,n)}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=o),o.prototype=Object.create(a.prototype),s(a,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return a(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=a(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 a(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(a(t)):null}function a(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,a=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 s(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=s(e);if("string"!=typeof t&&(r.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,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 a=c(t[r]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(e.lastNeed=a-2),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(2===a?a=0:e.lastNeed=a-3),a):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 m(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 g(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"),a=e("./util");function s(){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=S,n.format=C,n.Url=s;var o=/^([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}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={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&&a.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return a.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!a.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<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=o.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var O,T,E=-1,A=0;A<h.length;A++)-1!==(R=C.indexOf(h[A]))&&(-1===E||R<E)&&(E=R);for(-1!==(T=-1===E?C.lastIndexOf("@"):C.lastIndexOf("@",E))&&(O=C.slice(0,T),C=C.slice(T+1),this.auth=decodeURIComponent(O)),E=-1,A=0;A<u.length;A++){var R;-1!==(R=C.indexOf(u[A]))&&(-1===E||R<E)&&(E=R)}-1===E&&(E=C.length),this.host=C.slice(0,E),C=C.slice(E),this.parseHost(),this.hostname=this.hostname||"";var P="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!P)for(var M=this.hostname.split(/\./),j=(A=0,M.length);A<j;A++){var U=M[A];if(U&&!U.match(f)){for(var x="",D=0,q=U.length;D<q;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var N=M.slice(0,A),B=M.slice(A+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(C="/"+B.join(".")+C),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+F,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(A=0,j=d.length;A<j;A++){var $=d[A];if(-1!==C.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),C=C.split($).join(Q)}}var z=C.indexOf("#");-1!==z&&(this.hash=C.substr(z),C=C.slice(0,z));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){F=this.pathname||"";var H=this.search||"";this.path=F+H}return this.href=this.format(),this},s.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||"",s=!1,o="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&a.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(a.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),o=0;o<r.length;o++){var i=r[o];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 m=n.pathname||"",g=n.search||"";n.path=m+g}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,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.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]||""===S[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,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!a.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),n.search=e.search,n.query=e.query,a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],O=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,T=0,E=S.length;E>=0;E--)"."===(k=S[E])?S.splice(E,1):".."===k?(S.splice(E,1),T++):T&&(S.splice(E,1),T--);if(!C&&!I)for(;T--;T)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),O&&"/"!==S.join("/").substr(-1)&&S.push("");var A,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=R?"":S.length?S.shift():"",(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),(C=C||n.host&&S.length)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.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},s.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 a(){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 a}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!==Dt?Dt:"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),a=t[t.length-1];return"function"==typeof r&&r!==a&&Object.keys(a).forEach((function(e){r[e]=a[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=a;var r=Object.prototype.hasOwnProperty;function a(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var a in n)r.call(n,a)&&(e[a]=n[a])}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,a=arguments.length;n<a;n++)t.push(arguments[n]);return t}function a(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 s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(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++)s(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,a=this.head;null!==a;)n.push(e.call(t,a.value,this)),a=a.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,a=this.tail;null!==a;)n.push(e.call(t,a.value,this)),a=a.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 a=0;null!==r;a++)n=e(n,r.value,a),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 a=this.length-1;null!==r;a--)n=e(n,r.value,a),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 a=0,s=this.head;null!==s&&a<e;a++)s=s.next;for(;null!==s&&a<t;a++,s=s.next)n.push(s.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 a=this.length,s=this.tail;null!==s&&a>t;a--)s=s.prev;for(;null!==s&&a>e;a--,s=s.prev)n.push(s.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,s=this.head;null!==s&&r<e;r++)s=s.next;var o=[];for(r=0;s&&r<t;r++)o.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=a(this,s,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);var Lt=qt(Bt.exports);class Ft{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 Kt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ft},$t=()=>b.default.v4().toString();let Qt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=$t(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:a})=>{a.tabId!==e&&("startup"===a.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Qt}),"identify"===a.type&&void 0!==a.tabIndex&&a.tabId&&(t[a.tabId]=a.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Qt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const zt=async()=>{var e;const t=`${null!==(e=Ee().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(Kt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${$t()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{Kt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Vt=()=>{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:$}},Ht=1e3;var Jt;!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"}(Jt||(Jt={}));const Wt=e=>{let t,n="disconnected";const r=new Set,a=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await zt()}_${e}_${Qt}`)(n.userId);return a("connecting"),t&&(a("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Lt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Ht,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=Ht,a("connected"),(()=>{const e=[Ct(gt()),Ct(yt()),Ct(vt()),Ct(bt()),Ct(pt(Xe())),Ct(mt()),Ct(wt())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),a("disconnected")}})),t.on("reconnect",(()=>{a("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Ht),8e3)})),t.on("close",(()=>{a("disconnected")})),t.on("disconnect",(()=>{a("disconnected")})),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()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(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 a;if(t||128===(null===(a=r[0])||void 0===a?void 0:a.qos)){const r=t?new Ie(t.message,8e5,"error"):new _e(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)}}},Gt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const a=we[e];if(!a)return;const s=be(a);s&&r.forEach((e=>{(n?Me:Ue)([a,"get",s(e)],e,t)}))}))},Yt=(e,t)=>{const{log:n,cache:r}=Ee(),a=[e,Y,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:a,data:s}),xe([e,"get",t],!0),Me(a,s))};function Zt(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 a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}const Xt=(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(!Ee().cache)return;return(null===(n=Pe(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},en=(e,t,n="userId",r="user")=>{const a=e,s=t,o=a[s],i=Zt(a,["symbol"==typeof s?s:s+""]),c=Xt(o,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function tn(e){return e.map((e=>{var{isMentioned:t}=e,n=Zt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function nn(e){return tn(e)}function rn(e){return tn(e)}const an=e=>{var t,n;return null!==(n=null===(t=Pe(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},sn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Pe(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),on=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:a,messageFeedId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:a,subChannelId:s,data:o,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:[]};Gt(r)},cn=e=>{var t,n;return null!==(n=null===(t=Pe(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},ln=e=>{var t;const n=e.messagePreviewId?cn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Pe(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},dn=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:a,messageFeedId:s,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:a,subChannelId:s,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:[]};Gt(r)};function un(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function hn(e,t,n){Me(["subChannel","get",e],un(t,n))}const pn=(e,t)=>{const{log:n,cache:r}=Ee(),a=[e,Y,t];if(!r)return;n("cache/api/isInTombstone",a);const s=Pe(a),{lifeSpan:o}=me("cache_then_server",18e4);if(s&&pe(s.data,o))throw new Se("Item not found!",400400,"error")},fn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Pe(n))||void 0===t?void 0:t.data,a=Re(["subChannelUnreadInfo","get"]);let s=0,o=!1;if(a&&(null==a?void 0:a.length)>0){const t=null==a?void 0:a.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=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:s,isMentioned:o});return Me(n,i),i},mn=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,a={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};Gt({subChannelUnreadInfo:[a]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{fn(e)}))}},gn=async()=>{const e=Ee();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&&Gt({userMarkers:n},{cachedAt:r}),ot("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}},yn=e=>!0===e&&void 0;function vn(e,t,n){var r,a;if(n)return n.hasMentioned;const s=Ee();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Pe(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:Xe()._id},i=null===(a=Pe(["subChannelMarker","get",be("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return!!i&&i.hasMentioned}const bn=["broadcast","conversation","community"],wn=({channelType:e})=>bn.includes(e);function Cn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:a,creatorId:s,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=Zt(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,a;if(n)return n.unreadCount;const s=Ee();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Pe(["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:Xe()._id},i=null===(a=Pe(["subChannelMarker","get",be("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return vn(t,l)},get isMentioned(){return vn(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:a,subChannelId:l,isUnreadCountSupport:wn({channelType:r})})}function In(e,t,n){var r;const a=(e=>{var t,n,r;const a=null===(n=null===(t=Re(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign(Object.assign({},a),e),{referenceId:null!==(r=a.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:s,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=a,y=Zt(a,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Pe(["message","get",p])),v||(v=Pe(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:s,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:m,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=Ee(),a=Pe(["message","get",e.messageId]),s=(null==a?void 0:a.data.myReactions)||[];Object.assign(e,{myReactions:s});const o=t[0];o&&o.userId===r.userId&&("message.reactionAdded"!==n||s.includes(o.reactionName)||Object.assign(e,{myReactions:[...s,o.reactionName]}),"message.reactionRemoved"===n&&s.includes(o.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const Sn={},_n=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Gt({messages:(r=e).messages.map((e=>In(e,r.reactions)))});const t=n.join("");Sn[t]&&clearTimeout(Sn[t]),Sn[t]=setTimeout((()=>{try{(async e=>{const t=Ee();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:a,userMarkers:s}=n,o=t.cache&&Date.now();t.cache&&Gt({contentMarkers:r,feedMarkers:a,userMarkers:s},{cachedAt:o}),ot("local.feedMarker.fetched",{feedMarkers:a}),ot("local.messageMarker.fetched",{contentMarkers:r}),ot("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:a}=e,s=Zt(e,["messageFeeds"]);return a&&a.length>0&&(null==a||a.forEach((e=>{var t,n;const r=null!==(n=null===(t=Pe(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},a=Zt(Cn(e),["unreadCount","isMentioned"]);hn(e.messageFeedId,r,a)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>In(n,e.reactions,t)))})};function kn(e){var{subChannelId:t,mentionees:n,dataType:r,data:a}=e,s=Zt(e,["subChannelId","mentionees","dataType","data"]);return r===j.IMAGE||r===j.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},a)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:a},s)}function On(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:a,includeDeleted:s,aroundMessageId:o,limit:i,type:c}=e,l=Zt(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:yn(s),options:{sortBy:t,limit:i||Q,around:o}});return r&&(d.includeTags=r),c&&(d.dataType=c),a&&(d.excludeTags=a),d}function Tn(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const En=["broadcast","conversation","community"],An=({channelType:e})=>En.includes(e),Rn=async e=>{const t=e.messageFeeds.filter(An).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Gt({messageFeeds:e.messageFeeds.map((e=>Cn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ee();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:ie(t,"skiplimit")}}}),{paging:a}=r,s=Zt(r,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&mn({feedMarkers:l,userFeedMarkers:i});const d=nn(o),u=rn(i),h=n.cache&&Date.now();n.cache&&Gt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),ot("local.channelMarker.fetched",{userEntityMarkers:d}),ot("local.subChannelMarker.fetched",{userFeedMarkers:u}),ot("local.userMarker.fetched",{userMarkers:c});const p=ce(a.next);return{data:u,cachedAt:h,prevPage:ce(a.previous),nextPage:p}})(t)}catch(e){}}dn(e);const n=e.messageFeeds.map(Cn),r=e.messages.map((e=>In(e))),a=e.users.map(Tn);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:a})};const Pn=async e=>{const t=Ee();t.log("channel/getSubChannel",e),pn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:a}}catch(t){throw ne(null==t?void 0:t.code)&&Yt("subChannel",e),t}};Pn.locally=e=>{const t=Ee();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Pe(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Mn=e=>new Date(e).getTime(),jn=async e=>{var t;let n=null===(t=Pe(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await Pn(e)).data),n},Un=async e=>{const t=await(async()=>Ee().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await jn(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Pe(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Mn(n.createdAt)<=Mn(e.createdAt)})(e)&&(Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),hn(e.subChannelId,h,{lastActivity:s,messagePreviewId:r})):Mn(h.lastActivity)<Mn(s)&&hn(e.subChannelId,h,{lastActivity:s})},xn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Pe(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await jn(l);Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Dn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:a,updatedAt:s,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Mn(n.createdAt)<=Mn(e.createdAt)})(e)){const u=await jn(c);Me(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:a,updatedAt:s,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},qn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await jn(l);Me(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Nn=async e=>{var t,n,r,a;const{channelId:s,subChannelId:o}=e,i=null===(t=Pe(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Pe(["subChannel","get",o]))||void 0===n?void 0:n.data;Me(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Pe(["messagePreviewSubChannel","get",o]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(a=Pe(["subChannel","get",o]))||void 0===a?void 0:a.data;Me(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Bn=["broadcast","conversation","community"],Ln=({type:e})=>Bn.includes(e);function Fn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const a=null===(n=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==a?void 0:a.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=a.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ln(e),messagePreviewId:r})}const Kn=(e,t={isMessagePreviewUpdated:!0})=>{Gt({channels:e.channels.map((e=>Fn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},$n=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ee(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&on(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let a=0;a<t.length;a+=1){const s=["channelUnread","get",t[a].channelId],o=n.find((n=>n.channelId===t[a].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;o&&(c=o.readToSegment,l=o.lastMentionedSegment,i=Math.max(t[a].messageCount-c,0),d=l>c);const u={channelId:t[a].channelId,lastSegment:t[a].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[a].isDeleted||!1};Me(s,u),r.push(u)}ot("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ln).map((({channelInternalId:e})=>e));if(n.length>0){Kn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ee();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:a}=n,s=nn(r),o=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:s,userMarkers:a},{cachedAt:o}),ot("local.channelMarker.fetched",{userEntityMarkers:s}),ot("local.userMarker.fetched",{userMarkers:a}),{data:s,cachedAt:o}})(n)}catch(e){}}}const a=e.channels.map((e=>Fn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ee().cache)return(null===(e=Pe(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(Tn),i=Zt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:a,channelUsers:s})},Qn=async e=>{const t=Ee();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return ot("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},zn=async e=>{const t=Ee(),n=await Qn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:a}=n;mn({feedMarkers:r,userFeedMarkers:a}),t.log("channel/prepareUnreadCountInfo",e.channels)},Vn=(e,t)=>{var n,r,a,s;const o=Ee();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Pe(["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!==(s=null===(a=(e=>{var t;const n={entityId:e,userId:Xe()._id};return null===(t=Pe(["channelMarker","get",be("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===a?void 0:a.hasMentioned)&&void 0!==s&&s},Hn=(e,t)=>{var n,r,a,s,o;const i=Ee();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Pe(["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!==(a=null==t?void 0:t.unreadCount)&&void 0!==a?a:null===(s=(e=>{var t;const n={entityId:e,userId:Xe()._id};return null===(t=Pe(["channelMarker","get",be("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==o?o:0},Jn=e=>{var t;return null===(t=Pe(["channelUnread","get",e]))||void 0===t?void 0:t.data},Wn=e=>{const t=Ee(),n=Zt(e,["messageCount"]);return un(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Jn(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Hn(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Jn(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Vn(n)}})},Gn=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=Pe(n))||void 0===t?void 0:t.data;return r?sn(r):void 0})()}}),Yn=e=>{const t=Ee();t.log("channel/getMyMembership.locally");const n=Pe(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Se("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Zn(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(!Zn(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=>Zn(e[n],t[n])))}const Xn=[];let er=null;const tr=e=>{if(0===Xn.length){const e=Ee();er=st(e,"onChannelCreated","channel.created",(async e=>{const t=await $n(e);Gt(t),Xn.forEach((e=>e(t.channels[0])))}))}return Xn.push(e),()=>(e=>{const t=Xn.indexOf(e);t>-1&&Xn.splice(t,1),0===Xn.length&&(null==er||er())})(e)},nr=[],rr=[],ar=e=>{const t=Ee();if(0===nr.length){const e=async e=>{const t=await $n(e);Gt(t),nr.forEach((e=>e(t.channels[0])))};rr.push(st(t,"onChannelUpdated","channel.updated",e)),rr.push(st(t,"onChannelUpdated","local.channel.updated",(e=>nr.forEach((t=>t(e.channels[0]))))))}return nr.push(e),()=>(e=>{const t=nr.indexOf(e);t>-1&&nr.splice(t,1),0===nr.length&&rr.forEach((e=>e()))})(e)},sr=e=>{const t=Re(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Me(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},or=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Pe(n))||void 0===t?void 0:t.data)&&xe(n)},ir=[];let cr=null;const lr=e=>{if(0===ir.length){const e=Ee(),t=async t=>{const n=await $n(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,a=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)sr(e.channelId),or(e.channelId);else if(a){const t=["channelUnread","get",e.channelId],n=Pe(t);n&&Me(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Gt(n),ir.forEach((e=>e(n.channels[0])))};cr=st(e,"onChannelDeleted","channel.deleted",t)}return ir.push(e),()=>(e=>{const t=ir.indexOf(e);t>-1&&ir.splice(t,1),0===ir.length&&(null==cr||cr())})(e)},dr=[];let ur=null;const hr=e=>{if(0===dr.length){const e=Ee();ur=st(e,"onChannelJoined","channel.joined",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),dr.forEach((e=>e(n[0],r[0])))}))}return dr.push(e),()=>(e=>{const t=dr.indexOf(e);t>-1&&dr.splice(t,1),0===dr.length&&(null==ur||ur())})(e)},pr=[];let fr=null;const mr=e=>{if(0===pr.length){const e=Ee(),t=async t=>{const{userId:n}=Ee(),{channelUsers:r}=t,a=r.some((e=>e.userId===n)),s=await $n(t,{isMessagePreviewUpdated:a}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;a&&s.channels.forEach((e=>{o?(sr(e.channelId),or(e.channelId)):i&&xe(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=s;Gt(s),pr.forEach((e=>e(c[0],l[0])))};fr=st(e,"onChannelLeft","channel.left",t)}return pr.push(e),()=>(e=>{const t=pr.indexOf(e);t>-1&&pr.splice(t,1),0===pr.length&&(null==fr||fr())})(e)},gr=[];let yr=null;const vr=e=>{if(0===gr.length){const e=Ee(),t=async e=>{var t;Ue(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&gr.forEach((e=>e(n)))};yr=st(e,"onChannelMute","channel.setMuted",t)}return gr.push(e),()=>(e=>{const t=gr.indexOf(e);t>-1&&gr.splice(t,1),0===gr.length&&(null==yr||yr())})(e)},br=[];let wr=null;const Cr=e=>{if(0===br.length){const e=Ee();wr=st(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),br.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return br.push(e),()=>(e=>{const t=br.indexOf(e);t>-1&&br.splice(t,1),0===br.length&&(null==wr||wr())})(e)},Ir=[];let Sr=null;const _r=e=>{if(0===Ir.length){const e=Ee();Sr=st(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),Ir.forEach((e=>e(n[0],r[0])))}))}return Ir.push(e),()=>(e=>{const t=Ir.indexOf(e);t>-1&&Ir.splice(t,1),0===Ir.length&&(null==Sr||Sr())})(e)},kr=[];let Or=null;const Tr=e=>{const t=Ee();return Or=st(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await $n(e),{channels:r,channelUsers:a}=n,s=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{sr(e.channelId),or(e.channelId)})),Gt(n),kr.forEach((e=>e(r[0],a.find((e=>"banned"===e.membership)))))})),kr.push(e),()=>(e=>{const t=kr.indexOf(e);t>-1&&kr.splice(t,1),0===kr.length&&(null==Or||Or())})(e)},Er=[];let Ar=null;const Rr=e=>{if(0===Er.length){const e=Ee();Ar=st(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),Er.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return Er.push(e),()=>(e=>{const t=Er.indexOf(e);t>-1&&Er.splice(t,1),0===Er.length&&(null==Ar||Ar())})(e)},Pr=[];let Mr=null;const jr=e=>{if(0===Pr.length){const e=Ee();Mr=st(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;Pr.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Pr.push(e),()=>(e=>{const t=Pr.indexOf(e);t>-1&&Pr.splice(t,1),0===Pr.length&&(null==Mr||Mr())})(e)},Ur=[];let xr=null;const Dr=e=>{if(0===Ur.length){const t=Ee();xr=st(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return Ur.push(e),()=>(e=>{const t=Ur.indexOf(e);t>-1&&Ur.splice(t,1),0===Ur.length&&(null==xr||xr())})(e)},qr=[];let Nr=null;const Br=e=>{if(0===qr.length){const e=Ee(),t=async e=>{var t,n;e.userIds.forEach((t=>Ue(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data,a=null===(n=Pe(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===n?void 0:n.data;r&&a&&qr.forEach((e=>e(r,a)))};Nr=st(e,"onChannelUserMute","channel.setMutedUsers",t)}return qr.push(e),()=>(e=>{const t=qr.indexOf(e);t>-1&&qr.splice(t,1),0===qr.length&&(null==Nr||Nr())})(e)},Lr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=Re(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Gn(e))))}return un(e,{markAsRead:()=>(async e=>{const t=Ee();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:a,userFeedMarkers:s}=n,o=Zt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=nn(a),l=rn(s);return t.cache&&Gt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),ot("local.channelMarker.updated",{userEntityMarkers:c}),ot("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Xe();if(!n)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:a}=Ee();a||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const s=[];let o=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Gn(e.data):e.data}))},c=(t,n)=>{const{data:r}=Yn(e);Zn(void 0,r)||i({loading:!1,data:r})};return s.push(Tr(c)),s.push(Rr(c)),s.push(Br(c)),(()=>{const t=fe((async()=>Yn(e)));ge(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}})(e.channelId,t)})},Fr=e=>Lr(Wn((e=>{var t;const n=e.messagePreviewId?an(e.channelId):null,r=null===(t=Pe(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,a=n?Object.assign(Object.assign({},n),{user:r?sn(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:a})})(e))),Kr=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("channel",e)})),t}const a=await $n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(r);const s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("local.channel.fetched",a.channels),{data:a.channels.map((e=>Fr(e))),cachedAt:s}};Kr.locally=e=>{var t,n;const r=Ee();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;const s=a.map((({data:e})=>e)),o=null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>Fr(e))),cachedAt:o.cachedAt}};class $r{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 Qr;var zr=()=>(Qr||(Qr=new $r),Qr);const Vr=e=>zr().onSessionStateChange(e),Hr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Jr=!1;const Wr={},Gr=async()=>{const e=Object.entries(Wr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ee();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=nn(r),c=rn(a),l=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),ot("local.feedMarker.fetched",{feedMarkers:s}),ot("local.channelMarker.fetched",{userEntityMarkers:i}),ot("local.subChannelMarker.fetched",{userFeedMarkers:c}),ot("local.userMarker.fetched",{userMarkers:o}),!0})(e)},Yr=()=>{Jr=!1},Zr=()=>(Jr=!0,Vr((e=>{"notLoggedIn"===e&&Yr()})),()=>{Yr()});Hr((async()=>{Jr&&await Gr()}),3e4);const Xr=async e=>{const t=Ee();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:a}};Xr.locally=e=>{var t;const n=Ee();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Pe(["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 ea=async(e=!0)=>{var t;const n=null===(t=Pe(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var a;return(a=r).messagePreview.enabled?a.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},ta=async()=>{var e;const t=await ea();if(t===(null===(e=Pe(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Me(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Re(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{xe(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=Re(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(xe(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Kr(n),0!==r.length&&await Xr(r)}},na=async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},ra=(e,t)=>{var n;const r=null===(n=Pe(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},aa=e=>{const{userId:t}=Ee();return{currentUser:()=>ra(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Pe(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ra(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Pe(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ra(e,t))})(t,e,n)}},sa=async e=>{const t=Ee();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},oa=async e=>{const t=Ee();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},ia=async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},ca={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},la=e=>{const t=Ee();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>ca[e].includes(t))(n,e))throw new Ie(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,zr().setSessionState(e),!0},da=async e=>{const t=Ee();la("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:s}=await(async({params:e,options:t})=>{const n=Ee();n.log("client/api/getToken",e);const r=Vt(),{data:a}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:a},la("established"),{accessToken:n,users:r}};function ua(e){return{users:e.users.map(Tn),files:e.files}}const ha=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=ua(e);n.cache&&Gt(r),t(r.users[0])}))},pa=e=>ha("user.deleted",e),fa=["analytic","normal-priority"],ma=["analytic","high-priority"],ga=async e=>{const t=Ee(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class ya{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=Pe(fa);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ga(t),xe(fa)}catch(e){this.stop(),xe(fa)}}async syncHighPriorityCapturedEvent(){try{const e=Pe(ma);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ga(t),xe(ma)}catch(e){this.stop(),xe(ma)}}}class va{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,a=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!a)return!0;return!(r.getTime()-a.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:a}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,o={event:[]},i=Pe(fa);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:s.toISOString()};a&&(c.metadata=a),o.event.push(c),Ue(fa,o),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const a={event:[]},s=Pe(ma);if((null==s?void 0:s.data)&&(a.event=s.data.event),a.event.length>=this._poolLimit&&a.event.shift(),a.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),Ue(ma,a),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Me(["story-seen","get",e.storyId],(new Date).toISOString());const o=Pe(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Me(["story-last-seen",e.targetId],e.expiresAt):Me(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),ot("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},xe(fa),xe(ma)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class ba{constructor(){this._client=Ee(),this._eventCapturer=new va,this._eventSyncer=new ya}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)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let wa;var Ca=()=>(wa||(wa=new ba),wa),Ia=()=>{const e=Ca();return e.established(),Vr((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Sa{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ee(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Re(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=Pe(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Ee();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],a=null===(t=Pe(r))||void 0===t?void 0:t.data;Me(r,Object.assign(Object.assign({},a),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],a=null===(n=Pe(r))||void 0===n?void 0:n.data;"number"==typeof(null==a?void 0:a.readToSegment)&&a&&t>a.readToSegment&&(a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0),Me(r,a),ot("local.channelUnread.updated",[a])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Pe(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let _a=null;var ka=()=>(_a||(_a=new Sa),_a),Oa=()=>{const e=ka();return e.startSyncReadReceipt(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Ta{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ee(),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=Re(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Pe(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:a}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=Ee();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:a});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Pe(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Me(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:a}))}else s||(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],a=null===(n=Pe(r))||void 0===n?void 0:n.data;if(a&&t>a.readToSegment){a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0);const e=fn(a.channelId);ot("local.channelUnreadInfo.updated",e),Me(r,a),ot("local.subChannelUnread.updated",a)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Pe(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.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 Ea=null;var Aa=()=>(Ea||(Ea=new Ta),Ea),Ra=()=>{const e=Aa();return e.startSyncReadReceipt(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Pa=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")},Ma=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")},ja=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("channel",e)})),t}const a=await $n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(r);const s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("local.channel.fetched",a.channels),{data:a.channels,cachedAt:s}};ja.locally=e=>{var t,n;const r=Ee();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Ua{constructor(){this.TIMER_INTERVAL_MS=W,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(Pa((()=>{this.isConnected=!0}))),this.connectionListener.push(Ma((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await ja(e);const a=null!==(r=null===(n=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];ot("local.channel.resolved",a)})(e),t.length>0&&(async e=>{const t=await Qn(e),{feedMarkers:n,userFeedMarkers:r}=t;mn({feedMarkers:n,userFeedMarkers:r}),ot("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 xa=null;var Da=()=>(xa||(xa=new Ua),xa),qa=()=>{const e=Da();return e.startResolver(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Na{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Pa((()=>{this.isConnected=!0}))),this.connectionListener.push(Ma((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{streamId:n}=t,r=Zt(t,["streamId"]);return e[n]?e[n].push(r):e[n]=[r],e}),{});Object.entries(t).forEach((([e,t])=>{(async({reactions:e,liveStreamId:t})=>{const n=Ee();n.log("live_reaction/addReaction",e);const{data:r}=await n.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e})})({liveStreamId:e,reactions:t})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Ba;var La=()=>(Ba||(Ba=new Na),Ba);const Fa=async()=>{var e;const t=Ee();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&la("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},Ka=e=>{const t=Ee();la("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,Fa()},$a=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Qa=e=>{const t=Ee(),n=$a.map((n=>st(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new Ie(t.message,t.code,"fatal"):new ke(n);e(r)}))));return()=>{n.forEach((e=>e()))}},za=e=>{const t=Ee();return st(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Va=e=>{const t=Ee();return st(t,"client/onTokenExpired","tokenExpired",e)},Ha=e=>{const t=Ee();return st(t,"client/onTokenTerminated","tokenTerminated",e)},Ja=e=>{const t=be("channelMarker")({userId:Xe()._id,entityId:e.channelId});xe(["channelMarker","get",t],!0)};let Wa=[];const Ga=async(e,t,n)=>{const r=Ee();let a;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await Fa(),Wa.forEach((e=>e())),Wa=[]);const s=await zt();try{const{users:n}=await da({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||s}),options:{setAccessTokenCookie:!0}}),o=n.find((t=>t.userId===e.userId));if(null==o)throw new Ie(`${e.userId} has not been founded`,8e5,"error");if(o.isDeleted)return Ka("userDeleted"),!1;if(o.isGlobalBanned)return Ka("globalBan"),!1;r.userId=o.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),et(o)}catch(e){throw zr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await lt()}(),await ta(),0===Wa.length&&(Wa.push(za((e=>{Ka("globalBan"),Wa.forEach((e=>e())),a()})),Ha((e=>{Ka(),Wa.forEach((e=>e())),a()})),pa((e=>{e.userId===r.userId&&(Ka("userDeleted"),Wa.forEach((e=>e())),a())})),Va((e=>{zr().setSessionState(e),Fa(),Wa.forEach((e=>e()))})),lr(Ja),Tr(Ja),Zr(),Ia(),qa(),(()=>{const e=La();return e.startReactionsSync(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()),r.useLegacyUnreadCount?Wa.push(Oa()):Wa.push(Ra())),!0},Ya=()=>{let e,t=!1;const n=Ee();n.log("initiating access token renewal");const r=async r=>{const{userId:a,displayName:s}=Xe(),o={userId:a,displayName:s,authToken:r,deviceId:await zt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await Ga(o,n.sessionHandler):await da({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Ya())}),G)}}},Za=3e5,Xa=e=>{const t=setInterval((()=>{const t=Ee();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-Za)(r))return ot("tokenExpired","tokenExpired"),void rt((()=>e.sessionWillRenewAccessToken(Ya())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),a=Date.parse(n),s=Date.now();return s>a+.8*(r-a-Za)&&s<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(Ya())}),G);return()=>clearInterval(t)},es=e=>{if(Ee().useLegacyUnreadCount){ka().markRead(e.channelId,e.channelSegment)}else{Aa().markRead(e.subChannelId,e.channelSegment)}},ts=e=>{const t=Ee(),n=Xe(),r=[st(t,"message/onMessageCreated","message.created",(async r=>{const a=await _n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Ee(),r=["subChannelUnreadInfo","get",e.messageFeedId],a=null===(t=Pe(r))||void 0===t?void 0:t.data;if(!a)return;const s=a.lastSegment<e.segment?e.segment:a.lastSegment,o=s-a.readToSegment;let{lastMentionSegment:i}=a;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({},a),{lastMentionSegment:i,lastSegment:s,isMentioned:!(a.readToSegment>=i),unreadCount:Math.max(o,0)});Me(r,c)})(e),fn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const a=null===(n=Pe(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!a||a.lastSegment>=e.segment||"number"!=typeof a.readToSegment||"number"!=typeof a.lastMentionedSegment)return;const s=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:a.lastMentionedSegment,i=Object.assign(Object.assign({},a),{lastSegment:s,unreadCount:Math.max(s-a.readToSegment,0),lastMentionedSegment:o,isMentioned:!(a.readToSegment>=o)});Me(["channelUnread","get",e.channelId],i),ot("local.channelUnread.updated",[i])})),Gt(a),a.messages.forEach((t=>{t.creatorPrivateId===n._id&&es(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},ns=e=>{const t=Ee(),n=[st(t,"message/onMessageCreated","local.message.created",(async t=>(Gt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},rs=e=>{const t=Ee();return st(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Rn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:a}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:a};Me(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Gt(r),e(r.messageFeeds[0])}))},as=e=>{const t=Ee(),n=[st(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Rn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Pe(n))||void 0===t?void 0:t.data;r&&Me(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),fn(e.channelId)})),Gt(r),e(r.messageFeeds[0])})),st(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},ss=async e=>{const t=Ee();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=nn(r),c=rn(a),l=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),ot("local.feedMarker.fetched",{feedMarkers:s}),ot("local.channelMarker.fetched",{userEntityMarkers:i}),ot("local.subChannelMarker.fetched",{userFeedMarkers:c}),ot("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let os=!1,is=[],cs=!1;let ls=null;let ds=[];const us=e=>{ds=e},hs=async()=>{var e;if(!cs&&0!==ds.length)try{cs=!0,ds=[];const t=await ss((null==ls?new Date:ls).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!ls||e.getTime()>ls.getTime())&&(ls=e),t.hasMore&&ds.push("has_more")}catch(e){}finally{cs&&(cs=!1)}};Hr((async()=>{os&&await hs()}),2e3);const ps=()=>true,fs=e=>{var t;const n=Ee();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};let ms=[];var gs;class ys{constructor(){gs.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,a){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?a.call(e,n):a?a.value=n:t.set(e,n)}(this,gs,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,gs,"f")}}let vs;gs=new WeakMap;var bs=()=>(vs||(vs=new ys),vs);const ws=e=>{const t=Ee();return st(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Cs=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Is=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Ss=e=>{const t=Ee();return st(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},_s=e=>{const t=Ee();return st(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ks=e=>{const t=Ee();return st(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,a;Gt(t);const s=Re(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.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==o?void 0:o.length)>0){(null!==(a=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Pe(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==a?a:[]).forEach((e=>{var t,n;const r=["messageMarker","get",be("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],a=null===(t=Pe(r))||void 0===t?void 0:t.data;if(!a)return;const s=o[0].feedId===a.feedId,i=o[0].readCount>a.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>a.deliveredCount;if(s){const e=Object.assign(Object.assign({},a),{readCount:i?o[0].readCount:a.readCount,deliveredCount:c?o[0].deliveredCount:a.deliveredCount});Me(r,e)}}))}}e(t.contentMarkers[0])}))};function Os(e){return"object"==typeof e&&null!==e}const Ts=e=>{if(!Os(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)},Es=e=>{if(!Os(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var As=Object.freeze({__proto__:null,getActiveClient:Ee,getActiveUser:Xe,setActiveUser:et,createClient:(e,t=Ot.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:a,rteEnabled:s=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!kt,n=m.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:Et("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:Et("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:Et("mqtt",t),p=xt(d),g=xt(u);let y;s&&(y=Wt(h));const v=f.default(),b={version:`${$}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:y,upload:g,emitter:v,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Xa,sessionHandler:undefined,hasPermission:aa,validateUrls:sa,validateTexts:oa,getFeedSettings:ia,getSocialSettings:na,getMessagePreviewSetting:ea,onRTEConnectionStateChange:fs,use:()=>Ae(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:ps,prefixDeviceIdKey:a};try{const t=Ee();if(t.apiKey===e)return t;Ae(b)}catch(e){Ae(b)}return b},login:Ga,logout:Fa,secureLogout:async()=>{const e=Ee(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Fa()},resumeSession:async(e,t,n)=>{const r=Ee();let a;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&(e=>{var t;const n=Ee(),r=w.default(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId})(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),ms.forEach((e=>e())),ms=[]):(await Fa(),ms.forEach((e=>e())),ms=[]));try{const n=await(async({token:e,userId:t})=>{const n=Ee();la("establishing");const{data:{users:r}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),a=r.find((e=>e.userId===t));return n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,la("established"),a})(e);if(null==n)throw new Ie(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return Ka("userDeleted"),!1;if(n.isGlobalBanned)return Ka("globalBan"),!1;r.userId=n.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),et(n)}catch(e){throw zr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await lt()}(),await ta(),0===ms.length&&(ms.push(za((e=>{Ka("globalBan"),ms.forEach((e=>e())),a()})),Ha((e=>{Ka(),ms.forEach((e=>e())),a()})),pa((e=>{e.userId===r.userId&&(Ka("userDeleted"),ms.forEach((e=>e())),a())})),Va((e=>{zr().setSessionState(e),Fa(),ms.forEach((e=>e()))})),lr(Ja),Tr(Ja),Zr(),Ia(),qa()),r.useLegacyUnreadCount?ms.push(Oa()):ms.push(Ra())),!0},isConnected:()=>{var e,t;const n=Ee();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:ia,renewal:Ya,markerSync:ss,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){bs().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ee();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Oe("Unsupported platform");n=l.Platform.OS;const r=await zt(),{data:{status:a,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new Se(s,5e5,"error");return"success"===a},unregisterPushNotification:async()=>{const e=Ee(),t=zt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new Se(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:fs,fetchLinkPreview:async e=>{const t=Ee();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getSocialSettings:na,getShareableLinkConfiguration:async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/shareable-deep-links");return t},onConnectionError:Qa,onClientDisconnected:e=>Qa((({code:t})=>{800211===t&&e()})),onClientBanned:za,onSessionStateChange:Vr,onNetworkActivities:e=>Mt().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=Xe();if(!t)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ee();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Ts(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(Ss((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),a=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==a?void 0:a.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};Zn(s,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=fe(gn);ge(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(s===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e())))}))})(),()=>{a.forEach((e=>e()))}},getMarkerSyncEvents:()=>ds,setMarkerSyncEvents:us,pushMarkerSyncEvent:e=>ds.push(e),markerSyncTrigger:hs,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{os=!1,us([]),is.forEach((e=>e())),is=[]},getMarkerSyncConsistentMode:ps});function Rs(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Tn)})}function Ps(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Tn)})}function Ms(e){const{follows:t}=e,n=Zt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const js=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Rs(e);n.cache?(Gt(r),t(r.follows[0])):t(r.follows[0])}))},Us=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Ms(e);n.cache?(Gt(r),t(r.follows[0])):t(r.follows[0])}))},xs=e=>js("follow.created",e),Ds=e=>js("follow.unfollowed",e),qs=e=>js("follow.followerDeleted",e),Ns=e=>js("follow.requested",e),Bs=e=>js("follow.requestCanceled",e),Ls=e=>js("follow.accepted",e),Fs=e=>js("follow.requestDeclined",e),Ks=async e=>{var t,n;const r=Ee();r.log("follow/getFollowInfo",e);const{data:a}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),o="follows"in a?Object.assign(Object.assign({},a.followCounts[0]),{status:null===(n=null===(t=a.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):a.followCounts[0];return r.cache&&Me(["followInfo","get",e],o,{cachedAt:s}),{data:o,cachedAt:s}};Ks.locally=e=>{const t=Ee();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Pe(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $s=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([Ks(t.from),Ks(t.to)]);e(n),e(r)},n=[js("follow.created",t),js("follow.requested",t),js("follow.accepted",t),js("follow.unfollowed",t),js("follow.requestCanceled",t),js("follow.requestDeclined",t),js("follow.followerDeleted",t),Us("local.follow.created",t),Us("local.follow.requested",t),Us("local.follow.accepted",t),Us("local.follow.unfollowed",t),Us("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},Qs=e=>Us("local.follow.created",e),zs=e=>Us("local.follow.unfollowed",e),Vs=e=>Us("local.follow.requested",e),Hs=e=>Us("local.follow.accepted",e),Js=e=>Us("local.follow.requestDeclined",e);class Ws{constructor(e){const{http:t}=Ee();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,a;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const o=await this.getRequest(this.queryParams,s);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===(a=o.paging)||void 0===a?void 0:a.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Gs extends Ws{async getRequest(e,t){const{limit:n=Q,userId:r}=e,a=Zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ee().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}class Ys{constructor(e,t){this.query=e,this.cacheKey=t}}var Zs;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Zs||(Zs={}));class Xs extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(be("follow"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(be("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Zs.OnDeclined:case Zs.OnCanceled:case Zs.OnUnfollowed:case Zs.OnDeleted:r.data=r.data.filter((e=>e!==be("follow")(t)));break;case Zs.OnRequested:case Zs.OnAccepted:case Zs.OnFollowed:r.data=[...new Set([be("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class eo{constructor(e){const{http:t}=Ee();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class to{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 eo?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 eo)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 eo)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(Ts).map(Es);return!Zn(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function no(e){return null!=e}const ro=({userId:e})=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{const r=ua(n);Gt(r);const a=Pe(["follow","get",be("follow")({from:r.users[0].userId,to:e})]);a&&t(null==a?void 0:a.data)}))};class ao extends to{constructor(e,t){const n=C.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new Gs(e),n,r,t),this.query=e,this.queryStreamController=new Xs(this.query,this.cacheKey,this.notifyChange.bind(this),Rs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:xs,action:Zs.OnFollowed},{fn:Ds,action:Zs.OnUnfollowed},{fn:Ls,action:Zs.OnAccepted},{fn:Fs,action:Zs.OnDeclined},{fn:Bs,action:Zs.OnCanceled},{fn:qs,action:Zs.OnDeleted},{fn:Hs,action:Zs.OnAccepted},{fn:Js,action:Zs.OnDeclined},{fn:Qs,action:Zs.OnFollowed},{fn:zs,action:Zs.OnUnfollowed},{fn:ro({userId:this.query.userId}),action:Zs.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["follow","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Pe(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class so extends Ws{async getRequest(e,t){const{limit:n=Q,userId:r}=e,a=Zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ee().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}class oo extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(be("follow"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(be("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Zs.OnDeclined:case Zs.OnCanceled:case Zs.OnUnfollowed:case Zs.OnDeleted:r.data=r.data.filter((e=>e!==be("follow")(t)));break;case Zs.OnRequested:case Zs.OnAccepted:case Zs.OnFollowed:r.data=[...new Set([be("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const io=({userId:e})=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{const r=ua(n);Gt(r);const a=Pe(["follow","get",be("follow")({from:e,to:r.users[0].userId})]);a&&t(null==a?void 0:a.data)}))};class co extends to{constructor(e,t){const n=C.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new so(e),n,r,t),this.query=e,this.queryStreamController=new oo(this.query,this.cacheKey,this.notifyChange.bind(this),Ps),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Ns,action:Zs.OnRequested},{fn:Ls,action:Zs.OnAccepted},{fn:Fs,action:Zs.OnDeclined},{fn:Bs,action:Zs.OnCanceled},{fn:xs,action:Zs.OnFollowed},{fn:Ds,action:Zs.OnUnfollowed},{fn:qs,action:Zs.OnDeleted},{fn:Vs,action:Zs.OnRequested},{fn:Hs,action:Zs.OnAccepted},{fn:Js,action:Zs.OnDeclined},{fn:Qs,action:Zs.OnFollowed},{fn:zs,action:Zs.OnUnfollowed},{fn:io({userId:this.query.userId}),action:Zs.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["follow","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Pe(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const lo=(e,t,n,r,a,s)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=Ee();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=Zt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Ts(n)};return h.push(...a.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&Zn(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=fe(r,e,!0);ge(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===J?(p({data:t,origin:r,loading:!1,error:new Se(H,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,blockUser:async e=>{const t=Ee();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Gt(o,{cachedAt:r}),Ue(["followInfo","get",e],s[0],{cachedAt:r}));const i=Ms(o);return ot("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=Ee();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Gt(o,{cachedAt:r}),Ue(["followInfo","get",e],s[0],{cachedAt:r}));const i=Ms(o);return ot("local.follow.created",i),n},follow:async e=>{const t=Ee();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const a=Ms(n);return"accepted"===n.follows[0].status?ot("local.follow.created",a):ot("local.follow.requested",a),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Ee();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Ee();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Ee();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.requestDeclined",r),!0},onUserFollowed:xs,onUserUnfollowed:Ds,onFollowerDeleted:qs,onFollowerRequested:Ns,onFollowRequestCanceled:Bs,onFollowRequestAccepted:Ls,onFollowRequestDeclined:Fs,onFollowInfoUpdated:$s,onLocalUserFollowed:Qs,onLocalUserUnfollowed:zs,onLocalFollowerRequested:Vs,onLocalFollowRequestAccepted:Hs,onLocalFollowRequestDeclined:Js,getFollowers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const o=new ao(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const o=new co(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>lo(e,t,"userId",Ks,[$s],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Xe();return lo(t,e,"userId",Ks,[$s],{forceDispatch:!0})}});class ho{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Pe(["story-expire",this._targetId]),this.cacheStoreSeenTime=Pe(["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=Pe(["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 Pe(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Re(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:a}}=t;return n!==this._targetId||a||(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 po=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:a,targetUpdatedAt:s,localFilter:o}=e,i=new ho(n,r,a);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},fo=async e=>{const t=Ee();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,a=Zt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},a),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await $n(n.data),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{channels:s}=r;return{data:Fr(s[0]),cachedAt:a}},mo=async e=>{const t=Ee();let n;t.log("channel/getChannel",e),pn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await $n(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&zn(r)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("channel",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{channels:a}=n;return{data:a.find((t=>t.channelId===e)),cachedAt:r}};mo.locally=e=>{var t;const n=Ee();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Re(["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 go=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Pe(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Pe(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Pe(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Pe(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=Pe(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return go(n)})).filter(no):[]},getLiveChat:()=>(async e=>{var t;const n=Ee();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Lr(Fr(n));const{data:r}=await mo(e.channelId);return Lr(Fr(r))}if(e.userId===n.userId){const{data:t}=await fo({type:"live",postId:e.postId,videoStreamId:e.streamId});return je(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null}),yo=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Pe(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),vo=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=Pe(["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=Pe(["user","get",e.userId]);if(null==t?void 0:t.data)return sn(t.data)},get childrenComment(){return e.children.map((e=>{const t=Pe(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(no).map((e=>vo(e)))}});function bo(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function wo(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const Co=e=>un(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=Pe(["post","get",e]))||void 0===t?void 0:t.data})).filter(no).map(Co),analytics:{markAsViewed:()=>{Ca().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Pe(["comment","get",e]))||void 0===t?void 0:t.data;return n?vo(n):null})).filter(Boolean)||[]},get creator(){const t=Pe(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return sn(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return bo(e)?null===(r=Pe(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return bo(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getLivestreamInfo(){var t,n;if(!wo(e))return;const r=null===(n=Pe(["stream","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.streamId]))||void 0===n?void 0:n.data;return r?go(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e))return;const r=null===(n=Pe(["poll","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.pollId]))||void 0===n?void 0:n.data;return r||void 0},getClipInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0}}),Io=(e,t)=>{"message"===e?ot("local.message.updated",{messages:[t]}):"post"===e?ot("post.updated",{posts:[t]}):"comment"===e?ot("comment.updated",{comments:[t]}):"story"===e&&ot("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},So=async(e,t,n,r)=>{var a,s,o;const i=Ee();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(i.cache){const r=Pe([e,"get",t]);if(!r||(null===(a=r.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(s=r.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(o=r.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return ot("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0}return!0};So.optimistically=(e,t,n)=>{var r,a,s,o,i;const c=Ee();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Pe([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Ue([e,"get",t],d,{cachedAt:J}),Io(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const _o=(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=Pe(["messageMarker","get",be("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},ko=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var a,s;const o=Ee();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(o.cache){const r=Pe([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return ot("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)};function Oo(e,t){return e.map((e=>{const n=Pe(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=Xe();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const To=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:R};function Eo({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Zt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:To({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Ao=e=>{const t=Eo({communities:e.communities}),n=e.users.map(Tn),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=Oo(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(Tn),communities:a,communityUsers:r})},Ro=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(Tn);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Po=e=>{const t=Eo({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Oo(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Mo=e=>{const{postSetting:t,storySetting:n}=e,r=Zt(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})},jo=e=>{var t=Zt(e,["searchResult"]);const n=Ao(t);return Object.assign({},n)},Uo=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Pe(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return sn(n)},cancel:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),ot("local.joinRequest.deleted",[a])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"approved"}),ot("local.joinRequest.updated",[a])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"rejected"}),ot("local.joinRequest.updated",[a])),r.success})(e)}});class xo extends Ws{async getRequest(e,t){const{limit:n=20,communityId:r}=e,a=Zt(e,["limit","communityId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},a),{options:s})});return o}}var Do;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Do||(Do={}));class qo extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Do.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===Do.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===Do.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const No=e=>{const t=Ee(),n=[st(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Bo=e=>{const t=Ee(),n=[st(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Lo=e=>{const t=Ee(),n=[st(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Fo extends to{constructor(e,t){const n=C.default(e),r=["joinRequest","collection",n];super(new xo(e),n,r,t),this.query=e,this.queryStreamController=new qo(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:No,action:Do.OnLocalJoinRequestCreated},{fn:Bo,action:Do.OnLocalJoinRequestUpdated},{fn:Lo,action:Do.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Pe(["joinRequest","get",e]))).filter(no).map((({data:e})=>e)).map(Uo));(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;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}const Ko=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),$o=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Ko),users:e.users.map(Tn)}),Qo=e=>Object.assign(Object.assign({},e),{users:e.users.map(Tn),invitations:e.invitations.map(Ko)}),zo=e=>Object.assign(Object.assign({},e),{get user(){const t=Pe(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get createdBy(){const t=Pe(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get target(){if("community"===e.targetType){const t=Pe(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ee();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),a=null===(t=Pe(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Ue(["invitation","get",e],{status:"approved"}),ot("local.invitation.updated",[a])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ee();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),a=null===(t=Pe(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Ue(["invitation","get",e],{status:"rejected"}),ot("local.invitation.updated",[a])),r.success})(e._id)}});var Vo;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationDeleted="onLocalInvitationDeleted"}(Vo||(Vo={}));class Ho extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class Jo extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(be("invitation"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(be("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Vo.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===Vo.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===Vo.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Wo=e=>{const t=Ee(),n=[st(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Go=e=>{const t=Ee(),n=[st(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Yo=e=>{const t=Ee(),n=[st(t,"onLocalInvitationDeleted","local.invitation.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Zo extends to{constructor(e,t){const n=C.default(e),r=["invitation","collection",n];super(new Ho(e),n,r,t),this.query=e,this.queryStreamController=new Jo(this.query,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wo,action:Vo.OnLocalInvitationCreated},{fn:Go,action:Vo.OnLocalInvitationUpdated},{fn:Yo,action:Vo.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["invitation","get",e]))).filter(no).map((({data:e})=>zo(e))))&&void 0!==a?a:[]);(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;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}const Xo=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=Pe(["category","get",e]);if(null==t?void 0:t.data)return yo(t.data)})).filter((e=>!!e))},createInvitations:async t=>{await(async e=>{const t=Ee();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=$o(n),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:a}})({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getInvitations: (tmpid: ${s}) > listen`);const o=new Zo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await(async(e,t)=>{const n=Ee();n.log("invitation/getInvitation",e,t);const{data:r}=await n.http.get("/api/v1/invitations/me",{params:{targetType:e,targetId:t}}),a=Qo(r),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),{data:a.invitations[0]?zo(a.invitations[0]):void 0,cachedAt:s}})("community",e.communityId);return t},join:async()=>(async e=>{var t;const n=Ee();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),a=Ro(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const o="approved"===a.joinRequests[0].status?"success":"pending";if("success"===o&&n.cache){const n=null===(t=Pe(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});Ue(["community","get",e],t)}}return ot("v4.local.community.joined",a.joinRequests),"success"===o?{status:o}:{status:o,request:Uo(a.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getJoinRequests: (tmpid: ${s}) > listen`);const o=new Fo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getJoinRequests (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ee();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=Ro(n),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.joinRequests[0]?Uo(r.joinRequests[0]):void 0,cachedAt:a}})(e.communityId);return t}}),ei={ad:e=>{const t=Ca(),{image9_16:n,image1_1:r}=e,a=Zt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},a),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Pe(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const a=null===(n=Pe(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:a})},get image1_1(){const e=Pe(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Pe(["file","get",n]);if(e)return e.data||void 0}})},comment:vo,post:Co,user:sn,category:yo,stream:go,story:e=>{const t=Ca(),n=Pe(["storyTarget","get",e.targetId]),r=Pe(["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=Pe(["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:a}=r;return a||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Pe(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:a}=r;return a?Object.assign(Object.assign({},a),{fileUrl:`${a.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=Pe(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Pe(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return po(n.data)},get isSeen(){const t=Pe(["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,a=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(r,a)>=s}})},storyTarget:po,message:e=>{const t=Zt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return _o(e).readCount},get deliveredCount(){return _o(e).deliveredCount},get creator(){var t;return null===(t=Pe(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>es(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return So("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>ko(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Pe(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return sn(n)}}),channel:Lr,pinnedPost:e=>{var t;const n=Pe(["post","get",e.referenceId]),r=null===(t=Re(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return Co(n.data)},get target(){const e=Pe(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map((e=>sn(e)))}),community:Xo,invitation:zo,joinRequest:Uo,channelMember:Gn},ti=async e=>{const t=Ee();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}}),a=ua(r),s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("user.fetched",r),{data:a.users.map((e=>ei.user(e))),cachedAt:s}};ti.locally=e=>{var t;const n=Ee();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Pe(["user","get",e]))).filter(Boolean),a=r.map((({data:e})=>ei.user(e))),s=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:a,cachedAt:s.cachedAt}};const ni=e=>ha("user.updated",e),ri=e=>ha("user.flagged",e),ai=e=>ha("user.unflagged",e),si=e=>ha("user.flagCleared",e),oi=e=>ha("user.fetched",e),ii=async e=>{const t=Ee();t.log("user/getUser",e),pn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),a=ua(n);return t.cache&&Gt(a,{cachedAt:r}),ot("user.fetched",n),{data:a.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ne(null==t?void 0:t.code)&&Yt("user",e),t}};ii.locally=e=>{const t=Ee();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Pe(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ci extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class li extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var di;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(di||(di={}));class ui extends to{constructor(e,t){const n=C.default(e),r=["user","collection",n];super(new ci(e),n,r,t),this.query=e,this.queryStreamController=new li(this.query,this.cacheKey,this.notifyChange.bind(this),ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:di.OnUserDeleted},{fn:ni,action:di.OnUserUpdated},{fn:ri,action:di.OnUserFlagged},{fn:ai,action:di.OnUserUnflagged},{fn:si,action:di.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ei.user))&&void 0!==a?a:[]);(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;const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class hi extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class pi extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return t=>{var n;if(e===Zs.OnFollowed){const e=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Me(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function fi(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Tn(n)})})),users:t.map(Tn)})}const mi=(e,t,n)=>r=>e((e=>{var a;if(!e)return e;const s=[n,"get",`${e[t]}`],o=null===(a=Pe(s))||void 0===a?void 0:a.data;return o?r(o):void 0}));class gi extends to{constructor(e,t){const n=C.default(e),r=["blockedUsers","collection",n];super(new hi(e),n,r,t),this.query=e,this.queryStreamController=new pi(this.query,this.cacheKey,this.notifyChange.bind(this),fi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:di.OnUserDeleted},{fn:mi(Qs,"to","user"),action:Zs.OnFollowed},{fn:mi(xs,"to","user"),action:Zs.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ei.user))&&void 0!==a?a:[]);(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 t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class yi extends Ws{async getRequest(e,t){const{limit:n=Q,displayName:r}=e,a=Zt(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:null==r?void 0:r.toLocaleLowerCase(),options:s,isDeleted:!1})});return o}}class vi extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class bi extends to{constructor(e,t){var n;const r=C.default(e),a=["user","collection",r];super(new yi(e),r,a,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new vi(this.query,this.cacheKey,this.notifyChange.bind(this),ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:di.OnUserDeleted},{fn:ni,action:di.OnUserUpdated},{fn:ri,action:di.OnUserFlagged},{fn:ai,action:di.OnUserUnflagged},{fn:si,action:di.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ei.user))&&void 0!==a?a:[]);(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"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const wi=async({viewId:e,viewedType:t,limit:n,token:r})=>{const a=Ee(),s={};r?s.token=r:s.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await a.http.get(o,{params:s});return Gt(i.data),i.data};var Ci;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ci||(Ci={}));var Ii=Object.freeze({__proto__:null,Relationship:uo,getUserByIds:ti,updateUser:async(e,t)=>{const n=Ee();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})),a=ua(r),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),ot("user.updated",r),{data:a.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=Ee();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=ua(n);return t.cache&&Gt(r),ot("user.flagged",n),!!r},unflagUser:async e=>{const t=Ee();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=ua(n);return t.cache&&Gt(r),ot("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Ee();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:ni,onUserDeleted:pa,onUserFlagged:ri,onUserUnflagged:ai,onUserFlagCleared:si,getUser:(e,t)=>lo(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?ei.user(e.data):e.data}))),"userId",ii,[oi,ni,pa,ri,ai,si]),getUsers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const o=new ui(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const o=new gi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),xe(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`liveSearchUsers(tmpid: ${s}) > listen`);const o=new bi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:a}=Ee(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];a||console.log(V);const o=Date.now();r(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,a,o;const d=null===(r=Pe(s))||void 0===r?void 0:r.data,u=null!==(a=null==d?void 0:d.data)&&void 0!==a?a:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=fe(wi,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});ge(h,(e=>{var r,a,o,i,c;let l=null!==(o=null===(a=null===(r=Pe(s))||void 0===r?void 0:r.data)||void 0===a?void 0:a.data)&&void 0!==o?o:[];(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||[]};Me(s,d),(e=>{var r,a;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Pe(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(a=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===a?void 0:a.next),loading:e.loading||!1})})(d)}),me(z,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${o}) > dispose`),xe(s)}},get AmityUserSearchMatchType(){return Ci}});const Si=async e=>{const t=Ee();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Gt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};Si.locally=e=>{const t=Ee();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Pe(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _i=async(e,t,n)=>{const r=Ee();r.log("file/uploadVideo",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const s=bs().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},ki=async(e,t,n)=>{const r=Ee();r.log("file/uploadImage",e);const a=e.getAll("files");if(null==a?void 0:a.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",a[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const s=bs().getFileAccessType();e.append("accessType",s);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Oi=Object.freeze({__proto__:null,getFile:Si,uploadFile:async(e,t)=>{const n=Ee();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const a=bs().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Gt({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=Ee();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),xe(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:_i,uploadImage:ki,updateAltText:async(e,t)=>{const n=Ee();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),a=n.cache&&Date.now();return n.cache&&Gt({files:[r]},{cachedAt:a}),!0},uploadClip:async(e,t,n)=>{const r=Ee();r.log("file/uploadClip",e);const a=e.get("files");if(!a)throw new Error("The formData object must have a `files` key.");const s=bs().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a.name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/clips",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}}});const Ti=async e=>{const t=Ee();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:a,displayName:s,sortBy:o}=n,i=Zt(n,["limit","queryToken","displayName","sortBy"]),c=a?{token:a}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:s,sortBy:o,options:c})}),{paging:d}=l,u=Zt(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Gt(u,{cachedAt:p});const f=ce(d.next);return{data:h,cachedAt:p,prevPage:ce(d.previous),nextPage:f,paging:d}};Ti.locally=e=>{Ee().log("role/queryRoles.locally",e)};const Ei=async e=>{const t=Ee();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Gt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Ei.locally=e=>{const t=Ee();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Pe(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ai=async(e,t=!1)=>{const n=Ee();let r;n.log("message/getMessage",e),pn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await _n(t)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("message",e),t}const a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{messages:s}=r;return ot("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:a}};Ai.locally=e=>{const t=Ee();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Pe(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ri=async e=>{const t=Ee();let n;t.log("post/getPost",e),pn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("post",e),t}const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};Ri.locally=e=>{const t=Ee();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Pe(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Pi=async e=>{const t=Ee();let n;t.log("comment/getComment",e),pn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{comments:a}=n;return{data:ei.comment(a.find((t=>t.commentId===e))),cachedAt:r}};Pi.locally=e=>{const t=Ee();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Pe(["comment","get",e]);return n?{data:ei.comment(n.data),cachedAt:n.cachedAt}:void 0};const Mi=(e,t)=>{var n,r;let a,s;if("post"===t)s="post",a=e.posts[0].postId;else if("comment"===t)s="comment",a=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",a=e.stories[0].referenceId}return(null===(r=null===(n=Pe([s,"get",a]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},ji=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Ui=(e,t,n,r=[])=>{const a=e.split(".")[1];let s=r;if(Ee().userId===t)if(["addReaction","reactionAdded"].includes(a))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(a))throw new Error(`Unknown event type: ${a}`);s=s.filter((e=>e!==n))}return s},xi=(e,t)=>{const n=e.split(".")[0],r=Mi(t,n),a=Ui(e,t.reactor.userId,t.reactor.reactionName,r);return ji(t,`${n}s`,a)},Di=(e,t)=>{var n,r;const a=e.split(".")[0];let s=Mi(t,a);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=Ui(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,s));const o=ji(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=Oo(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},qi=async(e,t,n)=>{var r,a,s;const o=Ee();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Pe([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(a=c.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return ot("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};qi.optimistically=(e,t,n)=>{var r,a,s,o,i;const c=Ee();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Pe([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Ue([e,"get",t],d,{cachedAt:J}),Io(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Ni=async(e,t,n)=>{var r,a;const s=Ee();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(s.cache){const i=Pe([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(a=i.data.reactions[n])&&void 0!==a?a:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return ot("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};Ni.optimistically=(e,t,n)=>{var r,a,s,o;const i=Ee();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Pe([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 l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(a=c.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)-1)})});return Ue([e,"get",t],l,{cachedAt:J}),Io(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const Bi=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,a=Zt(e,["posts","postChildren","videoStreamings"]),s=Eo({communities:a.communities}),o=a.communityUsers.map((e=>{const t=a.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=Oo(s,o);let c=[];const l=t.map((t=>{var n,s;const o=null===(n=a.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,i=e.postChildren.filter((e=>e.parentPostId===t.postId));var l,d,u;return i.length>0&&wo(i[0])&&(l=r,d=null===(s=i[0].data)||void 0===s?void 0:s.streamId,u=t.postId,c=d?l.map((e=>e.streamId===d?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:u,postId:u}):e)):l),Object.assign(Object.assign({},t),{childPosts:i,feedType:o})}));return Object.assign(Object.assign({},a),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:o})},Li=e=>{var{searchResult:t,polls:n}=e,r=Zt(e,["searchResult","polls"]);const a=Bi(r);return Object.assign(Object.assign({},a),{polls:n})},Fi=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=Pe(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;Me(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>je(["post","get",e],{isDeleted:!0})))},Ki=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a;if(n.cache){const s=Bi(r),{communities:o}=s;if(Gt(s,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&ot("community.updated",{communities:o,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:a}=r.posts[0];Fi(r);try{pn("post",e)}catch(e){return}return a!==n.userId&&xe(["post","get",e]),t(r.posts[0])}const i=Pe(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(a=Re(["post","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===i.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})=>Ue(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=Pe(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&Me(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(i.data)}else t(r.posts[0])}))},$i=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{if(n.cache){const n=Bi(r),{communities:a}=n;Gt(n),(null==a?void 0:a[0])&&!["local.post.updated"].includes(e)&&ot("community.updated",{communities:a,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const s=Pe(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&Fi(r),t(s.data)}else t(r.posts[0])}))},Qi=e=>Ki("post.created",e),zi=e=>Ki("post.updated",e),Vi=e=>Ki("post.deleted",e),Hi=e=>Ki("post.approved",e),Ji=e=>Ki("post.declined",e),Wi=e=>Ki("post.flagged",e),Gi=e=>Ki("post.unflagged",e),Yi=e=>{const t=Ee();return st(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Zt(xi("post.addReaction",n),["reactor"]);Gt(t);const r=Pe(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Zi=e=>{const t=Ee();return st(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Zt(xi("post.removeReaction",n),["reactor"]);Gt(t);const r=Pe(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Xi=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a;if(n.cache){const s=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Mi(e,"comment");return ji(e,"comments",t)})(r):r;Gt(s,void 0,!1);const{comments:o}=s;if(o.length>0){const r=Pe(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||Me(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t)}}const t=null===(a=Re(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>Ue(e,t,{cachedAt:-1})))}t(ei.comment(r.data))}}else t(ei.comment(r.comments[0]))}))},ec=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a,s;if(n.cache){const n=r;Gt(n);const{comments:o}=n;if(o.length>0){const n=Pe(["comment","get",o[0].commentId]);if(["local.comment.created"].includes(e)){if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{ot("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Re(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Ue(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{ot("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(s=Re(["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})=>Ue(e,t,{cachedAt:-1})))}t(ei.comment(n.data))}}else t(ei.comment(r.comments[0]))}))},tc=e=>Xi("comment.created",e),nc=e=>Xi("comment.updated",e),rc=e=>Xi("comment.deleted",e),ac=e=>Xi("comment.flagged",e),sc=e=>Xi("comment.unflagged",e),oc=e=>{const t=Ee();return st(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Zt(xi("comment.addReaction",n),["reactor"]);Gt(t);const r=Pe(["comment","get",n.comments[0].commentId]);e(ei.comment(r.data))}else e(ei.comment(n.comments[0]))}))},ic=e=>{const t=Ee();return st(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Zt(xi("comment.removeReaction",n),["reactor"]);Gt(t);const r=Pe(["comment","get",n.comments[0].commentId]);e(ei.comment(r.data))}else e(ei.comment(n.comments[0]))}))},cc=(e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return st(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),Gt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return st(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return st(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return st(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))},lc=(e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return st(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return st(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return st(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return st(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))};class dc extends Ws{async getRequest(e,t){const{limit:n=Q,referenceType:r}=e,a=Zt(e,["limit","referenceType"]),s=t?{token:t}:{limit:n};Ee().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},a),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:s})});return o}}class uc extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Ee(),a=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=Zt(n,["reactions"]);Gt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:a})}}appendToQueryStream(e,t,n=!1){var r,a,s,o;const i=null!==(a=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==a?a:[];if(n)Me(this.cacheKey,{data:i.map(be("reactor"))});else{const e=null===(s=Pe(this.cacheKey))||void 0===s?void 0:s.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];Me(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(be("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hc extends to{constructor(e,t){const n=C.default(e),r=["reaction","collection",n];super(new dc(e),n,r,t),this.query=e,this.queryStreamController=new uc(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>cc(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>lc(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return st(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return st(r,"local.post.removeReaction","local.post.removeReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return st(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return st(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return st(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),Gt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return st(r,"local.post.addReaction","local.post.addReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return st(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return st(r,"local.comment.addReaction","local.comment.addReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["reactor","get",e]))).filter(Boolean).map((({data:e})=>ei.reactor(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var pc=Object.freeze({__proto__:null,addReaction:qi,removeReaction:Ni,onReactionAdded:(e,t,n)=>{const r=r=>{be(e)(r)===t&&n(r)};if("message"===e){const e=Ee(),t=async e=>{var t;const n=await _n(e),a=Pe(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Gt(n),s&&r(n.messages[0])};return st(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Yi(r):oc(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{be(e)(r)===t&&n(r)};if("message"===e){const e=Ee(),t=async e=>{var t;const n=await _n(e),a=Pe(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Gt(n),s&&r(n.messages[0])};return st(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Zi(r):ic(r)},onReactorAdded:cc,onReactorRemoved:lc,getReactions:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getReactions(tmpid: ${s}) > listen`);const o=new hc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getReactions(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});function fc(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const mc=e=>{const t=Ee(),n=[st(t,"onMessageUpdated","message.updated",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])})),st(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},gc=e=>{const t=Ee(),n=[st(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])})),st(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},yc=e=>{const t=Ee(),n=[st(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Rn(t);Gt(n),e(n.messageFeeds[0])})),st(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function vc(e,t){Me(["channel","get",e.channelId],un(e,t))}const bc=e=>{const t=Ee();return st(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},wc=async(e,t=!1)=>{const n=Ee(),r=await Pn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const a=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Ce(r.data.updatedAt)});return t?setTimeout((()=>{Yt("subChannel",e)}),0):Ue(["subChannel","get",e],a),ot("local.message-feed.deleted",{messageFeeds:[a]}),a},Cc=e=>st(Ee(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Ic=()=>`LOCAL_${$t()}`;let Sc;const _c=async(e,t)=>{const n=Ee();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)}`,kn(t)),a=await _n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{messages:o}=a;return ot("local.message.updated",{messages:o}),{data:ei.message(o.find((t=>t.messageId===e))),cachedAt:s}};_c.optimistically=(e,t)=>{const n=Ee();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Pe(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Ue(["message","get",e],a,{cachedAt:-1}),ot("local.message.updated",{messages:[a]}),{data:ei.message(a),cachedAt:-1}};const kc=async(e,t)=>{const n=Ee();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,kn(t)),a=await _n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{messages:o}=a;return ot("local.message.updated",{messages:o}),{data:ei.message(o.find((t=>t.messageId===e))),cachedAt:s}};kc.optimistically=(e,t)=>{const n=Ee();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Pe(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Ue(["message","get",e],a,{cachedAt:-1}),ot("local.message.updated",{messages:[a]}),{data:ei.message(a),cachedAt:-1}};const Oc=async e=>{var t;const n=Ee();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=Pe(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return ot("local.message.deleted",{messages:[r]}),ei.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),a=await _n(r);return ot("local.message.deleted",{messages:[a.messages[0]]}),ei.message(a.messages[0])};Oc.optimistically=e=>{Ee().log("message/deleteMessage.optimistically",e);const t=Pe(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ue(["message","get",e],n,{cachedAt:-1}),ot("local.message.deleted",{messages:[n]}),{data:ei.message(n),cachedAt:-1}};const Tc=async e=>{const t=Ee();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Ai(e);return ot("local.message.deleted",{messages:[n.data]}),ei.message(n.data)};Tc.optimistically=e=>{Ee().log("message/softDeleteMessage.optimistically",e);const t=Pe(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ue(["message","get",e],n,{cachedAt:-1}),ot("local.message.deleted",{messages:[n]}),{data:ei.message(n),cachedAt:-1}};const Ec=async e=>{const t=Ee();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,a=Zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},a),{options:{token:ie(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},l),{userFeedMarkers:rn(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ti(i));return{data:u,cachedAt:d,prevPage:ce(o.previous),nextPage:ce(o.next)}};Ec.locally=e=>{var t;const n=Ee();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,a=Zt(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Pe(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ce(null==o?void 0:o.paging.previous),nextPage:ce(null==o?void 0:o.paging.next)}};const Ac=async e=>{const t=Ee();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,a=Zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},a),{options:{token:ie(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},l),{userFeedMarkers:rn(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ti(i));return{data:u,cachedAt:d,prevPage:ce(o.previous),nextPage:ce(o.next)}};Ac.locally=e=>{var t;const n=Ee();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,a=Zt(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Pe(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ce(null==o?void 0:o.paging.previous),nextPage:ce(null==o?void 0:o.paging.next)}};const Rc=e=>{const t=Ee();return st(t,"onMessageFlagged","message.flagged",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},Pc=e=>{const t=Ee();return st(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},Mc=e=>{const t=Ee();return st(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},jc=e=>{const t=Ee();return st(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await _n(t,"message.reactionAdded");Gt(n),e(n.messages[0])}))},Uc=e=>{const t=Ee();return st(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await _n(t,"message.reactionRemoved");Gt(n),e(n.messages[0])}))},xc=e=>{const t=Ee();return st(t,"message/onMessageFetched","local.message.fetched",(t=>{Gt(t),e(t.messages[0])}))},Dc=e=>{const t=Ee();return st(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;je(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Re(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{je(e.key,{isDeleted:!0})}))}));const a=null===(n=Pe(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))};class qc extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messages.map(be("message")),query:this.query});else{const n=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,s=null!==(a=null==n?void 0:n.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...e.messages.map(be("message"))])]:[...new Set([...e.messages.map(be("message")),...s])]}))}}reactor(e){return t=>{var n,r,a,s;if("onCreate"===e){const e=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:s}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(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;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=s?s:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=s?s:t.messageId])]),Me(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(s=Pe(this.cacheKey))||void 0===s?void 0:s.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));Me(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Nc extends Ws{async getRequest(e,t){const n=On(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 Bc extends to{constructor(e,t){const n=C.default(e),r=["message","collection",n];super(new Nc(e),n,r,t),this.query=e,this.queryStreamController=new qc(this.query,this.cacheKey,this.notifyChange.bind(this),_n,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ts,action:"onCreate"},{fn:ns,action:"onCreate"},{fn:gc,action:"onDelete"},{fn:mc,action:"onUpdate"},{fn:Rc,action:"onFlagged"},{fn:Pc,action:"onUnflagged"},{fn:Mc,action:"onFlagCleared"},{fn:jc,action:"onReactionAdded"},{fn:Uc,action:"onReactionRemoved"},{fn:mi(_s,"contentId","message"),action:"onUpdate"},{fn:mi(ks,"contentId","message"),action:"onUpdate"},{fn:mi(Dc,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>(e=>{var t,n;const r=null===(t=Pe(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const a=Re(["message","get"]);return null===(n=null==a?void 0:a.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>ei.message(e))))&&void 0!==a?a:[]);(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 this.query.includeDeleted||(t=De(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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)}}var Lc=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ee();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Ee();if(!r.cache)return;Sc=e.referenceId||Ic();const a=Object.assign({messageId:Sc,uniqueId:Sc},e);r.log("message/createMessage.optimistically",a);const s=Pe(["subChannel","get",e.subChannelId]);if(s&&(Ue(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},s.data),{messageCount:s.data.messageCount+1})),s.data.channelId===s.data.subChannelId)){const e=Pe(["channel","get",s.data.channelId]);(null==e?void 0:e.data)&&Ue(["channel","get",s.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:Xe()._id,channelSegment:(null!==(n=null==s?void 0:s.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},a);return Me(["message","get",i.messageId],i,{cachedAt:-5}),ot("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||Sc||Ic();Sc=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},kn(e)),{referenceId:r})),a=await _n(n),{messages:s}=a,o=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:o}),ot("local.message.created",{messages:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})]}),{data:ei.message(s[0]),cachedAt:o}}catch(e){throw ot("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:_c,editMessage:kc,deleteMessage:Oc,softDeleteMessage:Tc,markAsDelivered:async(e,t)=>{const n=Ee();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=r,i=Zt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Gt(Object.assign({userMarkers:a,userEntityMarkers:nn(s),userFeedMarkers:rn(o)},i),{cachedAt:c}),!0},getReadUsers:Ec,getDeliveredUsers:Ac,flagMessage:async(t,n)=>{const r=Ee();r.log("message/flag",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:a?n:e.ContentFlagReasonEnum.Others,detail:a?"":n},{data:o}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,s);if(r.cache){const e=await _n(o);Gt(e)}return ot("message.flagged",o),!!o},unflagMessage:async e=>{const t=Ee();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await _n(n);Gt(e)}return ot("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ee();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:ts,onMessageCreatedLocal:ns,onMessageUpdated:mc,onMessageDeleted:gc,onMessageFlagged:Rc,onMessageUnflagged:Pc,onMessageFlagCleared:Mc,onMessageReactionAdded:jc,onMessageReactionRemoved:Uc,onMessageFetched:xc,getMessage:(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ei.message(e.data):n}))}),"messageId",Ai,[xc,mc,gc,Rc,Pc,Mc,jc,Uc,mi(_s,"contentId","message"),mi(ks,"contentId","message"),mi(Dc,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const o=new Bc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:In,prepareMessagePayload:_n,convertParams:kn,convertQueryParams:On});const Fc=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class Kc extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Zt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Zt(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:o}=a,i=Zt(a,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:yn(o),options:c})});return l}}class $c extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(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=Pe(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])]),Me(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Qc extends to{constructor(e,t){const n=C.default(e),r=["subChannel","collection",n];super(new Kc(e),n,r,t),this.query=e,this.queryStreamController=new $c(this.query,this.cacheKey,this.notifyChange.bind(this),Rn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Cc,action:"onCreate"},{fn:rs,action:"onCreate"},{fn:as,action:"onDelete"},{fn:e=>yc((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ee();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=cn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Mn(t.updatedAt)>Mn(e.subChannelUpdatedAt)&&Me(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:mi((e=>ts((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Un(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:mi((e=>ns((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Un(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Is((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Pe(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:mi(Cs,"feedId","subChannel"),action:"onUpdate"},{fn:mi((e=>mc((async t=>{var n;const r=Ee();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&(xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:mi((e=>gc((async t=>{const n=Ee(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await Pn(t.subChannelId):await xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:mi(Fc,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ln))&&void 0!==a?a:[]);(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=De(e,"isDeleted",!1)),t.sort(Ye),t}isRelatedCollection(e){var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const zc={},Vc=async e=>{const t=await(async e=>{const t=Pn.locally(e);if(t)return t.data.channelId;const{data:n}=await Pn(e);return n.channelId})(e),n=ft({channelId:t,subChannelId:e});zc[e]=Ct(n)};var Hc=Object.freeze({__proto__:null,getSubChannelByIds:Xr,createSubChannel:async e=>{const t=Ee();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:a}},updateSubChannel:async(e,t)=>{const n=Ee();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),a=await Rn(r.data),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),ot("message-feed.updated",r.data),{data:a.messageFeeds[0],cachedAt:s}},deleteSubChannel:wc,hardDeleteSubChannel:async e=>{Ee().log("channel/hardDeleteSubChannel",e);return await wc(e,!0)},softDeleteSubChannel:async e=>{Ee().log("channel/softDeleteSubChannel",e);return await wc(e,!1)},onSubChannelCreated:rs,onSubChannelUpdated:yc,onSubChannelDeleted:as,getSubChannel:(e,t)=>{const n=Ee();let r;return lo(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:ln(e.data)}),a=Zt(n,["origin"]);return Zn(r,a)?void 0:(r=a,t(n))}),"subChannelId",Pn,[Cc,t=>yc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Nn(r),r.subChannelId===e&&t(r))})),as,mi(Cs,"feedId","subChannel"),t=>Is((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const a=null===(r=Pe(["subChannel","get",e]))||void 0===r?void 0:r.data;a&&t(a)})),mi((t=>ts((async n=>{n.subChannelId===e&&(await Un(n),t(n))}))),"subChannelId","subChannel"),mi((t=>ns((async n=>{n.subChannelId===e&&(await Un(n),t(n))}))),"subChannelId","subChannel"),mi((t=>mc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(xn(r),t(r))}))),"subChannelId","subChannel"),mi((t=>gc((async r=>{const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&r.subChannelId===e&&("message-preview-include-deleted"===a&&await xn(r),"message-preview-not-include-deleted"===a&&await Pn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),mi(Fc,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),a||console.log(V);const o=new Qc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:Zr,startMessageReceiptSync:async e=>(await Vc(e),!0),stopMessageReceiptSync:e=>(zc[e]&&zc[e](),!0)});const Jc=e=>{const t=Ee();return st(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},Wc=e=>{const t=Ee();return st(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Gc extends Ws{async getRequest(e,t){const{limit:n=Q,displayName:r,membership:a}=e,s=Zt(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:r,filter:a,options:o})});return i}}class Yc extends eo{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Zc extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channels.map(be("channel"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(be("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Yc)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(be("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Xc=e=>{const t=Ee();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Da().resolve(e.channelId,"userMessageFeedMarker")}},el=e=>{const t=Ee();return st(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class tl extends to{constructor(e,t){const n=C.default(e),r=["channel","collection",n],a=tl.getPaginationController(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Zc(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ee();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(e)}catch(e){console.error("Error while preparing unread count info",e)}return $n(e)}),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=null!==(a=s.data.map((e=>Pe(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Fr))&&void 0!==a?a:[];this.paginationController instanceof Gc&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Gc?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof Gc&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ee();let n=e;switch(n=De(n,"isDeleted",this.query.isDeleted),n=qe(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=Be(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ve);break;case"lastCreated":n=n.sort(Je);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Qe);break;default:n=n.sort(Ye)}return n}shouldAbort(e){var t,n;const r=null===(t=Pe(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 Ee().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Yc(e):new Gc(e)}getSubscriptions(){const e=[{fn:mi((e=>ts((t=>{var n,r;const a=Da();(null===(n=Pe(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||a.resolve(t.subChannelId,"userMessageFeedMarker");const s=null===(r=Pe(["channel","get",t.channelId]))||void 0===r?void 0:r.data;s?(vc(s,{lastActivity:t.createdAt}),e(t)):a.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>ns((t=>{var n;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(vc(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:lr,action:"onDelete"},{fn:ar,action:"onUpdate"},{fn:vr,action:"onMute"},{fn:e=>hr((t=>{Xc(t),e(t)})),action:"onJoin"},{fn:e=>mr(((t,n)=>{var r,a;const{userId:s}=Ee();if("member"===this.query.membership&&s===n.userId){const e=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;Me(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(a=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==a?a:[]}))}return e(t)})),action:"onLeft"},{fn:Cr,action:"onMemberAdded"},{fn:_r,action:"onMemberRemoved"},{fn:mi(ws,"entityId","channel"),action:"onUpdate"},{fn:mi(bc,"entityId","channel"),action:"onUpdate"},{fn:mi((e=>ts((async t=>{var n;if("no-message-preview"===await tl.getMessagePreviewSetting())return;if(Dn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(vc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>ns((async t=>{var n;if("no-message-preview"===await tl.getMessagePreviewSetting())return;if(Dn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(vc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>mc((async t=>{"no-message-preview"!==await tl.getMessagePreviewSetting()&&(qn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>gc((async t=>{const n=await tl.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await qn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await mo(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>as((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=an(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await mo(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:mi((e=>yc((async t=>{var n;if("no-message-preview"===await tl.getMessagePreviewSetting())return;(null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data)&&(await Nn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:mi(rs,"channelId","channel"),action:"onUpdate"},{fn:el,action:"onResolveChannel"},{fn:e=>(e=>{const t=Ee();return st(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Pe(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:mi(Jc,"channelId","channel"),action:"onUpdate"},{fn:mi((e=>Wc((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Ws?[...e,{fn:e=>tr((t=>{Xc(t),e(t)})),action:"onCreate"}]:e}}const nl=()=>{var e;const t=Ee();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Re(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class rl extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(a.channelId)}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class al extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>be("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>be("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=be("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==a)):r.data.includes(a)||(r.data=[a,...r.data]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sl extends to{constructor(e,t){const n=C.default(e),r=["channelUsers","collection",n];super(new rl(e),n,r,t),this.query=e,this.queryStreamController=new al(this.query,this.cacheKey,this.notifyChange.bind(this),$n),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:hr,action:"onJoin"},{fn:mr,action:"onLeft"},{fn:Cr,action:"onMemberAdded"},{fn:_r,action:"onMemberRemoved"},{fn:Tr,action:"onChannelMemberBanned"},{fn:Rr,action:"onChannelMemberUnbanned"},{fn:jr,action:"onChannelMemberRoleAdded"},{fn:Dr,action:"onChannelMemberRoleRemoved"},{fn:Br,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{var r,a;const s=ua(n);if(0===s.users.length)return;const o=s.users[0];Gt(s);const i=be("channelUsers")({channelId:e,userId:o.userId}),c=null===(r=Pe(["channelUsers","get",i]))||void 0===r?void 0:r.data;Ue(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ei.channelMember))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?Je:Ve),t}}const ol=(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new sl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var il=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ee();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=>ot("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await $n(r);n.cache&&Gt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ee();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=>ot("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await $n(r);n.cache&&Gt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Ne(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Je:Ve),n},getMembers:ol,searchMembers:(e,t,n)=>ol(e,t)});var cl=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Ee();r.log("channel/addRole",e,t,n);const{data:a}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await $n(a);r.cache&&Gt(s),ot("local.channel-moderator.role-added",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Ee();r.log("channel/removeRole",e,t,n);const{data:a}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await $n(a);r.cache&&Gt(s),ot("local.channel-moderator.role-removed",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ee();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),a=await $n(r),{channelUsers:s}=a,o=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:o}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ee();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),a=await $n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{channelUsers:o}=a;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{const r=Ee();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:a}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:s}=a;return s},unmuteMembers:async(e,t)=>{const n=Ee();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:a}=r;return a}}),ll=Object.freeze({__proto__:null,Membership:il,Moderation:cl,getChannelByIds:Kr,createChannel:fo,updateChannel:async(e,t)=>{const n=Ee();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),a=await $n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{channels:o}=a;return{data:Wn(o.find((t=>t.channelId===e))),cachedAt:s}},deleteChannel:async e=>{const t=Ee();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await mo(e);return Wn(n.data)},joinChannel:async e=>{const t=Ee();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await $n(n);t.cache&&Gt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ee();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await $n(n);t.cache&&Gt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ee();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Ie("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:a}=r;return a},unmuteChannel:async e=>{const t=Ee();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},onChannelCreated:tr,onChannelUpdated:ar,onChannelDeleted:lr,onChannelJoined:hr,onChannelLeft:mr,onChannelSetMuted:vr,onChannelMemberAdded:Cr,onChannelMemberRemoved:_r,onChannelMemberBanned:Tr,onChannelMemberUnbanned:Rr,onChannelMemberRoleAdded:jr,onChannelMemberRoleRemoved:Dr,getChannel:(e,t)=>{const n=Ee();let r;return lo(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Fr(e.data)}),a=Zt(n,["origin"]);return Zn(r,a)?void 0:(r=a,t(n))}),"channelId",mo,[ar,lr,hr,mr,Cr,_r,Tr,Rr,vr,mi(ws,"entityId","channel"),mi(bc,"entityId","channel"),mi((t=>ts((async r=>{await(async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dn(r),r.channelId!==e)return;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;s&&(vc(s,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),mi((t=>ns((async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dn(r),r.channelId!==e)return;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;s&&(vc(s,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),mi((t=>mc((async r=>{var a;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await qn(r),t(r))}))),"channelId","channel"),mi((t=>gc((async r=>{var a;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(xe(["messagePreviewChannel","get",e]),await mo(r.channelId)):await qn(r),t(r))}))),"channelId","channel"),mi((e=>as((async t=>{var r,a;const{channelId:s,subChannelId:o}=t,i=null===(r=Pe(["messagePreviewChannel","get",s]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await mo(s);(null===(a=Pe(["channel","get",s]))||void 0===a?void 0:a.data)&&e(t)}))),"channelId","channel"),mi((t=>yc((async r=>{var a,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Nn(r);const o=null===(a=Pe(["messagePreviewChannel","get",e]))||void 0===a?void 0:a.data;if(!o||o.subChannelId!==r.subChannelId)return;(null===(s=Pe(["channel","get",e]))||void 0===s?void 0:s.data)&&t(r)}))),"channelId","channel"),mi(rs,"channelId","channel"),mi(Jc,"channelId","channel"),mi((e=>Wc((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getChannels(tmpid: ${o}) > listen`);const i=new tl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Xe();if(!t)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ee();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Ts(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(Wc((e=>{const{data:t}=nl();Zn(s,t)||i({loading:!1,data:t})}))),(()=>{const e=fe((async()=>nl()));ge(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e()))}))})(),()=>{a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Bn,isUnreadCountSupport:Ln,convertFromRaw:Fn,preUpdateChannelCache:Kn,prepareChannelPayload:$n});const dl=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Me(["communityUsers","collection",e],n)}))},ul=async(e,t)=>{const n=Ee();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:a}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),s=Ao(a),o=n.cache&&Date.now();return n.cache&&(Gt(s,{cachedAt:o}),dl(s.communities,s.communityUsers)),{data:s.communities.map((e=>ei.community(e))),cachedAt:o}};ul.locally=e=>{var t;const n=Ee();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Pe(["community","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a,cachedAt:s.cachedAt}};const hl=async e=>{const t=Ee();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Ao(n),a=t.cache&&Date.now();t.cache&&(Gt(r,{cachedAt:a}),dl(r.communities,r.communityUsers));const{communities:s}=r;return{data:s.find((t=>t.communityId===e)),cachedAt:a}};hl.locally=e=>{const t=Ee();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Pe(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pl=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Ao(e);if(n.cache){Gt(r);const e=Pe(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},fl=e=>pl("community.created",e),ml=e=>pl("community.updated",e),gl=e=>pl("community.deleted",e);class yl extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=Zt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:yn(a.includeDeleted),keyword:a.displayName,filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class vl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var bl,wl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(bl||(bl={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(wl||(wl={}));class Cl extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class Il extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=be("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Sl(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function _l(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!Sl(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!Sl(e,t,"ADD_COMMUNITY_USER")))}const kl=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{const a=Ao(r),{communities:s,communityUsers:o}=a,i=Oo(s,o);if(a.communities=i,n.cache){Gt(a,void 0,!1);const n=Pe(["community","get",a.communities[0].communityId]),r=_l(e,a).map((e=>{const t=Pe(["communityUsers","get",be("communityUsers")(e)]);return null==t?void 0:t.data})).filter(no);t(n.data,r)}else t(a.communities[0],_l(e,a))}))},Ol=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{const a=Ao(r),{communities:s,communityUsers:o}=a,i=Oo(s,o);if(a.communities=i,n.cache){Gt(a,void 0,!1);const n=Pe(["community","get",a.communities[0].communityId]),r=_l(e,a).map((e=>{const t=Pe(["communityUsers","get",be("communityUsers")(e)]);return null==t?void 0:t.data})).filter(no);t(n.data,r)}else t(a.communities[0],_l(e,a))}))},Tl=e=>kl("community.userBanned",e),El=e=>kl("community.userChanged",e),Al=e=>kl("community.userUnbanned",e),Rl=e=>kl("community.roleAdded",e),Pl=e=>kl("community.roleRemoved",e),Ml=e=>Ol("local.community.userAdded",e),jl=e=>Ol("local.community.userRemoved",e),Ul=e=>kl("community.joined",e),xl=e=>kl("community.left",e),Dl=e=>Ol("local.community.joined",e),ql=e=>Ol("local.community.left",e),Nl=e=>{const t=Ee(),n=[st(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Bl=e=>{const t=Ee();return st(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Ll=e=>{const t=Ee();return st(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Fl=e=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{var r,a;const s=ua(n);if(0===s.users.length)return;const o=s.users[0];Gt(s);const i=be("communityUsers")({communityId:e,userId:o.userId}),c=null===(r=Pe(["communityUsers","get",i]))||void 0===r?void 0:r.data;Me(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Pe(["community","get",e]))||void 0===a?void 0:a.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class Kl extends to{constructor(e,t){const n=C.default(e),r=["communityUsers","collection",n];super(new Cl(e),n,r,t),this.query=e,this.queryStreamController=new Il(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Ul,action:wl.OnCommunityJoined},{fn:Dl,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:ql,action:wl.OnCommunityLeft},{fn:Tl,action:wl.OnCommunityUserBanned},{fn:El,action:wl.OnCommunityUserChanged},{fn:Rl,action:wl.OnCommunityUserRoleAdded},{fn:Pl,action:wl.OnCommunityUserRoleRemoved},{fn:Ll,action:wl.OnCommunityUserRoleAdded},{fn:Bl,action:wl.OnCommunityUserRoleRemoved},{fn:Al,action:wl.OnCommunityUserUnbanned},{fn:Ml,action:wl.OnCommunityUserAdded},{fn:jl,action:wl.onCommunityUserRemoved},{fn:Fl(this.query.communityId),action:wl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["communityUsers","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(Ve);else t=t.sort(Je);return t}}class $l extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class Ql extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=be("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var zl;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(zl||(zl={}));class Vl extends to{constructor(e,t){const n=C.default(e),r=["communityUsers","collection",n];super(new $l(e),n,r,t),this.query=e,this.queryStreamController=new Ql(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Ul,action:zl.OnCommunityJoined},{fn:Dl,action:zl.OnCommunityJoined},{fn:xl,action:zl.OnCommunityLeft},{fn:ql,action:zl.OnCommunityLeft},{fn:Tl,action:zl.OnCommunityUserBanned},{fn:El,action:zl.OnCommunityUserChanged},{fn:Bl,action:zl.OnCommunityUserRoleRemoved},{fn:Pl,action:zl.OnCommunityUserRoleRemoved},{fn:Al,action:zl.OnCommunityUserUnbanned},{fn:Fl(this.query.communityId),action:zl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["communityUsers","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=$e(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var Hl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ee();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ot("local.community.userAdded",r);const a=en(r,"communityUsers");n.cache&&Gt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ee();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ot("local.community.userRemoved",r);const a=en(r,"communityUsers");n.cache&&Gt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Ne(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Je:Ve),n},getMembers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new Kl(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new Vl(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>kl("community.userAdded",e),onCommunityUserRemoved:e=>kl("community.userRemoved",e),onCommunityUserBanned:Tl,onCommunityUserChanged:El,onCommunityUserUnbanned:Al,onCommunityUserRoleAdded:Rl,onCommunityUserRoleRemoved:Pl,onLocalCommunityUserAdded:Ml,onLocalCommunityUserRemoved:jl,onCommunityJoined:Ul,onCommunityLeft:xl,onLocalCommunityJoined:Dl,onLocalCommunityLeft:ql,onLocalCommunityJoin:Nl});class Jl extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new yl(e),n,r,t),this.query=e,this.queryStreamController=new vl(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:gl,action:bl.OnCommunityDeleted},{fn:ml,action:bl.OnCommunityUpdated},{fn:Ul,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:El,action:wl.OnMemberCountChanged},{fn:Dl,action:wl.OnCommunityJoined},{fn:ql,action:wl.OnCommunityLeft},{fn:mi(Nl,"targetId","community"),action:bl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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}=Ee();let n=e;return this.query.includeDeleted||(n=De(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=Fe(n,this.query.membership,t)),n}}class Wl extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=Zt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:yn(a.includeDeleted),filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class Gl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),dl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Yl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Yl||(Yl={}));class Zl extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new Wl(e),n,r,t),this.query=e,this.queryStreamController=new Gl(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:fl,action:Yl.OnCommunityCreated},{fn:gl,action:Yl.OnCommunityDeleted},{fn:ml,action:Yl.OnCommunityUpdated},{fn:Ul,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:El,action:wl.OnMemberCountChanged},{fn:Dl,action:wl.OnCommunityJoined},{fn:ql,action:wl.OnCommunityLeft},{fn:mi(Nl,"targetId","community"),action:Yl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>Xo(e))))&&void 0!==a?a:[];(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}=Ee();let n=e;this.query.includeDeleted||(n=De(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=Fe(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return n=n.sort(r),n}}class Xl extends Ws{async getRequest(e,t){const{limit:n=Q,includeDiscoverablePrivateCommunity:r}=e,a=Zt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class ed extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),dl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var td;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(td||(td={}));class nd extends to{constructor(e,t){const n=C.default(e),r=["trendingCommunity","collection",n];super(new Xl(e),n,r,t),this.query=e,this.queryStreamController=new ed(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:gl,action:td.OnCommunityDeleted},{fn:ml,action:td.OnCommunityUpdated},{fn:Ul,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:El,action:wl.OnMemberCountChanged},{fn:Dl,action:wl.OnCommunityJoined},{fn:ql,action:wl.OnCommunityLeft},{fn:mi(Nl,"targetId","community"),action:td.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>Xo(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class rd extends Ws{async getRequest(e,t){const{limit:n=Q,includeDiscoverablePrivateCommunity:r}=e,a=Zt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class ad extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),dl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var sd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(sd||(sd={}));class od extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new rd(e),n,r,t),this.query=e,this.queryStreamController=new ad(this.query,this.cacheKey,this.notifyChange.bind(this),Ao),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:gl,action:sd.OnCommunityDeleted},{fn:ml,action:sd.OnCommunityUpdated},{fn:Ul,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:El,action:wl.OnMemberCountChanged},{fn:Dl,action:wl.OnCommunityJoined},{fn:ql,action:wl.OnCommunityLeft},{fn:mi(Nl,"targetId","community"),action:sd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>Xo(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class id extends Ws{async getRequest(e,t){var n;const{limit:r=Q,communityMembershipStatus:a}=e,s=Zt(e,["limit","communityMembershipStatus"]),o={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:r}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=a?a:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function cd(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class ld extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:cd(e)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...cd(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var dd;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(dd||(dd={}));class ud extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new id(e),n,r,t),this.query=e,this.queryStreamController=new ld(this.query,this.cacheKey,this.notifyChange.bind(this),jo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:fl,action:dd.OnCommunityCreated},{fn:gl,action:dd.OnCommunityDeleted},{fn:ml,action:dd.OnCommunityUpdated},{fn:Ul,action:wl.OnCommunityJoined},{fn:xl,action:wl.OnCommunityLeft},{fn:El,action:wl.OnMemberCountChanged},{fn:Dl,action:wl.OnCommunityJoined},{fn:ql,action:wl.OnCommunityLeft},{fn:mi(Nl,"targetId","community"),action:dd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Pe(["community","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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}=Ee();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=Fe(n,this.query.communityMembershipStatus,t)),n}}class hd extends Ws{async getRequest(e,t){const{limit:n=Q,communityIds:r}=e,a=Zt(e,["limit","communityIds"]),s=t?{token:t}:{limit:n},o=r.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},a),{options:s,communityIds:o})});return i}}var pd;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(pd||(pd={}));class fd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===pd.OnLocalJoinRequestUpdated){if(!r.data.find((e=>a.includes(e))))return}e===pd.OnLocalJoinRequestCreated&&(r.data=[...new Set([...a,...r.data])]),e===pd.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!a.includes(e)))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class md extends to{constructor(e,t){const n=C.default(e),r=["joinRequestList","collection",n];super(new hd(e),n,r,t),this.query=e,this.queryStreamController=new fd(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:No,action:pd.OnLocalJoinRequestCreated},{fn:Bo,action:pd.OnLocalJoinRequestUpdated},{fn:Lo,action:pd.OnLocalJoinRequestUpdated},{fn:Nl,action:pd.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Pe(["joinRequest","get",e]))).filter(no).map((({data:e})=>e)).map(Uo));(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;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}var gd;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(gd||(gd={}));var yd=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Ee();r.log("community/moderation/addRoles",e,t,n);const{data:a}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=Po(a);r.cache&&Gt(s),ot("local.community.roleAdded",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Ee();r.log("community/moderation/removeRoles",e,t,n);const{data:a}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=Po(a);r.cache&&Gt(s),ot("local.community.roleRemoved",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ee();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Ee();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}}}),vd=Object.freeze({__proto__:null,Moderation:yd,Membership:Hl,getCommunityByIds:ul,createCommunity:async e=>{const t=Ee();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Mo(e));ot("community.created",n);const r=Ao(n),a=t.cache&&Date.now();t.cache&&(Gt(r,{cachedAt:a}),dl(r.communities,r.communityUsers));const{communities:s}=r;return{data:ei.community(s[0]),cachedAt:a}},updateCommunity:async(e,t)=>{const n=Ee();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Mo(t));ot("community.updated",r);const a=Ao(r),s=n.cache&&Date.now();n.cache&&(Gt(a,{cachedAt:s}),dl(a.communities,a.communityUsers));const{communities:o}=a;return{data:ei.community(o.find((t=>t.communityId===e))),cachedAt:s}},deleteCommunity:async e=>{const t=Ee();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await hl(e);return ot("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),ei.community(n.data)},joinCommunity:async e=>{const t=Ee();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ot("local.community.joined",n);const r=Ao(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ee();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ot("local.community.left",n);const r=Ao(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:fl,onCommunityUpdated:ml,onCommunityDeleted:gl,searchCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`searchCommunities(tmpid: ${s}) > listen`);const o=new Jl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCommunities(tmpid: ${s}) > listen`);const o=new Zl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>lo(e,t,"communityId",hl,[ml,gl,Ul,xl,Dl,ql,Tl,Al,El,mi(Nl,"targetId","community")],{callbackDataSelector:e=>e?ei.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new nd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>xe(l))),()=>{r(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new od(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>xe(l))),()=>{r(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`semanticSearchCommunities(tmpid: ${s}) > listen`);const o=new ud(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`semanticSearchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getJoinRequestList: (tmpid: ${s}) > listen`);const o=new md(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getJoinRequestList (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return gd}});const bd=async e=>{const t=Ee();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&&Gt(n,{cachedAt:r});const{categories:a}=n;return{data:ei.category(a.find((t=>t.categoryId===e))),cachedAt:r}};bd.locally=e=>{const t=Ee();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Pe(["category","get",e]);return n?{data:ei.category(n.data),cachedAt:n.cachedAt}:void 0};const wd=async e=>{const t=Ee();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:a,includeDeleted:s}=n,o=Zt(n,["page","limit","includeDeleted"]),i=r?{token:r}:a?{limit:a}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:yn(s),options:i})}),{paging:l}=c,d=Zt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Gt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:s,options:i})];Me(e,{categories:null==u?void 0:u.map(be("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};wd.locally=e=>{var t,n;const r=Ee();if(r.log("category/queryCategories.locally",e),!r.cache)return;const a=null!=e?e:{},{page:s,limit:o=10}=a,i=Zt(a,["page","limit"]),c=s?{token:s}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Pe(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Pe(["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 Cd=Object.freeze({__proto__:null,getCategory:bd,getCategories:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:o}=e,i=Zt(e,["limit"]),c=null!=o?o:Q,{policy:l=z}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,a;const s=null===(r=Pe(u))||void 0===r?void 0:r.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];if(!n&&o.length>0&&!(null==s?void 0:s.params.page))return;const d=fe(wd,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));ge(d,(({data:n,error:r,loading:a,paging:s})=>{const i={loading:a,error:r,params:{page:null==s?void 0:s.next},data:o};n&&(i.data=[...new Set([...o,...n.map(be("category"))])]),Me(u,i),(n=>{var r,a;let s=null!==(r=n.data.map((e=>Pe(["category","get",e]))).filter(Boolean).map((({data:e})=>ei.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(s=De(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(Ve);break;case"lastCreated":s=s.sort(Je);break;default:s=s.sort(ze)}t({onNextPage:h,data:s,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})})(i)}),me(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Id=async e=>{const t=Ee();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:a}=n,s=Zt(n,["queryToken","dataTypes"]),o=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})}),{paging:c}=i,l=Zt(i,["paging"]),d=en(l,"communityUsers"),{posts:u}=d,{communities:h}=Ao(d),p=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:o})];Me(e,{posts:u.map(be("post")),paging:c})}return{data:u.map(ei.post),cachedAt:p,paging:c}};Id.locally=e=>{var t,n;const r=Ee();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const a=Zt(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Pe(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ei.post),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};class Sd extends Ws{async getRequest(e,t){const{limit:n}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:a})});return s}}var _d;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(_d||(_d={}));class kd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===_d.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===_d.OnPostCreated||e===_d.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===_d.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Od=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("comment",e)})),t}const a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.comments.map((e=>ei.comment(e))),cachedAt:a}};Od.locally=e=>{var t;const n=Ee();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Pe(["comment","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a.map((e=>ei.comment(e))),cachedAt:s.cachedAt}};const Td=(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})},Ed=async e=>{const t=Ee();t.log("story/getStoryByStoryId",e);const n=Pe(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;pn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Td(n.data)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("story",e),t}const a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.stories[0],cachedAt:a}};Ed.locally=e=>{const t=Ee();t.log("story/getStorybyStoryId",e);const n=Pe(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;pn("story",e)}const r=t.cache&&Date.now(),a=Pe(["story","get",e]);if(a)return{data:a.data,cachedAt:r}};const Ad=async(e,t=!1)=>{var n;const r=Ee(),a=await Pi(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});if(t?rt((()=>Yt("comment",e))):Ue(["comment","get",e],{isDeleted:!0}),"story"===a.data.referenceType){const e=await Ed(a.data.referenceId);ot("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Pe(["post","get",a.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=s.parentId?1:s.childrenNumber+1,e.commentsCount-=t,ot("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return ot("local.comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),s},Rd=async e=>{const t=Ee();let n;t.log("comment/getComment",e),pn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{comments:a}=n;return{data:a.find((t=>t.commentId===e)),cachedAt:r}};Rd.locally=e=>{const t=Ee();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Pe(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Pd=e=>ec("local.comment.deleted",e),Md=e=>{const t=Ee();return st(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(Ue(["comment","get",n.commentId],n),e(vo(n))):e(n)}))},jd=e=>{const t=Ee();return st(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(Ue(["comment","get",n.commentId],n),e(vo(n))):e(n)}))};class Ud extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s={type:a.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},a),{isDeleted:yn(r),options:o})});return i}}var xd;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(xd||(xd={}));class Dd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.comments.map(be("comment"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(be("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===xd.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const qd=e=>ec("local.comment.created",e);class Nd extends to{constructor(e,t){const n=C.default(e),r=["comments","collection",n];super(new Ud(e),n,r,t),this.query=e,this.queryStreamController=new Dd(this.query,this.cacheKey,this.notifyChange.bind(this),fc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:qd,action:xd.OnCommentCreated},{fn:Pd,action:xd.OnCommentDeleted},{fn:tc,action:xd.OnCommentCreated},{fn:nc,action:xd.OnCommentUpdated},{fn:rc,action:xd.OnCommentDeleted},{fn:ac,action:xd.OnCommentFlagged},{fn:sc,action:xd.OnCommentUnflagged},{fn:oc,action:xd.OnCommentReactionAdded},{fn:ic,action:xd.OnCommentReactionRemoved},{fn:Md,action:xd.OnCommentReactionAdded},{fn:jd,action:xd.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["comment","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.comment);(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;if(this.query.includeDeleted||(t=De(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],a=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return a.length===r.length&&r.every(((e,t)=>e===a[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(Ve);else t=t.sort(Je);return t}}var Bd=Object.freeze({__proto__:null,getCommentByIds:Od,createComment:async e=>{var t;const n=Ee();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:a}=r;if(0===a.length)throw new Error("Comment not created");const s=n.cache&&Date.now();if(n.cache&&Gt(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const n=null===(t=Pe(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,ot("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Pe(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Pe(["story","get",t.data]);(null==e?void 0:e.data)&&ot("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,a[0].commentId])]})],categories:[],comments:a,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return ot("local.comment.created",r),{data:ei.comment(a[0]),cachedAt:s}},updateComment:async(e,t)=>{const n=Ee();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a}),ot("comment.updated",r);const{comments:s}=r;return{data:ei.comment(s.find((t=>t.commentId===e))),cachedAt:a}},deleteComment:Ad,softDeleteComment:async e=>{Ee().log("comment/softDeleteComment",e);return Ad(e)},hardDeleteComment:async e=>{Ee().log("comment/hardDeleteComment",e);return Ad(e,!0)},flagComment:async(t,n)=>{const r=Ee();r.log("comment/flagComment",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,s);return r.cache&&Gt(o),ot("comment.flagged",o),!!o},unflagComment:async e=>{const t=Ee();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Gt(n),ot("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ee();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:tc,onCommentUpdated:nc,onCommentDeleted:rc,onCommentFlagged:ac,onCommentUnflagged:sc,onCommentReactionAdded:oc,onCommentReactionRemoved:ic,getComment:(e,t)=>lo(e,t,"commentId",Rd,[Pd,rc,ac,oc,ic,sc,nc,Md,jd]),getComments:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const o=new Nd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Ld=async e=>{const t=Ee();let n;t.log("post/getPost",e),pn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("post",e),t}const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};Ld.locally=e=>{const t=Ee();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Pe(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Fd=e=>$i("local.post.deleted",e),Kd=e=>{const t=Ee();return st(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(Ue(["post","get",n.postId],n),e(n)):e(n)}))},$d=e=>{const t=Ee();return st(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(Ue(["post","get",n.postId],n),e(n)):e(n)}))},Qd=e=>$i("local.post.updated",e),zd=e=>[tc,rc,oc,ic,qd,Pd,Md,jd].map((t=>({fn:mi((n=>((e,t,n)=>t((async t=>{var r;const a=null===(r=Pe(n))||void 0===r?void 0:r.data;a&&a.data.includes(t.referenceId)&&(await Ld(t.referenceId),e(t))})))(n,t,e)),"referenceId","post"),action:_d.OnPostUpdated}))),Vd=e=>[{fn:Qi,action:_d.OnPostCreated},{fn:zi,action:_d.OnPostUpdated},{fn:Qd,action:_d.OnPostUpdated},{fn:Vi,action:_d.OnPostDeleted},{fn:Wi,action:_d.OnPostFlagged},{fn:Gi,action:_d.OnPostUnflagged},{fn:Hi,action:_d.OnPostApproved},{fn:Ji,action:_d.OnPostDeclined},{fn:Yi,action:_d.OnPostReactionAdded},{fn:Zi,action:_d.OnPostReactionRemoved},{fn:Kd,action:_d.OnPostReactionAdded},{fn:$d,action:_d.OnPostReactionRemoved},{fn:Fd,action:_d.OnPostDeleted},...zd(e)];class Hd extends to{constructor(e,t){const n=C.default(e),r=["customRankingGlobalFeed","collection",n];super(new Sd(e),n,r,t),this.query=e,this.queryStreamController=new kd(this.query,this.cacheKey,this.notifyChange.bind(this),Bi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(Vd(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Jd extends Ws{async getRequest(e,t){const{limit:n,dataTypes:r}=e,a=Zt(e,["limit","dataTypes"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:s})});return o}}class Wd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===_d.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===_d.OnPostCreated||e===_d.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===_d.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Gd extends to{constructor(e,t){const n=C.default(e),r=["globalFeed","collection",n];super(new Jd(e),n,r,t),this.query=e,this.queryStreamController=new Wd(this.query,this.cacheKey,this.notifyChange.bind(this),Bi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(Vd(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Yd extends Ws{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:a,includeDeleted:s,matchingOnlyParentPost:o,limit:i=Q}=e,c=Zt(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit"]),l=t?{token:t}:{limit:i},{data:d}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:l,dataTypes:(null==a?void 0:a.length)?a:void 0,includePostedFeed:r,isDeleted:yn(s),matchingOnlyParentPost:null!=o?o:!(null==a?void 0:a.length)})});return d}}class Zd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(this.query.dataTypes&&0!==this.query.dataTypes.length||a.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(e===_d.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}if(e===_d.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e===_d.OnPostCreated||e===_d.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xd extends to{constructor(e,t){const n=C.default(e),r=["userFeed","collection",n];super(new Yd(e),n,r,t),this.query=e,this.queryStreamController=new Zd(this.query,this.cacheKey,this.notifyChange.bind(this),Bi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Qi,action:_d.OnPostCreated},{fn:zi,action:_d.OnPostUpdated},{fn:Qd,action:_d.OnPostUpdated},{fn:Vi,action:_d.OnPostDeleted},{fn:Wi,action:_d.OnPostFlagged},{fn:Gi,action:_d.OnPostUnflagged},{fn:Hi,action:_d.OnPostApproved},{fn:Ji,action:_d.OnPostDeclined},{fn:Yi,action:_d.OnPostReactionAdded},{fn:Zi,action:_d.OnPostReactionRemoved},{fn:Kd,action:_d.OnPostReactionAdded},{fn:$d,action:_d.OnPostReactionRemoved},{fn:Fd,action:_d.OnPostDeleted},{fn:mi((e=>tc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ld(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated},{fn:mi((e=>rc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ld(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var eu=Object.freeze({__proto__:null,queryGlobalFeed:Id,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${s}) > listen`);const o=new Hd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getGlobalFeed(tmpid: ${s}) > listen`);const o=new Gd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getUserFeed(tmpid: ${s}) > listen`);const o=new Xd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getUserFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const tu=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("post",e)})),t}const a=en(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),{data:a.posts.map(ei.post),cachedAt:s}};tu.locally=e=>{var t;const n=Ee();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Pe(["post","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a.map(ei.post),cachedAt:s.cachedAt}};const nu=async(e,t=!1)=>{var n;const r=Ee(),a=await Ri(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===a.data.targetType){const e=await hl(a.data.targetId),t=(null!==(n=Re(["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));ot("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});return t?setTimeout((()=>{Yt("post",e)}),0):Ue(["post","get",e],{isDeleted:!0}),ot("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),ei.post(s)};class ru extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r,matchingOnlyParentPost:a}=e,s=Zt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:o}=s,i={type:s.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},s),{isDeleted:yn(r),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:c})});return l}}class au extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===_d.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==_d.OnPostCreated&&e!==_d.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const su=({cacheKey:e,resolveId:t})=>[tc,rc,oc,ic,qd,Pd,Md,jd].map((n=>({fn:mi((r=>((e,t,n,r)=>t((async t=>{var a;const s=null===(a=Pe(n))||void 0===a?void 0:a.data;s&&s.data.includes(r?r(t.referenceId):t.referenceId)&&(await Ld(t.referenceId),e(t))})))(r,n,e,t)),"referenceId","post"),action:_d.OnPostUpdated})));class ou extends to{constructor(e,t){const n=C.default(e),r=["posts","collection",n];super(new ru(e),n,r,t),this.query=e,this.queryStreamController=new au(this.query,this.cacheKey,this.notifyChange.bind(this),Bi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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((e=this.cacheKey,[{fn:Qi,action:_d.OnPostCreated},{fn:zi,action:_d.OnPostUpdated},{fn:Qd,action:_d.OnPostUpdated},{fn:Vi,action:_d.OnPostDeleted},{fn:Wi,action:_d.OnPostFlagged},{fn:Gi,action:_d.OnPostUnflagged},{fn:Hi,action:_d.OnPostApproved},{fn:Ji,action:_d.OnPostDeclined},{fn:Yi,action:_d.OnPostReactionAdded},{fn:Zi,action:_d.OnPostReactionRemoved},{fn:Kd,action:_d.OnPostReactionAdded},{fn:$d,action:_d.OnPostReactionRemoved},{fn:Fd,action:_d.OnPostDeleted},...su({cacheKey:e})]));var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=De(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Le(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Ke(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ve);else n=n.sort(Je);return n}}class iu extends Ws{async getRequest(e,t){const n=Zt(e,["limit"]),{communityId:r,placement:a}=n,s=a?`/api/v1/pinned-posts/communities/${r}/${a}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(s);return o}}class cu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(Tn):[]});Gt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(be("pin"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(be("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===_d.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class lu extends to{constructor(e,t){const n=C.default(e),r=["pinnedPosts","collection",n];super(new iu(e),n,r,t),this.query=e,this.queryStreamController=new cu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(su({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=(null!==(a=s.data.map((e=>Pe(["pin","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Je({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class du extends Ws{async getRequest(e,t){Zt(e,["limit"]);const{data:n}=await this.http.get("/api/v1/pinned-posts/global");return n}}class uu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(Tn)});Gt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(be("pin"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(be("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===_d.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hu extends to{constructor(e,t){const n=C.default(e),r=["pinnedPosts","collection",n];super(new du(e),n,r,t),this.query=e,this.queryStreamController=new uu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Fd,action:_d.OnPostDeleted},{fn:Vi,action:_d.OnPostDeleted},...su({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["pin","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class pu extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:s})});return o}}function fu(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function mu(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class gu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:fu(e)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...fu(e)])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===_d.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==_d.OnPostCreated&&e!==_d.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class yu extends to{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=C.default(n),a=["posts","collection",r];super(new pu(n),r,a,t),this.query=n,this.queryStreamController=new gu(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:zi,action:_d.OnPostUpdated},{fn:Vi,action:_d.OnPostDeleted},{fn:Wi,action:_d.OnPostFlagged},{fn:Gi,action:_d.OnPostUnflagged},{fn:Hi,action:_d.OnPostApproved},{fn:Ji,action:_d.OnPostDeclined},{fn:Yi,action:_d.OnPostReactionAdded},{fn:Zi,action:_d.OnPostReactionRemoved},{fn:mi((e=>tc((async t=>{const n=Pe(this.cacheKey);mu(null==n?void 0:n.data).includes(t.referenceId)||(await Ri(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated},{fn:mi((e=>rc((async t=>{const n=Pe(this.cacheKey);mu(null==n?void 0:n.data).includes(t.referenceId)||(await Ri(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(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.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=Ke(t,this.query.dataTypes)),t}}class vu extends Ws{async getRequest(e,t){const{limit:n=Q,matchingOnlyParentPost:r,hashtags:a,dataTypes:s,targetType:o="all"}=e,i=Zt(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:i.sortBy||e.limit?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},i),{hashtags:a,dataTypes:s,targetType:o,matchingOnlyParentPost:null!=r?r:!(null==s?void 0:s.length),options:l})});return d}}class bu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}e===_d.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==_d.OnPostCreated&&e!==_d.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class wu extends to{constructor(e,t){const n=C.default(e),r=["posts","collection",n];super(new vu(e),n,r,t),this.query=e,this.queryStreamController=new bu(this.query,this.cacheKey,this.notifyChange.bind(this),Bi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Qi,action:_d.OnPostCreated},{fn:zi,action:_d.OnPostUpdated},{fn:Qd,action:_d.OnPostUpdated},{fn:Vi,action:_d.OnPostDeleted},{fn:Wi,action:_d.OnPostFlagged},{fn:Gi,action:_d.OnPostUnflagged},{fn:Hi,action:_d.OnPostApproved},{fn:Ji,action:_d.OnPostDeclined},{fn:Yi,action:_d.OnPostReactionAdded},{fn:Zi,action:_d.OnPostReactionRemoved},{fn:Kd,action:_d.OnPostReactionAdded},{fn:$d,action:_d.OnPostReactionRemoved},{fn:Fd,action:_d.OnPostDeleted},{fn:mi((e=>tc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ld(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated},{fn:mi((e=>rc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ld(t.referenceId),e(t))}))),"referenceId","post"),action:_d.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Ke(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ve);else n=n.sort(Je);return n}}var Cu=Object.freeze({__proto__:null,getPostByIds:tu,createPost:async e=>{const t=Ee();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);ot("post.created",n);const r=Bi(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:ei.post(s[0]),cachedAt:a}},editPost:async(e,t)=>{const n=Ee();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s}),ot("local.post.updated",a);const{posts:o}=a;return{data:ei.post(o.find((t=>t.postId===e))),cachedAt:s}},deletePost:nu,softDeletePost:async e=>{Ee().log("post/softDeletePost",e);const t=await nu(e,!1);return ei.post(t)},hardDeletePost:async e=>{Ee().log("post/hardDeletePost",e);const t=await nu(e,!0);return ei.post(t)},approvePost:async e=>{const t=Ee();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ot("post.approved",n),"community"===n.posts[0].targetType&&ot("community.updated",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:ei.post(r.posts.find((t=>t.postId===e))),cachedAt:a}},declinePost:async e=>{const t=Ee();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ot("community.updated",n),ot("post.declined",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:ei.post(n.posts.find((t=>t.postId===e))),cachedAt:a}},flagPost:async(t,n)=>{const r=Ee();r.log("post/flagPost",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,s);return r.cache&&Gt(en(o,"communityUsers")),ot("post.flagged",o),!!o},unflagPost:async e=>{const t=Ee();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Gt(en(n,"communityUsers")),ot("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ee();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Ee();t.log("post/createPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ot("post.created",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:ei.post(s[0]),cachedAt:a}},onPostCreated:Qi,onPostUpdated:zi,onPostDeleted:Vi,onPostApproved:Hi,onPostDeclined:Ji,onPostFlagged:Wi,onPostUnflagged:Gi,onPostReactionAdded:Yi,onPostReactionRemoved:Zi,getPost:(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ei.post(e.data):n}))}),"postId",Ri,[Hi,Ji,Kd,$d,t=>Vi((n=>{var r;let a=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Pe(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Me(["post","get",e.postId],e),a=e)}t(a)})),Wi,e=>Yi((t=>{e(t)})),e=>Zi((t=>{e(t)})),Gi,zi,Qd,Fd,mi((t=>tc((async n=>{n.referenceId===e&&(await Ri(e),t(n))}))),"referenceId","post"),mi((t=>rc((async n=>{n.referenceId===e&&(await Ri(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const o=new ou(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getPinnedPosts(tmpid: ${s}) > listen`);const o=new lu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getGlobalPinnedPosts(tmpid: ${s}) > listen`);const o=new hu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`semanticSearchPosts(tmpid: ${s}) > listen`);const o=new yu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`searchPostsByHashtag(tmpid: ${s}) > listen`);const o=new wu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`searchPostsByHashtag(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Iu=async e=>{const t=Ee();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}};Iu.locally=e=>{const t=Ee();if(t.log("stream/getStream",e),!t.cache)return;const n=Pe(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Su=e=>{const t=Ee();return st(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Gt(t),e(t.videoStreamings[0])}))},_u=e=>{const t=Ee();return st(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Gt(t),e(t.videoStreamings[0])}))},ku=e=>{const t=Ee();return st(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Gt(t),e(t.videoStreamings[0])}))},Ou=e=>{const t=Ee();return st(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Gt(t),e(t.videoStreamings[0])}))},Tu=e=>{const t=Ee();return st(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Gt(t),e(t.videoStreamings[0])}))},Eu=(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ei.stream(e.data):n}))}),"streamId",Iu,[ku,Su,_u,Ou,Tu,Dc]);Eu.locally=e=>{const t=Ee();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Pe(["stream","get",e]);return n?{data:ei.stream(n.data),cachedAt:n.cachedAt}:void 0};const Au=async e=>{const t=Ee();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:a}=n,s=Zt(n,["page","limit"]),o=r?{token:r}:a?{limit:a}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Gt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Ru=Object.freeze({__proto__:null,createStream:async e=>{const t=Ee();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:ei.stream(a[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Ee();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{videoStreamings:s}=r;return{data:ei.stream(s.find((t=>t.streamId===e))),cachedAt:a}},deleteStream:async e=>{const t=Ee();t.log("stream/deleteStream",e);const n=await Iu(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Ue(["stream","get",e],s),a},disposeStream:async e=>{const t=Ee();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&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Ee();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{videoStreamings:s}=r;return{data:ei.stream(s.find((t=>t.streamId===e))),cachedAt:a}},onStreamStarted:Su,onStreamStopped:_u,onStreamRecorded:ku,onStreamFlagged:Ou,onStreamTerminated:Tu,onStreamViewerBanned:Dc,onStreamViewerUnbanned:e=>{const t=Ee();return st(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>Iu(e))));const a=null===(n=Pe(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))},getStreamById:Eu,getStreams:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getStreams(tmpid: ${s}) > listen`);const{limit:o}=e,i=Zt(e,["limit"]),c=null!=o?o:Q,{policy:l=z}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=De(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Je:Ve),n},p=(e,n=!1)=>{var r,a;const s=null!==(r=e.data.map((e=>Pe(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(s):s,hasNextPage:!!(null===(a=e.params)||void 0===a?void 0:a.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Pe(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Me(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=Pe(u))||void 0===t?void 0:t.data,a=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null==r?void 0:r.params.page))return;const s=fe(Au,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ge(s,(({data:e,error:t,loading:n,paging:r})=>{const s={loading:n,error:t,params:{page:null==r?void 0:r.next},data:a};e&&(s.data=[...new Set([...a,...e.map(be("stream"))])]),Me(u,s),p(s)}),me(l))};return d.push(ku(f()),Su(f()),_u(f())),m(!0),()=>{r(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Pu=async e=>{const t=Ee();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}};Pu.locally=e=>{const t=Ee();if(t.log("poll/getPoll",e),!t.cache)return;const n=Pe(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Mu=e=>{const t=Ee();return st(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Gt(n),e(n.polls[0])}))},ju=e=>{const t=Ee();return st(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Gt(n),e(n.polls[0])}))};var Uu=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ee();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{polls:a}=n;return{data:a[0],cachedAt:r}},closePoll:async e=>{const t=Ee();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&&Gt(n,{cachedAt:r}),ot("poll.updated",n);const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=Ee();t.log("poll/deletePoll",e);const n=await Pu(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Ue(["poll","get",e],s),ot("poll.deleted",{polls:[s],users:[]}),a},votePoll:async(e,t)=>{const n=Ee();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{polls:s}=r;return ot("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:a}},unvotePoll:async e=>{const t=Ee();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r}),ot("poll.updated",n)},onPollUpdated:Mu,onPollDeleted:ju,getPoll:(e,t)=>lo(e,t,"pollId",Pu,[Mu,ju])});const xu={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function Du(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function qu(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,xu,!1,["sign"])}async function Nu({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const a=e();if(a.length)try{const n=(new Date).toISOString(),s=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(),a=`nonceStr=${r}&timestamp=${e}&data=${n}==`,s=(new TextEncoder).encode(a),o=await qu("-----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:Du(await crypto.subtle.sign(xu,o,s)),nonceStr:r}}({timestamp:n,streams:a});if(!s||!s.signature)throw new Error("Signature is undefined");const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:a},i=Ee();return await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||r(),!0}catch(e){return a.forEach((e=>n(e))),!1}}class Bu{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((()=>{Nu({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Lu=null;class Fu{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Lu||(Lu=new Bu,Lu),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(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(Dc((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var Ku=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(!I.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Iu(t),{watcherUrl:r,status:a,recordings:s=[],resolution:o}=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 I.default;if(c.attachMedia(i),"recorded"!==a){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new Fu(i,o,t).registerEvents(),i}});const $u=e=>{const t=(e=>{var t;const n=Ee(),r=new Date,a=r.getTime()+31536e6,s=new Date(a).toISOString();let o=null===(t=Pe(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Gt({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(a).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Gt(t),t},Qu=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const a=t.getAll("files")[0]||void 0;if(!a)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:a.uri})});return n&&(s.data.videoFileId={original:void 0}),r($u(s))}return r($u(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},zu=async e=>{const t=Ee();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Td(n.data);t.cache&&Gt(r),Me(["story-sync-state",e.targetId],"synced"),ot("local.story.created",r);const a=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:a}},Vu=async({targetId:e,targetType:t})=>{var n,r;if(!Pe(["storyTarget","get",e])){let a={targetId:e,targetType:t};if("community"===t){const t=await hl(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await ii(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Me(["storyTarget","get",e],a)}},Hu=e=>e?Pe(["story","get",e]):{data:void 0,cachedAt:void 0},Ju=async(e,t=!1)=>{var n,r,a;const s=Ee();let o;if(s.log("story/deleteStory",e),s.cache&&(o=Hu(e),null==o?void 0:o.data)){const{data:s}=o;if(ot("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},s),{isDeleted:!0})]}),"synced"!==s.syncState){t?xe(["story","get",e]):Me(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const r=null===(n=Re(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Me(["story-expire",o.data.targetId],e.toISOString())}else xe(["story-expire",o.data.targetId]);return!0}const i=null===(r=Pe(["storyTarget","get",s.targetId]))||void 0===r?void 0:r.data,c=null===(a=Re(["story","get"]))||void 0===a?void 0:a.filter((e=>"synced"===e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Me(["storyTarget","get",s.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await s.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Wu=e=>{const t=Ee(),n=[st(t,"onStoryUpdated","story.updated",(async t=>{const n=Td(t);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Gu=e=>{const t=Ee(),n=[st(t,"onStoryUpdated","local.story.updated",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Yu=e=>{const t=Ee(),n=[st(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Zt(t,["reactions"]),a=Td(r),s=Di("story.reactionAdded",Object.assign(Object.assign({},a),{reactions:n}));Gt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Zu=e=>{const t=Ee(),n=[st(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Gt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Xu=e=>{const t=Ee(),n=[st(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Zt(t,["reactions"]),a=Td(r),s=Di("story.reactionRemoved",Object.assign(Object.assign({},a),{reactions:n}));Gt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},eh=e=>{const t=Ee(),n=[st(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Gt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},th=e=>{e.forEach((e=>{const t=Pe(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Me(["story-expire",e.targetId],n.toISOString())}))},nh=e=>{e.forEach((e=>{Me(["story-reference",e.storyId],e.referenceId)}))},rh=async({targetType:e,targetId:t,options:n})=>{const r=Ee();r.log("story/getActiveStoriesByTarget");const a=r.cache&&Date.now(),s=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=Td(s.data);return r.cache&&(Gt(o),th(o.stories),nh(o.stories)),{data:o.stories,cachedAt:a,paging:{next:void 0,previous:void 0}}},ah=e=>{const t=Ee(),n=[st(t,"onStoryCreated","story.created",(async t=>{const n=Td(t,!0);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},sh=e=>{const t=Ee(),n=[st(t,"onStoryCreated","local.story.created",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},oh=e=>{const t=Ee(),n=[st(t,"onStoryDeleted","story.deleted",(async t=>{const n=Td(t);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},ih=e=>{const t=Ee(),n=[st(t,"onStoryDeleted","local.story.deleted",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ch=e=>{const t=Ee();return st(t,"onStoryError","local.story.error",(async t=>{Gt(t),e(t.stories)}))},lh=e=>t=>e((e=>t(e[0]))),dh=async e=>{const t=Ee();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Gt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class uh extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now(),r=Td(e);t.cache&&(Gt(r,{cachedAt:n}),th(r.stories),nh(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(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=Pe(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])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hh extends eo{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class ph extends to{constructor(e,t){const n=C.default(e),r=["story-target-ids","collection",n],a=new hh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new uh(this.query,this.cacheKey,this.notifyChange.bind(this),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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 a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let s=a.data.map((e=>Pe(["story","get",e]))).filter(Boolean).map((e=>ei.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,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(Ve):r.sort(Je)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ah,action:"onCreate"},{fn:Wu,action:"onUpdate"},{fn:oh,action:"onDelete"},{fn:ch,action:"onError"}])}}const fh=(e,t)=>{var n,r;const a=null===(n=Pe(e))||void 0===n?void 0:n.data,s=null!==(r=null==a?void 0:a.data)&&void 0!==r?r:[];Me(e,Object.assign(Object.assign({},a),{data:[...new Set([...s,...t])]}))};class mh extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=a}saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Gt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Me(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):fh(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&fh(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 gh extends Ws{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:a="unseen"}=e,s=await this.createRequest({seenState:"smart"===a?this.smartFilterState:a,limit:r,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==a)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=o,{categories:(i=s).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 yh extends to{constructor(e,t){const n=C.default(e),r=["story-global-feed","collection",n],a=new gh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new mh(this.query,this.cacheKey,this.notifyChange.bind(this),a,(e=>{const t=Zt(Ao(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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 a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=a.data,o=Re(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{a.data.includes(e[2])||s.push(e[2])})));let i=s.map((e=>Pe(["storyTarget","get",e]))).filter(Boolean).map((e=>ei.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>Zt(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(He);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(He)||[],r=t.unseen.sort(He)||[],a=t.seen.sort(He)||[];return n.concat(r,a)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ah,action:"onCreate"},{fn:Wu,action:"onUpdate"},{fn:oh,action:"onDelete"},{fn:sh,action:"onCreate"},{fn:Gu,action:"onUpdate"},{fn:ih,action:"onDelete"},{fn:ch,action:"onError"}])}}var vh=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},a="fit",s=[])=>{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:a},syncState:"syncing",referenceId:$t(),dataType:"image",items:s,targetType:e,targetId:t,metadata:r};const i=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),Qu({payload:o,formData:n},(e=>{ot("local.story.created",e)}));try{const{data:r}=await ki(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:a}=r[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:a})}),Vu({targetId:t,targetType:e}),Qu({payload:o,formData:n},(e=>{ot("local.story.created",e)}));const s=await zu(o);return s.data?Object.assign(Object.assign({},s),{data:ei.story(s.data)}):s}catch(e){throw Me(["story-sync-state",t],"error"),Qu({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{ot("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},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},syncState:"syncing",referenceId:$t(),dataType:"video",items:a,targetType:e,targetId:t,metadata:r};const o=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),Vu({targetId:t,targetType:e}),Qu({payload:s,formData:n,isVideo:!0},(e=>{ot("local.story.created",e)}));try{const{data:e}=await _i(n,P.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),Qu({payload:s,formData:n,isVideo:!0},(e=>{ot("local.story.created",e)}));const r=await zu(s);return r.data?Object.assign(Object.assign({},r),{data:ei.story(r.data)}):r}catch(e){throw Me(["story-sync-state",t],"error"),Qu({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{ot("local.story.error",e)})),e}},hardDeleteStory:async e=>await Ju(e,!0),softDeleteStory:async e=>await Ju(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Ee(),a=[],s=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),r||console.log(V);const i=t=>{var n,r;const a=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===a?"asc"===s?t.sort(Ve):t.sort(Je):"asc"===s?t.sort(We):t.sort(Ge)},c=e=>{var n;const r=e.data.map((e=>{const t=Hu(e);if(null==t?void 0:t.data)return ei.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),a=[];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")||[]);a.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);a.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);a.push(...t)}}t({onNextPage:()=>!1,data:a||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,a=!1,o=!1)=>{var i;const l=Pe(s),d={loading:a,error:o,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(be("story")):[...new Set([...d.data,...t.map(be("story"))])];const u=null===(i=Re(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>be("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Me(s,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=fe(rh,e);ge(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),a.push(ah(d("onCreate")),Wu(d("onUpdate")),oh(d("onDelete")),Yu(d("onReactionAdded")),Xu(d("onReactionRemoved")),ch(d("onError")),sh(d("onCreate")),Gu(d("onUpdate")),ih(d("onDelete")),Zu(d("onReactionAdded")),eh(d("onReactionRemoved")),(e=>{const t=Ee();return st(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Pe(s);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)})),(()=>xe(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>lo(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:ei.story(e.data)})):t(e)}),"storyId",Ed,[lh(Wu),lh(oh),lh(Yu),lh(Xu),lh(ch),lh(Gu),lh(ih),lh(Zu),lh(eh)]),getTargetById:(e,t)=>lo(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:ei.storyTarget(e.data[0])})):t(e)}),"query",(e=>dh([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Ee(),a=[],s=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),r||console.log(V);const i=(e,n=!1,r=!1,a=!1)=>{const o=Pe(s),i={loading:r,error:a,params:{page:void 0},data:[]};e&&(i.data=n?e.map(be("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(be("storyTarget"))])]),Me(s,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Pe(["storyTarget","get",e]);if(null==t?void 0:t.data)return ei.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=fe(dh,e);ge(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),a.push((()=>xe(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new ph(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new yh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const bh=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),wh=e=>Object.assign({},e);var Ch=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(bh),r=t.advertisers.map(wh);return Gt({ads:n,advertisers:r,files:t.files}),Me(["ad","setting"],t.settings),{ads:n.map(ei.ad),settings:t.settings}}});const Ih=async()=>{const e=Ee();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Me(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};Ih.locally=()=>{var e;const t=Ee();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=Pe(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const Sh=e=>{const t=Ee(),n=[st(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class _h extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class kh extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.notificationTrayItems.map(be("notificationTrayItem"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(be("notificationTrayItem"))])]}))}}}const Oh=e=>{const t=e.users.map(Tn);return Object.assign(Object.assign({},e),{users:t})};class Th extends to{constructor(e,t){const n=C.default(e),r=["notificationTrayItem","collection",n];super(new _h(e),n,r,t),this.query=e,this.queryStreamController=new kh(this.query,this.cacheKey,this.notifyChange.bind(this),Oh),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["notificationTrayItem","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ei.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Eh=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Xe();return lo(t,e,"userId",Ih,[Sh],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Mn(e.lastTraySeenAt)>Mn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getNotificationTrayItems(tmpid: ${s}) > listen`);const o=new Th(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getNotificationTrayItems(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ee();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=Pe(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const a=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Me(["notificationTrayItem","get"],a,{cachedAt:e})}return a})).filter(Boolean);ot("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Ee();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),a=null===(t=Pe(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,s={userId:n.userId,lastTraySeenAt:r.lastSeenAt},o=Object.assign(Object.assign({},a),s),i=n.cache&&Date.now();return n.cache&&Me(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),ot("local.notificationTraySeen.updated",s),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:Sh});class Ah extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:a})});return await ul(s.invitations.map((e=>e.communityId))),s}}class Rh extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(be("invitation"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(be("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Vo.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===Vo.OnLocalInvitationCreated){const e=Ee(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===Vo.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ph extends to{constructor(e,t){const n=C.default(e),r=["invitation","collection",n];super(new Ah(e),n,r,t),this.query=e,this.queryStreamController=new Rh(this.query,this.cacheKey,this.notifyChange.bind(this),Qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wo,action:Vo.OnLocalInvitationCreated},{fn:Go,action:Vo.OnLocalInvitationUpdated},{fn:Yo,action:Vo.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["invitation","get",e]))).filter(no).map((({data:e})=>zo(e))))&&void 0!==a?a:[]);(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;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}var Mh=Object.freeze({__proto__:null,onLocalInvitationCreated:Wo,onLocalInvitationUpdated:Go,onLocalInvitationDeleted:Yo,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMyCommunityInvitations: (tmpid: ${s}) > listen`);const o=new Ph(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const jh=e=>{const t=Ee();return st(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var Uh=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r})=>{const a=Ee();a.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n});const s=La(),o={reactionName:n,referencePublicId:e,referenceType:t,streamId:r,occurredAt:(new Date).toISOString()};return s.createLiveReaction(o),ot("local.liveReaction.created",[Object.assign(Object.assign({},o),{userId:a.userId,referenceId:e})]),!0},onLiveReactionCreated:jh,getReactions:(e,t)=>{const{_id:n}=Xe();if(!n)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ee();r(`getReactions(tmpid: ${Date.now()}) > listen`);const a=[],s=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return a.push(jh(s)),a.push((e=>{const t=Ee();return st(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(s)),()=>{a.forEach((e=>e()))}}});return e.API_REGIONS=Ot,e.AdRepository=Ch,e.CategoryRepository=Cd,e.ChannelRepository=ll,e.Client=As,e.CommentRepository=Bd,e.CommunityPostSettingMaps=A,e.CommunityPostSettings=E,e.CommunityRepository=vd,e.ContentFeedType=P,e.DefaultCommunityPostSetting=R,e.FeedRepository=eu,e.FileRepository=Oi,e.FileType=S,e.InvitationRepository=Mh,e.LiveReactionRepository=Uh,e.LiveStreamPlayer=Ku,e.MessageContentType=j,e.MessageRepository=Lc,e.PollRepository=Uu,e.PostContentType=U,e.PostRepository=Cu,e.ReactionRepository=pc,e.StoryRepository=vh,e.StreamRepository=Ru,e.SubChannelRepository=Hc,e.UserRepository=Ii,e.VERSION=$,e.VideoResolution=_,e.VideoSize=O,e.VideoTranscodingStatus=k,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:a}=Ee();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${a}`,JSON.stringify(s)),!0)},e.createQuery=fe,e.createReport=async(e,t)=>{const n=Ee();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await ua(n);Gt(e)}return ot("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await _n(n);Gt(e)}return ot("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Bi(n);Gt(e)}return ot("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await fc(n);Gt(e)}return ot("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await zt(),a=Vt(),s=xt(Et("http",t)),{data:o}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},a),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=Ee();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await ua(n);Gt(e)}return ot("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await _n(n);Gt(e)}return ot("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Bi(n);Gt(e)}return ot("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await fc(n);Gt(e)}return ot("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ee();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=xe,e.enableCache=(e={},t)=>{const n=Ee();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Be,e.filterByCommunityMembership=Fe,e.filterByFeedType=Le,e.filterByPostDataTypes=Ke,e.filterByPropEquality=De,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Ne,e.filterBySearchTerm=$e,e.filterByStringComparePartially=qe,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Xe();return`${ht(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>ut(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=wt,e.getMarkedMessageTopic=ft,e.getMarkerUserFeedTopic=mt,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Xe();return`${ht(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Xe();return`${ht(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=gt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Ei,e.getSmartFeedChannelTopic=yt,e.getSmartFeedMessageTopic=bt,e.getSmartFeedSubChannelTopic=vt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Xe();return`${ht(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=pt,e.isAfterBefore=ae,e.isAfterBeforeRaw=se,e.isCachable=he,e.isFetcher=le,e.isFresh=pe,e.isLocal=e=>he(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=de,e.isOffline=ue,e.isPaged=oe,e.isReportedByMe=async(e,t)=>{const n=Ee();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=re,e.mergeInCache=je,e.notificationTray=Eh,e.onChannelMarkerFetched=ws,e.onFeedMarkerFetched=e=>{const t=Ee();return st(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ee();return st(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Gt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=ks,e.onMessageMarkerFetched=_s,e.onSubChannelMarkerFetched=Cs,e.onSubChannelMarkerUpdated=Is,e.onUserMarkerFetched=Ss,e.onUserMarkerFetchedLegacy=e=>{const t=Ee();return st(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Pe,e.pushToCache=Me,e.queryCache=Re,e.queryOptions=me,e.queryRoles=Ti,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ee();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 a={};try{a=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},a),n.cache.data),!0},e.runQuery=ge,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Qe,e.sortByFirstCreated=Ve,e.sortByFirstUpdated=We,e.sortByLastActivity=Ye,e.sortByLastCreated=Je,e.sortByLastUpdated=Ge,e.sortByLocalSortingDate=He,e.sortByName=ze,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Ct,e.toPage=ce,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return se(n)?n:void 0},e.toToken=ie,e.upsertInCache=Ue,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Ee();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,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
5
+ var r=e("buffer"),a=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return a(e,t,n)}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=o),o.prototype=Object.create(a.prototype),s(a,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return a(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=a(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 a(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(a(t)):null}function a(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,a=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 s(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=s(e);if("string"!=typeof t&&(r.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,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 a=c(t[r]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(e.lastNeed=a-2),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(2===a?a=0:e.lastNeed=a-3),a):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 m(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 g(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"),a=e("./util");function s(){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=S,n.format=C,n.Url=s;var o=/^([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}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={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&&a.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return a.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!a.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<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=o.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var O,T,E=-1,A=0;A<h.length;A++)-1!==(R=C.indexOf(h[A]))&&(-1===E||R<E)&&(E=R);for(-1!==(T=-1===E?C.lastIndexOf("@"):C.lastIndexOf("@",E))&&(O=C.slice(0,T),C=C.slice(T+1),this.auth=decodeURIComponent(O)),E=-1,A=0;A<u.length;A++){var R;-1!==(R=C.indexOf(u[A]))&&(-1===E||R<E)&&(E=R)}-1===E&&(E=C.length),this.host=C.slice(0,E),C=C.slice(E),this.parseHost(),this.hostname=this.hostname||"";var P="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!P)for(var M=this.hostname.split(/\./),j=(A=0,M.length);A<j;A++){var U=M[A];if(U&&!U.match(f)){for(var x="",D=0,q=U.length;D<q;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var N=M.slice(0,A),B=M.slice(A+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(C="/"+B.join(".")+C),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+F,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(A=0,j=d.length;A<j;A++){var $=d[A];if(-1!==C.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),C=C.split($).join(Q)}}var z=C.indexOf("#");-1!==z&&(this.hash=C.substr(z),C=C.slice(0,z));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){F=this.pathname||"";var H=this.search||"";this.path=F+H}return this.href=this.format(),this},s.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||"",s=!1,o="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&a.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(a.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),o=0;o<r.length;o++){var i=r[o];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 m=n.pathname||"",g=n.search||"";n.path=m+g}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,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.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]||""===S[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,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!a.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),n.search=e.search,n.query=e.query,a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],O=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,T=0,E=S.length;E>=0;E--)"."===(k=S[E])?S.splice(E,1):".."===k?(S.splice(E,1),T++):T&&(S.splice(E,1),T--);if(!C&&!I)for(;T--;T)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),O&&"/"!==S.join("/").substr(-1)&&S.push("");var A,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=R?"":S.length?S.shift():"",(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),(C=C||n.host&&S.length)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.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},s.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 a(){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 a}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!==Dt?Dt:"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),a=t[t.length-1];return"function"==typeof r&&r!==a&&Object.keys(a).forEach((function(e){r[e]=a[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=a;var r=Object.prototype.hasOwnProperty;function a(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var a in n)r.call(n,a)&&(e[a]=n[a])}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,a=arguments.length;n<a;n++)t.push(arguments[n]);return t}function a(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 s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(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++)s(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,a=this.head;null!==a;)n.push(e.call(t,a.value,this)),a=a.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,a=this.tail;null!==a;)n.push(e.call(t,a.value,this)),a=a.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 a=0;null!==r;a++)n=e(n,r.value,a),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 a=this.length-1;null!==r;a--)n=e(n,r.value,a),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 a=0,s=this.head;null!==s&&a<e;a++)s=s.next;for(;null!==s&&a<t;a++,s=s.next)n.push(s.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 a=this.length,s=this.tail;null!==s&&a>t;a--)s=s.prev;for(;null!==s&&a>e;a--,s=s.prev)n.push(s.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,s=this.head;null!==s&&r<e;r++)s=s.next;var o=[];for(r=0;s&&r<t;r++)o.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=a(this,s,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);var Lt=qt(Bt.exports);class Ft{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 Kt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ft},$t=()=>b.default.v4().toString();let Qt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=$t(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:a})=>{a.tabId!==e&&("startup"===a.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Qt}),"identify"===a.type&&void 0!==a.tabIndex&&a.tabId&&(t[a.tabId]=a.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Qt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const zt=async()=>{var e;const t=`${null!==(e=Ee().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(Kt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${$t()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{Kt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Vt=()=>{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:$}},Ht=1e3;var Jt;!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"}(Jt||(Jt={}));const Wt=e=>{let t,n="disconnected";const r=new Set,a=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await zt()}_${e}_${Qt}`)(n.userId);return a("connecting"),t&&(a("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Lt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Ht,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=Ht,a("connected"),(()=>{const e=[Ct(gt()),Ct(yt()),Ct(vt()),Ct(bt()),Ct(pt(Xe())),Ct(mt()),Ct(wt())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),a("disconnected")}})),t.on("reconnect",(()=>{a("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Ht),8e3)})),t.on("close",(()=>{a("disconnected")})),t.on("disconnect",(()=>{a("disconnected")})),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()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(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 a;if(t||128===(null===(a=r[0])||void 0===a?void 0:a.qos)){const r=t?new Ie(t.message,8e5,"error"):new _e(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)}}},Gt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const a=we[e];if(!a)return;const s=be(a);s&&r.forEach((e=>{(n?Me:Ue)([a,"get",s(e)],e,t)}))}))},Yt=(e,t)=>{const{log:n,cache:r}=Ee(),a=[e,Y,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:a,data:s}),xe([e,"get",t],!0),Me(a,s))};function Zt(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 a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}const Xt=(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(!Ee().cache)return;return(null===(n=Pe(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},en=(e,t,n="userId",r="user")=>{const a=e,s=t,o=a[s],i=Zt(a,["symbol"==typeof s?s:s+""]),c=Xt(o,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function tn(e){return e.map((e=>{var{isMentioned:t}=e,n=Zt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function nn(e){return tn(e)}function rn(e){return tn(e)}const an=e=>{var t,n;return null!==(n=null===(t=Pe(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},sn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Pe(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),on=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:a,messageFeedId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:a,subChannelId:s,data:o,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:[]};Gt(r)},cn=e=>{var t,n;return null!==(n=null===(t=Pe(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},ln=e=>{var t;const n=e.messagePreviewId?cn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Pe(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},dn=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:a,messageFeedId:s,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:a,subChannelId:s,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:[]};Gt(r)};function un(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function hn(e,t,n){Me(["subChannel","get",e],un(t,n))}const pn=(e,t)=>{const{log:n,cache:r}=Ee(),a=[e,Y,t];if(!r)return;n("cache/api/isInTombstone",a);const s=Pe(a),{lifeSpan:o}=me("cache_then_server",18e4);if(s&&pe(s.data,o))throw new Se("Item not found!",400400,"error")},fn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Pe(n))||void 0===t?void 0:t.data,a=Re(["subChannelUnreadInfo","get"]);let s=0,o=!1;if(a&&(null==a?void 0:a.length)>0){const t=null==a?void 0:a.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=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:s,isMentioned:o});return Me(n,i),i},mn=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,a={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};Gt({subChannelUnreadInfo:[a]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{fn(e)}))}},gn=async()=>{const e=Ee();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&&Gt({userMarkers:n},{cachedAt:r}),ot("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}},yn=e=>!0===e&&void 0;function vn(e,t,n){var r,a;if(n)return n.hasMentioned;const s=Ee();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Pe(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:Xe()._id},i=null===(a=Pe(["subChannelMarker","get",be("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return!!i&&i.hasMentioned}const bn=["broadcast","conversation","community"],wn=({channelType:e})=>bn.includes(e);function Cn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:a,creatorId:s,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=Zt(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,a;if(n)return n.unreadCount;const s=Ee();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Pe(["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:Xe()._id},i=null===(a=Pe(["subChannelMarker","get",be("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return vn(t,l)},get isMentioned(){return vn(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:a,subChannelId:l,isUnreadCountSupport:wn({channelType:r})})}function In(e,t,n){var r;const a=(e=>{var t,n,r;const a=null===(n=null===(t=Re(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign(Object.assign({},a),e),{referenceId:null!==(r=a.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:s,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=a,y=Zt(a,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Pe(["message","get",p])),v||(v=Pe(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:s,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:m,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=Ee(),a=Pe(["message","get",e.messageId]),s=(null==a?void 0:a.data.myReactions)||[];Object.assign(e,{myReactions:s});const o=t[0];o&&o.userId===r.userId&&("message.reactionAdded"!==n||s.includes(o.reactionName)||Object.assign(e,{myReactions:[...s,o.reactionName]}),"message.reactionRemoved"===n&&s.includes(o.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const Sn={},_n=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Gt({messages:(r=e).messages.map((e=>In(e,r.reactions)))});const t=n.join("");Sn[t]&&clearTimeout(Sn[t]),Sn[t]=setTimeout((()=>{try{(async e=>{const t=Ee();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:a,userMarkers:s}=n,o=t.cache&&Date.now();t.cache&&Gt({contentMarkers:r,feedMarkers:a,userMarkers:s},{cachedAt:o}),ot("local.feedMarker.fetched",{feedMarkers:a}),ot("local.messageMarker.fetched",{contentMarkers:r}),ot("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:a}=e,s=Zt(e,["messageFeeds"]);return a&&a.length>0&&(null==a||a.forEach((e=>{var t,n;const r=null!==(n=null===(t=Pe(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},a=Zt(Cn(e),["unreadCount","isMentioned"]);hn(e.messageFeedId,r,a)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>In(n,e.reactions,t)))})};function kn(e){var{subChannelId:t,mentionees:n,dataType:r,data:a}=e,s=Zt(e,["subChannelId","mentionees","dataType","data"]);return r===j.IMAGE||r===j.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},a)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:a},s)}function On(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:a,includeDeleted:s,aroundMessageId:o,limit:i,type:c}=e,l=Zt(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:yn(s),options:{sortBy:t,limit:i||Q,around:o}});return r&&(d.includeTags=r),c&&(d.dataType=c),a&&(d.excludeTags=a),d}function Tn(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const En=["broadcast","conversation","community"],An=({channelType:e})=>En.includes(e),Rn=async e=>{const t=e.messageFeeds.filter(An).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Gt({messageFeeds:e.messageFeeds.map((e=>Cn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ee();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:ie(t,"skiplimit")}}}),{paging:a}=r,s=Zt(r,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&mn({feedMarkers:l,userFeedMarkers:i});const d=nn(o),u=rn(i),h=n.cache&&Date.now();n.cache&&Gt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),ot("local.channelMarker.fetched",{userEntityMarkers:d}),ot("local.subChannelMarker.fetched",{userFeedMarkers:u}),ot("local.userMarker.fetched",{userMarkers:c});const p=ce(a.next);return{data:u,cachedAt:h,prevPage:ce(a.previous),nextPage:p}})(t)}catch(e){}}dn(e);const n=e.messageFeeds.map(Cn),r=e.messages.map((e=>In(e))),a=e.users.map(Tn);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:a})};const Pn=async e=>{const t=Ee();t.log("channel/getSubChannel",e),pn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:a}}catch(t){throw ne(null==t?void 0:t.code)&&Yt("subChannel",e),t}};Pn.locally=e=>{const t=Ee();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Pe(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Mn=e=>new Date(e).getTime(),jn=async e=>{var t;let n=null===(t=Pe(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await Pn(e)).data),n},Un=async e=>{const t=await(async()=>Ee().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await jn(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Pe(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Mn(n.createdAt)<=Mn(e.createdAt)})(e)&&(Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),hn(e.subChannelId,h,{lastActivity:s,messagePreviewId:r})):Mn(h.lastActivity)<Mn(s)&&hn(e.subChannelId,h,{lastActivity:s})},xn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Pe(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await jn(l);Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Dn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:a,updatedAt:s,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Mn(n.createdAt)<=Mn(e.createdAt)})(e)){const u=await jn(c);Me(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:a,updatedAt:s,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},qn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await jn(l);Me(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Nn=async e=>{var t,n,r,a;const{channelId:s,subChannelId:o}=e,i=null===(t=Pe(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Pe(["subChannel","get",o]))||void 0===n?void 0:n.data;Me(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Pe(["messagePreviewSubChannel","get",o]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(a=Pe(["subChannel","get",o]))||void 0===a?void 0:a.data;Me(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Bn=["broadcast","conversation","community"],Ln=({type:e})=>Bn.includes(e);function Fn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const a=null===(n=Pe(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==a?void 0:a.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=a.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ln(e),messagePreviewId:r})}const Kn=(e,t={isMessagePreviewUpdated:!0})=>{Gt({channels:e.channels.map((e=>Fn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},$n=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ee(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&on(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let a=0;a<t.length;a+=1){const s=["channelUnread","get",t[a].channelId],o=n.find((n=>n.channelId===t[a].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;o&&(c=o.readToSegment,l=o.lastMentionedSegment,i=Math.max(t[a].messageCount-c,0),d=l>c);const u={channelId:t[a].channelId,lastSegment:t[a].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[a].isDeleted||!1};Me(s,u),r.push(u)}ot("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ln).map((({channelInternalId:e})=>e));if(n.length>0){Kn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ee();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:a}=n,s=nn(r),o=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:s,userMarkers:a},{cachedAt:o}),ot("local.channelMarker.fetched",{userEntityMarkers:s}),ot("local.userMarker.fetched",{userMarkers:a}),{data:s,cachedAt:o}})(n)}catch(e){}}}const a=e.channels.map((e=>Fn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ee().cache)return(null===(e=Pe(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(Tn),i=Zt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:a,channelUsers:s})},Qn=async e=>{const t=Ee();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return ot("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},zn=async e=>{const t=Ee(),n=await Qn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:a}=n;mn({feedMarkers:r,userFeedMarkers:a}),t.log("channel/prepareUnreadCountInfo",e.channels)},Vn=(e,t)=>{var n,r,a,s;const o=Ee();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Pe(["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!==(s=null===(a=(e=>{var t;const n={entityId:e,userId:Xe()._id};return null===(t=Pe(["channelMarker","get",be("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===a?void 0:a.hasMentioned)&&void 0!==s&&s},Hn=(e,t)=>{var n,r,a,s,o;const i=Ee();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Pe(["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!==(a=null==t?void 0:t.unreadCount)&&void 0!==a?a:null===(s=(e=>{var t;const n={entityId:e,userId:Xe()._id};return null===(t=Pe(["channelMarker","get",be("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==o?o:0},Jn=e=>{var t;return null===(t=Pe(["channelUnread","get",e]))||void 0===t?void 0:t.data},Wn=e=>{const t=Ee(),n=Zt(e,["messageCount"]);return un(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Jn(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Hn(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Jn(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Vn(n)}})},Gn=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=Pe(n))||void 0===t?void 0:t.data;return r?sn(r):void 0})()}}),Yn=e=>{const t=Ee();t.log("channel/getMyMembership.locally");const n=Pe(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Se("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Zn(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(!Zn(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=>Zn(e[n],t[n])))}const Xn=[];let er=null;const tr=e=>{if(0===Xn.length){const e=Ee();er=st(e,"onChannelCreated","channel.created",(async e=>{const t=await $n(e);Gt(t),Xn.forEach((e=>e(t.channels[0])))}))}return Xn.push(e),()=>(e=>{const t=Xn.indexOf(e);t>-1&&Xn.splice(t,1),0===Xn.length&&(null==er||er())})(e)},nr=[],rr=[],ar=e=>{const t=Ee();if(0===nr.length){const e=async e=>{const t=await $n(e);Gt(t),nr.forEach((e=>e(t.channels[0])))};rr.push(st(t,"onChannelUpdated","channel.updated",e)),rr.push(st(t,"onChannelUpdated","local.channel.updated",(e=>nr.forEach((t=>t(e.channels[0]))))))}return nr.push(e),()=>(e=>{const t=nr.indexOf(e);t>-1&&nr.splice(t,1),0===nr.length&&rr.forEach((e=>e()))})(e)},sr=e=>{const t=Re(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Me(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},or=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Pe(n))||void 0===t?void 0:t.data)&&xe(n)},ir=[];let cr=null;const lr=e=>{if(0===ir.length){const e=Ee(),t=async t=>{const n=await $n(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,a=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)sr(e.channelId),or(e.channelId);else if(a){const t=["channelUnread","get",e.channelId],n=Pe(t);n&&Me(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Gt(n),ir.forEach((e=>e(n.channels[0])))};cr=st(e,"onChannelDeleted","channel.deleted",t)}return ir.push(e),()=>(e=>{const t=ir.indexOf(e);t>-1&&ir.splice(t,1),0===ir.length&&(null==cr||cr())})(e)},dr=[];let ur=null;const hr=e=>{if(0===dr.length){const e=Ee();ur=st(e,"onChannelJoined","channel.joined",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),dr.forEach((e=>e(n[0],r[0])))}))}return dr.push(e),()=>(e=>{const t=dr.indexOf(e);t>-1&&dr.splice(t,1),0===dr.length&&(null==ur||ur())})(e)},pr=[];let fr=null;const mr=e=>{if(0===pr.length){const e=Ee(),t=async t=>{const{userId:n}=Ee(),{channelUsers:r}=t,a=r.some((e=>e.userId===n)),s=await $n(t,{isMessagePreviewUpdated:a}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;a&&s.channels.forEach((e=>{o?(sr(e.channelId),or(e.channelId)):i&&xe(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=s;Gt(s),pr.forEach((e=>e(c[0],l[0])))};fr=st(e,"onChannelLeft","channel.left",t)}return pr.push(e),()=>(e=>{const t=pr.indexOf(e);t>-1&&pr.splice(t,1),0===pr.length&&(null==fr||fr())})(e)},gr=[];let yr=null;const vr=e=>{if(0===gr.length){const e=Ee(),t=async e=>{var t;Ue(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&gr.forEach((e=>e(n)))};yr=st(e,"onChannelMute","channel.setMuted",t)}return gr.push(e),()=>(e=>{const t=gr.indexOf(e);t>-1&&gr.splice(t,1),0===gr.length&&(null==yr||yr())})(e)},br=[];let wr=null;const Cr=e=>{if(0===br.length){const e=Ee();wr=st(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),br.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return br.push(e),()=>(e=>{const t=br.indexOf(e);t>-1&&br.splice(t,1),0===br.length&&(null==wr||wr())})(e)},Ir=[];let Sr=null;const _r=e=>{if(0===Ir.length){const e=Ee();Sr=st(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),Ir.forEach((e=>e(n[0],r[0])))}))}return Ir.push(e),()=>(e=>{const t=Ir.indexOf(e);t>-1&&Ir.splice(t,1),0===Ir.length&&(null==Sr||Sr())})(e)},kr=[];let Or=null;const Tr=e=>{const t=Ee();return Or=st(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await $n(e),{channels:r,channelUsers:a}=n,s=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{sr(e.channelId),or(e.channelId)})),Gt(n),kr.forEach((e=>e(r[0],a.find((e=>"banned"===e.membership)))))})),kr.push(e),()=>(e=>{const t=kr.indexOf(e);t>-1&&kr.splice(t,1),0===kr.length&&(null==Or||Or())})(e)},Er=[];let Ar=null;const Rr=e=>{if(0===Er.length){const e=Ee();Ar=st(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await $n(e),{channels:n,channelUsers:r}=t;Gt(t),Er.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return Er.push(e),()=>(e=>{const t=Er.indexOf(e);t>-1&&Er.splice(t,1),0===Er.length&&(null==Ar||Ar())})(e)},Pr=[];let Mr=null;const jr=e=>{if(0===Pr.length){const e=Ee();Mr=st(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;Pr.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Pr.push(e),()=>(e=>{const t=Pr.indexOf(e);t>-1&&Pr.splice(t,1),0===Pr.length&&(null==Mr||Mr())})(e)},Ur=[];let xr=null;const Dr=e=>{if(0===Ur.length){const t=Ee();xr=st(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return Ur.push(e),()=>(e=>{const t=Ur.indexOf(e);t>-1&&Ur.splice(t,1),0===Ur.length&&(null==xr||xr())})(e)},qr=[];let Nr=null;const Br=e=>{if(0===qr.length){const e=Ee(),t=async e=>{var t,n;e.userIds.forEach((t=>Ue(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data,a=null===(n=Pe(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===n?void 0:n.data;r&&a&&qr.forEach((e=>e(r,a)))};Nr=st(e,"onChannelUserMute","channel.setMutedUsers",t)}return qr.push(e),()=>(e=>{const t=qr.indexOf(e);t>-1&&qr.splice(t,1),0===qr.length&&(null==Nr||Nr())})(e)},Lr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=Re(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Gn(e))))}return un(e,{markAsRead:()=>(async e=>{const t=Ee();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:a,userFeedMarkers:s}=n,o=Zt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=nn(a),l=rn(s);return t.cache&&Gt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),ot("local.channelMarker.updated",{userEntityMarkers:c}),ot("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Xe();if(!n)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:a}=Ee();a||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const s=[];let o=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Gn(e.data):e.data}))},c=(t,n)=>{const{data:r}=Yn(e);Zn(void 0,r)||i({loading:!1,data:r})};return s.push(Tr(c)),s.push(Rr(c)),s.push(Br(c)),(()=>{const t=fe((async()=>Yn(e)));ge(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}})(e.channelId,t)})},Fr=e=>Lr(Wn((e=>{var t;const n=e.messagePreviewId?an(e.channelId):null,r=null===(t=Pe(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,a=n?Object.assign(Object.assign({},n),{user:r?sn(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:a})})(e))),Kr=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("channel",e)})),t}const a=await $n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(r);const s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("local.channel.fetched",a.channels),{data:a.channels.map((e=>Fr(e))),cachedAt:s}};Kr.locally=e=>{var t,n;const r=Ee();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;const s=a.map((({data:e})=>e)),o=null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>Fr(e))),cachedAt:o.cachedAt}};class $r{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 Qr;var zr=()=>(Qr||(Qr=new $r),Qr);const Vr=e=>zr().onSessionStateChange(e),Hr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Jr=!1;const Wr={},Gr=async()=>{const e=Object.entries(Wr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ee();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=nn(r),c=rn(a),l=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),ot("local.feedMarker.fetched",{feedMarkers:s}),ot("local.channelMarker.fetched",{userEntityMarkers:i}),ot("local.subChannelMarker.fetched",{userFeedMarkers:c}),ot("local.userMarker.fetched",{userMarkers:o}),!0})(e)},Yr=()=>{Jr=!1},Zr=()=>(Jr=!0,Vr((e=>{"notLoggedIn"===e&&Yr()})),()=>{Yr()});Hr((async()=>{Jr&&await Gr()}),3e4);const Xr=async e=>{const t=Ee();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:a}};Xr.locally=e=>{var t;const n=Ee();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Pe(["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 ea=async(e=!0)=>{var t;const n=null===(t=Pe(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var a;return(a=r).messagePreview.enabled?a.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},ta=async()=>{var e;const t=await ea();if(t===(null===(e=Pe(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Me(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Re(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{xe(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=Re(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(xe(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Kr(n),0!==r.length&&await Xr(r)}},na=async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},ra=(e,t)=>{var n;const r=null===(n=Pe(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},aa=e=>{const{userId:t}=Ee();return{currentUser:()=>ra(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Pe(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ra(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Pe(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ra(e,t))})(t,e,n)}},sa=async e=>{const t=Ee();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},oa=async e=>{const t=Ee();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},ia=async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},ca={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},la=e=>{const t=Ee();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>ca[e].includes(t))(n,e))throw new Ie(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,zr().setSessionState(e),!0},da=async e=>{const t=Ee();la("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:s}=await(async({params:e,options:t})=>{const n=Ee();n.log("client/api/getToken",e);const r=Vt(),{data:a}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:a},la("established"),{accessToken:n,users:r}};function ua(e){return{users:e.users.map(Tn),files:e.files}}const ha=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=ua(e);n.cache&&Gt(r),t(r.users[0])}))},pa=e=>ha("user.deleted",e),fa=["analytic","normal-priority"],ma=["analytic","high-priority"],ga=async e=>{const t=Ee(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class ya{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=Pe(fa);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ga(t),xe(fa)}catch(e){this.stop(),xe(fa)}}async syncHighPriorityCapturedEvent(){try{const e=Pe(ma);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ga(t),xe(ma)}catch(e){this.stop(),xe(ma)}}}class va{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,a=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!a)return!0;return!(r.getTime()-a.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:a}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,o={event:[]},i=Pe(fa);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:s.toISOString()};a&&(c.metadata=a),o.event.push(c),Ue(fa,o),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const a={event:[]},s=Pe(ma);if((null==s?void 0:s.data)&&(a.event=s.data.event),a.event.length>=this._poolLimit&&a.event.shift(),a.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),Ue(ma,a),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Me(["story-seen","get",e.storyId],(new Date).toISOString());const o=Pe(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Me(["story-last-seen",e.targetId],e.expiresAt):Me(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),ot("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},xe(fa),xe(ma)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class ba{constructor(){this._client=Ee(),this._eventCapturer=new va,this._eventSyncer=new ya}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)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let wa;var Ca=()=>(wa||(wa=new ba),wa),Ia=()=>{const e=Ca();return e.established(),Vr((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Sa{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ee(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Re(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=Pe(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Ee();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],a=null===(t=Pe(r))||void 0===t?void 0:t.data;Me(r,Object.assign(Object.assign({},a),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],a=null===(n=Pe(r))||void 0===n?void 0:n.data;"number"==typeof(null==a?void 0:a.readToSegment)&&a&&t>a.readToSegment&&(a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0),Me(r,a),ot("local.channelUnread.updated",[a])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Pe(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let _a=null;var ka=()=>(_a||(_a=new Sa),_a),Oa=()=>{const e=ka();return e.startSyncReadReceipt(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Ta{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ee(),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=Re(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Pe(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:a}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=Ee();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:a});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Pe(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Me(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:a}))}else s||(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],a=null===(n=Pe(r))||void 0===n?void 0:n.data;if(a&&t>a.readToSegment){a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0);const e=fn(a.channelId);ot("local.channelUnreadInfo.updated",e),Me(r,a),ot("local.subChannelUnread.updated",a)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Pe(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.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 Ea=null;var Aa=()=>(Ea||(Ea=new Ta),Ea),Ra=()=>{const e=Aa();return e.startSyncReadReceipt(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Pa=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")},Ma=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")},ja=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("channel",e)})),t}const a=await $n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(r);const s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("local.channel.fetched",a.channels),{data:a.channels,cachedAt:s}};ja.locally=e=>{var t,n;const r=Ee();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Ua{constructor(){this.TIMER_INTERVAL_MS=W,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(Pa((()=>{this.isConnected=!0}))),this.connectionListener.push(Ma((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await ja(e);const a=null!==(r=null===(n=null===(t=Re(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];ot("local.channel.resolved",a)})(e),t.length>0&&(async e=>{const t=await Qn(e),{feedMarkers:n,userFeedMarkers:r}=t;mn({feedMarkers:n,userFeedMarkers:r}),ot("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 xa=null;var Da=()=>(xa||(xa=new Ua),xa),qa=()=>{const e=Da();return e.startResolver(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Na{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Pa((()=>{this.isConnected=!0}))),this.connectionListener.push(Ma((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{streamId:n}=t,r=Zt(t,["streamId"]);return e[n]?e[n].push(r):e[n]=[r],e}),{});Object.entries(t).forEach((([e,t])=>{(async({reactions:e,liveStreamId:t})=>{const n=Ee();n.log("live_reaction/addReaction",e);const{data:r}=await n.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e})})({liveStreamId:e,reactions:t})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Ba;var La=()=>(Ba||(Ba=new Na),Ba);const Fa=async()=>{var e;const t=Ee();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&la("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},Ka=e=>{const t=Ee();la("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,Fa()},$a=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Qa=e=>{const t=Ee(),n=$a.map((n=>st(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new Ie(t.message,t.code,"fatal"):new ke(n);e(r)}))));return()=>{n.forEach((e=>e()))}},za=e=>{const t=Ee();return st(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Va=e=>{const t=Ee();return st(t,"client/onTokenExpired","tokenExpired",e)},Ha=e=>{const t=Ee();return st(t,"client/onTokenTerminated","tokenTerminated",e)},Ja=e=>{const t=be("channelMarker")({userId:Xe()._id,entityId:e.channelId});xe(["channelMarker","get",t],!0)};let Wa=[];const Ga=async(e,t,n)=>{const r=Ee();let a;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await Fa(),Wa.forEach((e=>e())),Wa=[]);const s=await zt();try{const{users:n}=await da({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||s}),options:{setAccessTokenCookie:!0}}),o=n.find((t=>t.userId===e.userId));if(null==o)throw new Ie(`${e.userId} has not been founded`,8e5,"error");if(o.isDeleted)return Ka("userDeleted"),!1;if(o.isGlobalBanned)return Ka("globalBan"),!1;r.userId=o.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),et(o)}catch(e){throw zr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await lt()}(),await ta(),0===Wa.length&&(Wa.push(za((e=>{Ka("globalBan"),Wa.forEach((e=>e())),a()})),Ha((e=>{Ka(),Wa.forEach((e=>e())),a()})),pa((e=>{e.userId===r.userId&&(Ka("userDeleted"),Wa.forEach((e=>e())),a())})),Va((e=>{zr().setSessionState(e),Fa(),Wa.forEach((e=>e()))})),lr(Ja),Tr(Ja),Zr(),Ia(),qa(),(()=>{const e=La();return e.startReactionsSync(),Vr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()),r.useLegacyUnreadCount?Wa.push(Oa()):Wa.push(Ra())),!0},Ya=()=>{let e,t=!1;const n=Ee();n.log("initiating access token renewal");const r=async r=>{const{userId:a,displayName:s}=Xe(),o={userId:a,displayName:s,authToken:r,deviceId:await zt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await Ga(o,n.sessionHandler):await da({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Ya())}),G)}}},Za=3e5,Xa=e=>{const t=setInterval((()=>{const t=Ee();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-Za)(r))return ot("tokenExpired","tokenExpired"),void rt((()=>e.sessionWillRenewAccessToken(Ya())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),a=Date.parse(n),s=Date.now();return s>a+.8*(r-a-Za)&&s<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(Ya())}),G);return()=>clearInterval(t)},es=e=>{if(Ee().useLegacyUnreadCount){ka().markRead(e.channelId,e.channelSegment)}else{Aa().markRead(e.subChannelId,e.channelSegment)}},ts=e=>{const t=Ee(),n=Xe(),r=[st(t,"message/onMessageCreated","message.created",(async r=>{const a=await _n(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Ee(),r=["subChannelUnreadInfo","get",e.messageFeedId],a=null===(t=Pe(r))||void 0===t?void 0:t.data;if(!a)return;const s=a.lastSegment<e.segment?e.segment:a.lastSegment,o=s-a.readToSegment;let{lastMentionSegment:i}=a;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({},a),{lastMentionSegment:i,lastSegment:s,isMentioned:!(a.readToSegment>=i),unreadCount:Math.max(o,0)});Me(r,c)})(e),fn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const a=null===(n=Pe(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!a||a.lastSegment>=e.segment||"number"!=typeof a.readToSegment||"number"!=typeof a.lastMentionedSegment)return;const s=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:a.lastMentionedSegment,i=Object.assign(Object.assign({},a),{lastSegment:s,unreadCount:Math.max(s-a.readToSegment,0),lastMentionedSegment:o,isMentioned:!(a.readToSegment>=o)});Me(["channelUnread","get",e.channelId],i),ot("local.channelUnread.updated",[i])})),Gt(a),a.messages.forEach((t=>{t.creatorPrivateId===n._id&&es(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},ns=e=>{const t=Ee(),n=[st(t,"message/onMessageCreated","local.message.created",(async t=>(Gt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},rs=e=>{const t=Ee();return st(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Rn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:a}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:a};Me(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Gt(r),e(r.messageFeeds[0])}))},as=e=>{const t=Ee(),n=[st(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Rn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Pe(n))||void 0===t?void 0:t.data;r&&Me(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),fn(e.channelId)})),Gt(r),e(r.messageFeeds[0])})),st(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},ss=async e=>{const t=Ee();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=nn(r),c=rn(a),l=t.cache&&Date.now();return t.cache&&Gt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),ot("local.feedMarker.fetched",{feedMarkers:s}),ot("local.channelMarker.fetched",{userEntityMarkers:i}),ot("local.subChannelMarker.fetched",{userFeedMarkers:c}),ot("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let os=!1,is=[],cs=!1;let ls=null;let ds=[];const us=e=>{ds=e},hs=async()=>{var e;if(!cs&&0!==ds.length)try{cs=!0,ds=[];const t=await ss((null==ls?new Date:ls).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!ls||e.getTime()>ls.getTime())&&(ls=e),t.hasMore&&ds.push("has_more")}catch(e){}finally{cs&&(cs=!1)}};Hr((async()=>{os&&await hs()}),2e3);const ps=()=>true,fs=e=>{var t;const n=Ee();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};let ms=[];var gs;class ys{constructor(){gs.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,a){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?a.call(e,n):a?a.value=n:t.set(e,n)}(this,gs,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,gs,"f")}}let vs;gs=new WeakMap;var bs=()=>(vs||(vs=new ys),vs);const ws=e=>{const t=Ee();return st(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Cs=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Is=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Ss=e=>{const t=Ee();return st(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},_s=e=>{const t=Ee();return st(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ks=e=>{const t=Ee();return st(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,a;Gt(t);const s=Re(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.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==o?void 0:o.length)>0){(null!==(a=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Pe(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==a?a:[]).forEach((e=>{var t,n;const r=["messageMarker","get",be("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],a=null===(t=Pe(r))||void 0===t?void 0:t.data;if(!a)return;const s=o[0].feedId===a.feedId,i=o[0].readCount>a.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>a.deliveredCount;if(s){const e=Object.assign(Object.assign({},a),{readCount:i?o[0].readCount:a.readCount,deliveredCount:c?o[0].deliveredCount:a.deliveredCount});Me(r,e)}}))}}e(t.contentMarkers[0])}))};function Os(e){return"object"==typeof e&&null!==e}const Ts=e=>{if(!Os(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)},Es=e=>{if(!Os(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var As=Object.freeze({__proto__:null,getActiveClient:Ee,getActiveUser:Xe,setActiveUser:et,createClient:(e,t=Ot.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:a,rteEnabled:s=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!kt,n=m.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:Et("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:Et("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:Et("mqtt",t),p=xt(d),g=xt(u);let y;s&&(y=Wt(h));const v=f.default(),b={version:`${$}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:y,upload:g,emitter:v,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Xa,sessionHandler:undefined,hasPermission:aa,validateUrls:sa,validateTexts:oa,getFeedSettings:ia,getSocialSettings:na,getMessagePreviewSetting:ea,onRTEConnectionStateChange:fs,use:()=>Ae(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:ps,prefixDeviceIdKey:a};try{const t=Ee();if(t.apiKey===e)return t;Ae(b)}catch(e){Ae(b)}return b},login:Ga,logout:Fa,secureLogout:async()=>{const e=Ee(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Fa()},resumeSession:async(e,t,n)=>{const r=Ee();let a;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&(e=>{var t;const n=Ee(),r=w.default(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId})(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),ms.forEach((e=>e())),ms=[]):(await Fa(),ms.forEach((e=>e())),ms=[]));try{const n=await(async({token:e,userId:t})=>{const n=Ee();la("establishing");const{data:{users:r}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),a=r.find((e=>e.userId===t));return n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,la("established"),a})(e);if(null==n)throw new Ie(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return Ka("userDeleted"),!1;if(n.isGlobalBanned)return Ka("globalBan"),!1;r.userId=n.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),et(n)}catch(e){throw zr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await lt()}(),await ta(),0===ms.length&&(ms.push(za((e=>{Ka("globalBan"),ms.forEach((e=>e())),a()})),Ha((e=>{Ka(),ms.forEach((e=>e())),a()})),pa((e=>{e.userId===r.userId&&(Ka("userDeleted"),ms.forEach((e=>e())),a())})),Va((e=>{zr().setSessionState(e),Fa(),ms.forEach((e=>e()))})),lr(Ja),Tr(Ja),Zr(),Ia(),qa()),r.useLegacyUnreadCount?ms.push(Oa()):ms.push(Ra())),!0},isConnected:()=>{var e,t;const n=Ee();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:ia,renewal:Ya,markerSync:ss,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){bs().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ee();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Oe("Unsupported platform");n=l.Platform.OS;const r=await zt(),{data:{status:a,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new Se(s,5e5,"error");return"success"===a},unregisterPushNotification:async()=>{const e=Ee(),t=zt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new Se(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:fs,fetchLinkPreview:async e=>{const t=Ee();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getSocialSettings:na,getShareableLinkConfiguration:async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v3/network-settings/shareable-deep-links");return t},onConnectionError:Qa,onClientDisconnected:e=>Qa((({code:t})=>{800211===t&&e()})),onClientBanned:za,onSessionStateChange:Vr,onNetworkActivities:e=>Mt().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=Xe();if(!t)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ee();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Ts(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(Ss((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),a=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==a?void 0:a.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};Zn(s,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=fe(gn);ge(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(s===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e())))}))})(),()=>{a.forEach((e=>e()))}},getMarkerSyncEvents:()=>ds,setMarkerSyncEvents:us,pushMarkerSyncEvent:e=>ds.push(e),markerSyncTrigger:hs,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{os=!1,us([]),is.forEach((e=>e())),is=[]},getMarkerSyncConsistentMode:ps});function Rs(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Tn)})}function Ps(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Tn)})}function Ms(e){const{follows:t}=e,n=Zt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const js=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Rs(e);n.cache?(Gt(r),t(r.follows[0])):t(r.follows[0])}))},Us=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Ms(e);n.cache?(Gt(r),t(r.follows[0])):t(r.follows[0])}))},xs=e=>js("follow.created",e),Ds=e=>js("follow.unfollowed",e),qs=e=>js("follow.followerDeleted",e),Ns=e=>js("follow.requested",e),Bs=e=>js("follow.requestCanceled",e),Ls=e=>js("follow.accepted",e),Fs=e=>js("follow.requestDeclined",e),Ks=async e=>{var t,n;const r=Ee();r.log("follow/getFollowInfo",e);const{data:a}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),o="follows"in a?Object.assign(Object.assign({},a.followCounts[0]),{status:null===(n=null===(t=a.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):a.followCounts[0];return r.cache&&Me(["followInfo","get",e],o,{cachedAt:s}),{data:o,cachedAt:s}};Ks.locally=e=>{const t=Ee();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Pe(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $s=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([Ks(t.from),Ks(t.to)]);e(n),e(r)},n=[js("follow.created",t),js("follow.requested",t),js("follow.accepted",t),js("follow.unfollowed",t),js("follow.requestCanceled",t),js("follow.requestDeclined",t),js("follow.followerDeleted",t),Us("local.follow.created",t),Us("local.follow.requested",t),Us("local.follow.accepted",t),Us("local.follow.unfollowed",t),Us("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},Qs=e=>Us("local.follow.created",e),zs=e=>Us("local.follow.unfollowed",e),Vs=e=>Us("local.follow.requested",e),Hs=e=>Us("local.follow.accepted",e),Js=e=>Us("local.follow.requestDeclined",e);class Ws{constructor(e){const{http:t}=Ee();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,a;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const o=await this.getRequest(this.queryParams,s);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===(a=o.paging)||void 0===a?void 0:a.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Gs extends Ws{async getRequest(e,t){const{limit:n=Q,userId:r}=e,a=Zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ee().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}class Ys{constructor(e,t){this.query=e,this.cacheKey=t}}var Zs;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Zs||(Zs={}));class Xs extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(be("follow"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(be("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Zs.OnDeclined:case Zs.OnCanceled:case Zs.OnUnfollowed:case Zs.OnDeleted:r.data=r.data.filter((e=>e!==be("follow")(t)));break;case Zs.OnRequested:case Zs.OnAccepted:case Zs.OnFollowed:r.data=[...new Set([be("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class eo{constructor(e){const{http:t}=Ee();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class to{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 eo?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 eo)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 eo)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(Ts).map(Es);return!Zn(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function no(e){return null!=e}const ro=({userId:e})=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{const r=ua(n);Gt(r);const a=Pe(["follow","get",be("follow")({from:r.users[0].userId,to:e})]);a&&t(null==a?void 0:a.data)}))};class ao extends to{constructor(e,t){const n=C.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new Gs(e),n,r,t),this.query=e,this.queryStreamController=new Xs(this.query,this.cacheKey,this.notifyChange.bind(this),Rs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:xs,action:Zs.OnFollowed},{fn:Ds,action:Zs.OnUnfollowed},{fn:Ls,action:Zs.OnAccepted},{fn:Fs,action:Zs.OnDeclined},{fn:Bs,action:Zs.OnCanceled},{fn:qs,action:Zs.OnDeleted},{fn:Hs,action:Zs.OnAccepted},{fn:Js,action:Zs.OnDeclined},{fn:Qs,action:Zs.OnFollowed},{fn:zs,action:Zs.OnUnfollowed},{fn:ro({userId:this.query.userId}),action:Zs.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["follow","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Pe(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class so extends Ws{async getRequest(e,t){const{limit:n=Q,userId:r}=e,a=Zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ee().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}class oo extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(be("follow"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(be("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Zs.OnDeclined:case Zs.OnCanceled:case Zs.OnUnfollowed:case Zs.OnDeleted:r.data=r.data.filter((e=>e!==be("follow")(t)));break;case Zs.OnRequested:case Zs.OnAccepted:case Zs.OnFollowed:r.data=[...new Set([be("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const io=({userId:e})=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{const r=ua(n);Gt(r);const a=Pe(["follow","get",be("follow")({from:e,to:r.users[0].userId})]);a&&t(null==a?void 0:a.data)}))};class co extends to{constructor(e,t){const n=C.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new so(e),n,r,t),this.query=e,this.queryStreamController=new oo(this.query,this.cacheKey,this.notifyChange.bind(this),Ps),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Ns,action:Zs.OnRequested},{fn:Ls,action:Zs.OnAccepted},{fn:Fs,action:Zs.OnDeclined},{fn:Bs,action:Zs.OnCanceled},{fn:xs,action:Zs.OnFollowed},{fn:Ds,action:Zs.OnUnfollowed},{fn:qs,action:Zs.OnDeleted},{fn:Vs,action:Zs.OnRequested},{fn:Hs,action:Zs.OnAccepted},{fn:Js,action:Zs.OnDeclined},{fn:Qs,action:Zs.OnFollowed},{fn:zs,action:Zs.OnUnfollowed},{fn:io({userId:this.query.userId}),action:Zs.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["follow","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Pe(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const lo=(e,t,n,r,a,s)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=Ee();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=Zt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Ts(n)};return h.push(...a.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&Zn(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=fe(r,e,!0);ge(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===J?(p({data:t,origin:r,loading:!1,error:new Se(H,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,blockUser:async e=>{const t=Ee();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Gt(o,{cachedAt:r}),Ue(["followInfo","get",e],s[0],{cachedAt:r}));const i=Ms(o);return ot("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=Ee();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Gt(o,{cachedAt:r}),Ue(["followInfo","get",e],s[0],{cachedAt:r}));const i=Ms(o);return ot("local.follow.created",i),n},follow:async e=>{const t=Ee();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const a=Ms(n);return"accepted"===n.follows[0].status?ot("local.follow.created",a):ot("local.follow.requested",a),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Ee();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Ee();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Ee();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Gt(n);const r=Ms(n);return ot("local.follow.requestDeclined",r),!0},onUserFollowed:xs,onUserUnfollowed:Ds,onFollowerDeleted:qs,onFollowerRequested:Ns,onFollowRequestCanceled:Bs,onFollowRequestAccepted:Ls,onFollowRequestDeclined:Fs,onFollowInfoUpdated:$s,onLocalUserFollowed:Qs,onLocalUserUnfollowed:zs,onLocalFollowerRequested:Vs,onLocalFollowRequestAccepted:Hs,onLocalFollowRequestDeclined:Js,getFollowers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const o=new ao(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const o=new co(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>lo(e,t,"userId",Ks,[$s],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Xe();return lo(t,e,"userId",Ks,[$s],{forceDispatch:!0})}});class ho{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Pe(["story-expire",this._targetId]),this.cacheStoreSeenTime=Pe(["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=Pe(["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 Pe(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Re(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:a}}=t;return n!==this._targetId||a||(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 po=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:a,targetUpdatedAt:s,localFilter:o}=e,i=new ho(n,r,a);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},fo=async e=>{const t=Ee();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,a=Zt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},a),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await $n(n.data),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{channels:s}=r;return{data:Fr(s[0]),cachedAt:a}},mo=async e=>{const t=Ee();let n;t.log("channel/getChannel",e),pn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await $n(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&zn(r)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("channel",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{channels:a}=n;return{data:a.find((t=>t.channelId===e)),cachedAt:r}};mo.locally=e=>{var t;const n=Ee();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Re(["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 go=Symbol("getWatcherUrls"),yo=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Pe(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Pe(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Pe(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Pe(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=Pe(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return yo(n)})).filter(no):[]},getLiveChat:()=>(async e=>{var t;const n=Ee();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=Pe(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Lr(Fr(n));const{data:r}=await mo(e.channelId);return Lr(Fr(r))}if(e.userId===n.userId){const{data:t}=await fo({type:"live",postId:e.postId,videoStreamId:e.streamId});return je(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[go](){return e.watcherUrl}}),vo=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Pe(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),bo=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=Pe(["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=Pe(["user","get",e.userId]);if(null==t?void 0:t.data)return sn(t.data)},get childrenComment(){return e.children.map((e=>{const t=Pe(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(no).map((e=>bo(e)))}});function wo(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Co(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const Io=e=>un(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=Pe(["post","get",e]))||void 0===t?void 0:t.data})).filter(no).map(Io),analytics:{markAsViewed:()=>{Ca().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Pe(["comment","get",e]))||void 0===t?void 0:t.data;return n?bo(n):null})).filter(Boolean)||[]},get creator(){const t=Pe(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return sn(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return wo(e)?null===(r=Pe(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return wo(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getLivestreamInfo(){var t,n;if(!Co(e))return;const r=null===(n=Pe(["stream","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.streamId]))||void 0===n?void 0:n.data;return r?yo(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e))return;const r=null===(n=Pe(["poll","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.pollId]))||void 0===n?void 0:n.data;return r||void 0},getClipInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)?null===(n=Pe(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0}}),So=(e,t)=>{"message"===e?ot("local.message.updated",{messages:[t]}):"post"===e?ot("post.updated",{posts:[t]}):"comment"===e?ot("comment.updated",{comments:[t]}):"story"===e&&ot("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},_o=async(e,t,n,r)=>{var a,s,o;const i=Ee();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(i.cache){const r=Pe([e,"get",t]);if(!r||(null===(a=r.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(s=r.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(o=r.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return ot("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0}return!0};_o.optimistically=(e,t,n)=>{var r,a,s,o,i;const c=Ee();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Pe([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Ue([e,"get",t],d,{cachedAt:J}),So(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const ko=(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=Pe(["messageMarker","get",be("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Oo=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var a,s;const o=Ee();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(o.cache){const r=Pe([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return ot("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)};function To(e,t){return e.map((e=>{const n=Pe(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=Xe();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Eo=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:R};function Ao({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Zt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Eo({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Ro=e=>{const t=Ao({communities:e.communities}),n=e.users.map(Tn),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=To(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(Tn),communities:a,communityUsers:r})},Po=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(Tn);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Mo=e=>{const t=Ao({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=To(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},jo=e=>{const{postSetting:t,storySetting:n}=e,r=Zt(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})},Uo=e=>{var t=Zt(e,["searchResult"]);const n=Ro(t);return Object.assign({},n)},xo=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Pe(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return sn(n)},cancel:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),ot("local.joinRequest.deleted",[a])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"approved"}),ot("local.joinRequest.updated",[a])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ee();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),a=null===(t=Pe(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Ue(["joinRequest","get",e.joinRequestId],{status:"rejected"}),ot("local.joinRequest.updated",[a])),r.success})(e)}});class Do extends Ws{async getRequest(e,t){const{limit:n=20,communityId:r}=e,a=Zt(e,["limit","communityId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},a),{options:s})});return o}}var qo;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(qo||(qo={}));class No extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===qo.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===qo.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===qo.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Bo=e=>{const t=Ee(),n=[st(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Lo=e=>{const t=Ee(),n=[st(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Fo=e=>{const t=Ee(),n=[st(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Ko extends to{constructor(e,t){const n=C.default(e),r=["joinRequest","collection",n];super(new Do(e),n,r,t),this.query=e,this.queryStreamController=new No(this.query,this.cacheKey,this.notifyChange.bind(this),Po),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bo,action:qo.OnLocalJoinRequestCreated},{fn:Lo,action:qo.OnLocalJoinRequestUpdated},{fn:Fo,action:qo.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Pe(["joinRequest","get",e]))).filter(no).map((({data:e})=>e)).map(xo));(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;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}const $o=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Qo=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map($o),users:e.users.map(Tn)}),zo=e=>Object.assign(Object.assign({},e),{users:e.users.map(Tn),invitations:e.invitations.map($o)}),Vo=e=>Object.assign(Object.assign({},e),{get user(){const t=Pe(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get createdBy(){const t=Pe(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get target(){if("community"===e.targetType){const t=Pe(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ee();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),a=null===(t=Pe(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Ue(["invitation","get",e],{status:"approved"}),ot("local.invitation.updated",[a])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ee();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),a=null===(t=Pe(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Ue(["invitation","get",e],{status:"rejected"}),ot("local.invitation.updated",[a])),r.success})(e._id)}});var Ho;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationDeleted="onLocalInvitationDeleted"}(Ho||(Ho={}));class Jo extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class Wo extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(be("invitation"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(be("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Ho.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===Ho.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===Ho.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Go=e=>{const t=Ee(),n=[st(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Yo=e=>{const t=Ee(),n=[st(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Zo=e=>{const t=Ee(),n=[st(t,"onLocalInvitationDeleted","local.invitation.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Xo extends to{constructor(e,t){const n=C.default(e),r=["invitation","collection",n];super(new Jo(e),n,r,t),this.query=e,this.queryStreamController=new Wo(this.query,this.cacheKey,this.notifyChange.bind(this),Qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Go,action:Ho.OnLocalInvitationCreated},{fn:Yo,action:Ho.OnLocalInvitationUpdated},{fn:Zo,action:Ho.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["invitation","get",e]))).filter(no).map((({data:e})=>Vo(e))))&&void 0!==a?a:[]);(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;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}const ei=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=Pe(["category","get",e]);if(null==t?void 0:t.data)return vo(t.data)})).filter((e=>!!e))},createInvitations:async t=>{await(async e=>{const t=Ee();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=Qo(n),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:a}})({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getInvitations: (tmpid: ${s}) > listen`);const o=new Xo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await(async(e,t)=>{const n=Ee();n.log("invitation/getInvitation",e,t);const{data:r}=await n.http.get("/api/v1/invitations/me",{params:{targetType:e,targetId:t}}),a=zo(r),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),{data:a.invitations[0]?Vo(a.invitations[0]):void 0,cachedAt:s}})("community",e.communityId);return t},join:async()=>(async e=>{var t;const n=Ee();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),a=Po(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const o="approved"===a.joinRequests[0].status?"success":"pending";if("success"===o&&n.cache){const n=null===(t=Pe(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});Ue(["community","get",e],t)}}return ot("v4.local.community.joined",a.joinRequests),"success"===o?{status:o}:{status:o,request:xo(a.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getJoinRequests: (tmpid: ${s}) > listen`);const o=new Ko(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getJoinRequests (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ee();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=Po(n),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.joinRequests[0]?xo(r.joinRequests[0]):void 0,cachedAt:a}})(e.communityId);return t}}),ti={ad:e=>{const t=Ca(),{image9_16:n,image1_1:r}=e,a=Zt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},a),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Pe(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const a=null===(n=Pe(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:a})},get image1_1(){const e=Pe(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Pe(["file","get",n]);if(e)return e.data||void 0}})},comment:bo,post:Io,user:sn,category:vo,stream:yo,story:e=>{const t=Ca(),n=Pe(["storyTarget","get",e.targetId]),r=Pe(["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=Pe(["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:a}=r;return a||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Pe(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:a}=r;return a?Object.assign(Object.assign({},a),{fileUrl:`${a.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=Pe(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Pe(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return po(n.data)},get isSeen(){const t=Pe(["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,a=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(r,a)>=s}})},storyTarget:po,message:e=>{const t=Zt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return ko(e).readCount},get deliveredCount(){return ko(e).deliveredCount},get creator(){var t;return null===(t=Pe(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>es(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return _o("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Oo(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Pe(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return sn(n)}}),channel:Lr,pinnedPost:e=>{var t;const n=Pe(["post","get",e.referenceId]),r=null===(t=Re(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return Io(n.data)},get target(){const e=Pe(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map((e=>sn(e)))}),community:ei,invitation:Vo,joinRequest:xo,channelMember:Gn},ni=async e=>{const t=Ee();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}}),a=ua(r),s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),ot("user.fetched",r),{data:a.users.map((e=>ti.user(e))),cachedAt:s}};ni.locally=e=>{var t;const n=Ee();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Pe(["user","get",e]))).filter(Boolean),a=r.map((({data:e})=>ti.user(e))),s=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:a,cachedAt:s.cachedAt}};const ri=e=>ha("user.updated",e),ai=e=>ha("user.flagged",e),si=e=>ha("user.unflagged",e),oi=e=>ha("user.flagCleared",e),ii=e=>ha("user.fetched",e),ci=async e=>{const t=Ee();t.log("user/getUser",e),pn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),a=ua(n);return t.cache&&Gt(a,{cachedAt:r}),ot("user.fetched",n),{data:a.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ne(null==t?void 0:t.code)&&Yt("user",e),t}};ci.locally=e=>{const t=Ee();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Pe(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class li extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class di extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ui;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(ui||(ui={}));class hi extends to{constructor(e,t){const n=C.default(e),r=["user","collection",n];super(new li(e),n,r,t),this.query=e,this.queryStreamController=new di(this.query,this.cacheKey,this.notifyChange.bind(this),ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:ui.OnUserDeleted},{fn:ri,action:ui.OnUserUpdated},{fn:ai,action:ui.OnUserFlagged},{fn:si,action:ui.OnUserUnflagged},{fn:oi,action:ui.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ti.user))&&void 0!==a?a:[]);(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;const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class pi extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class fi extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return t=>{var n;if(e===Zs.OnFollowed){const e=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Me(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function mi(e){const{users:t,follows:n}=e,r=Zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Tn(n)})})),users:t.map(Tn)})}const gi=(e,t,n)=>r=>e((e=>{var a;if(!e)return e;const s=[n,"get",`${e[t]}`],o=null===(a=Pe(s))||void 0===a?void 0:a.data;return o?r(o):void 0}));class yi extends to{constructor(e,t){const n=C.default(e),r=["blockedUsers","collection",n];super(new pi(e),n,r,t),this.query=e,this.queryStreamController=new fi(this.query,this.cacheKey,this.notifyChange.bind(this),mi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:ui.OnUserDeleted},{fn:gi(Qs,"to","user"),action:Zs.OnFollowed},{fn:gi(xs,"to","user"),action:Zs.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ti.user))&&void 0!==a?a:[]);(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 t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class vi extends Ws{async getRequest(e,t){const{limit:n=Q,displayName:r}=e,a=Zt(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:null==r?void 0:r.toLocaleLowerCase(),options:s,isDeleted:!1})});return o}}class bi extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(be("user"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(be("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class wi extends to{constructor(e,t){var n;const r=C.default(e),a=["user","collection",r];super(new vi(e),r,a,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new bi(this.query,this.cacheKey,this.notifyChange.bind(this),ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:pa,action:ui.OnUserDeleted},{fn:ri,action:ui.OnUserUpdated},{fn:ai,action:ui.OnUserFlagged},{fn:si,action:ui.OnUserUnflagged},{fn:oi,action:ui.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["user","get",e]))).filter(no).map((({data:e})=>e)).map(ti.user))&&void 0!==a?a:[]);(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"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Ci=async({viewId:e,viewedType:t,limit:n,token:r})=>{const a=Ee(),s={};r?s.token=r:s.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await a.http.get(o,{params:s});return Gt(i.data),i.data};var Ii;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ii||(Ii={}));var Si=Object.freeze({__proto__:null,Relationship:uo,getUserByIds:ni,updateUser:async(e,t)=>{const n=Ee();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})),a=ua(r),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),ot("user.updated",r),{data:a.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=Ee();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=ua(n);return t.cache&&Gt(r),ot("user.flagged",n),!!r},unflagUser:async e=>{const t=Ee();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=ua(n);return t.cache&&Gt(r),ot("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Ee();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:ri,onUserDeleted:pa,onUserFlagged:ai,onUserUnflagged:si,onUserFlagCleared:oi,getUser:(e,t)=>lo(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?ti.user(e.data):e.data}))),"userId",ci,[ii,ri,pa,ai,si,oi]),getUsers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const o=new hi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const o=new yi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),xe(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`liveSearchUsers(tmpid: ${s}) > listen`);const o=new wi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:a}=Ee(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];a||console.log(V);const o=Date.now();r(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,a,o;const d=null===(r=Pe(s))||void 0===r?void 0:r.data,u=null!==(a=null==d?void 0:d.data)&&void 0!==a?a:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=fe(Ci,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});ge(h,(e=>{var r,a,o,i,c;let l=null!==(o=null===(a=null===(r=Pe(s))||void 0===r?void 0:r.data)||void 0===a?void 0:a.data)&&void 0!==o?o:[];(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||[]};Me(s,d),(e=>{var r,a;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Pe(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(a=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===a?void 0:a.next),loading:e.loading||!1})})(d)}),me(z,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${o}) > dispose`),xe(s)}},get AmityUserSearchMatchType(){return Ii}});const _i=async e=>{const t=Ee();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Gt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};_i.locally=e=>{const t=Ee();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Pe(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ki=async(e,t,n)=>{const r=Ee();r.log("file/uploadVideo",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const s=bs().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},Oi=async(e,t,n)=>{const r=Ee();r.log("file/uploadImage",e);const a=e.getAll("files");if(null==a?void 0:a.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",a[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const s=bs().getFileAccessType();e.append("accessType",s);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Ti=Object.freeze({__proto__:null,getFile:_i,uploadFile:async(e,t)=>{const n=Ee();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const a=bs().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Gt({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=Ee();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),xe(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ki,uploadImage:Oi,updateAltText:async(e,t)=>{const n=Ee();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),a=n.cache&&Date.now();return n.cache&&Gt({files:[r]},{cachedAt:a}),!0},uploadClip:async(e,t,n)=>{const r=Ee();r.log("file/uploadClip",e);const a=e.get("files");if(!a)throw new Error("The formData object must have a `files` key.");const s=bs().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a.name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/clips",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Gt({files:i},{cachedAt:c}),{data:i,cachedAt:c}}});const Ei=async e=>{const t=Ee();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:a,displayName:s,sortBy:o}=n,i=Zt(n,["limit","queryToken","displayName","sortBy"]),c=a?{token:a}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:s,sortBy:o,options:c})}),{paging:d}=l,u=Zt(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Gt(u,{cachedAt:p});const f=ce(d.next);return{data:h,cachedAt:p,prevPage:ce(d.previous),nextPage:f,paging:d}};Ei.locally=e=>{Ee().log("role/queryRoles.locally",e)};const Ai=async e=>{const t=Ee();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Gt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Ai.locally=e=>{const t=Ee();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Pe(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ri=async(e,t=!1)=>{const n=Ee();let r;n.log("message/getMessage",e),pn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await _n(t)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("message",e),t}const a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{messages:s}=r;return ot("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:a}};Ri.locally=e=>{const t=Ee();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Pe(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Pi=async e=>{const t=Ee();let n;t.log("post/getPost",e),pn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("post",e),t}const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};Pi.locally=e=>{const t=Ee();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Pe(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Mi=async e=>{const t=Ee();let n;t.log("comment/getComment",e),pn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{comments:a}=n;return{data:ti.comment(a.find((t=>t.commentId===e))),cachedAt:r}};Mi.locally=e=>{const t=Ee();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Pe(["comment","get",e]);return n?{data:ti.comment(n.data),cachedAt:n.cachedAt}:void 0};const ji=(e,t)=>{var n,r;let a,s;if("post"===t)s="post",a=e.posts[0].postId;else if("comment"===t)s="comment",a=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",a=e.stories[0].referenceId}return(null===(r=null===(n=Pe([s,"get",a]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Ui=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},xi=(e,t,n,r=[])=>{const a=e.split(".")[1];let s=r;if(Ee().userId===t)if(["addReaction","reactionAdded"].includes(a))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(a))throw new Error(`Unknown event type: ${a}`);s=s.filter((e=>e!==n))}return s},Di=(e,t)=>{const n=e.split(".")[0],r=ji(t,n),a=xi(e,t.reactor.userId,t.reactor.reactionName,r);return Ui(t,`${n}s`,a)},qi=(e,t)=>{var n,r;const a=e.split(".")[0];let s=ji(t,a);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=xi(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,s));const o=Ui(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=To(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},Ni=async(e,t,n)=>{var r,a,s;const o=Ee();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Pe([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(a=c.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return ot("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};Ni.optimistically=(e,t,n)=>{var r,a,s,o,i;const c=Ee();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Pe([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Ue([e,"get",t],d,{cachedAt:J}),So(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Bi=async(e,t,n)=>{var r,a;const s=Ee();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(s.cache){const i=Pe([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(a=i.data.reactions[n])&&void 0!==a?a:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ot("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return ot("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return ot("local.story.reactionAdded",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};Bi.optimistically=(e,t,n)=>{var r,a,s,o;const i=Ee();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Pe([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 l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(a=c.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)-1)})});return Ue([e,"get",t],l,{cachedAt:J}),So(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const Li=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,a=Zt(e,["posts","postChildren","videoStreamings"]),s=Ao({communities:a.communities}),o=a.communityUsers.map((e=>{const t=a.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=To(s,o);let c=[];const l=t.map((t=>{var n,s;const o=null===(n=a.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,i=e.postChildren.filter((e=>e.parentPostId===t.postId));var l,d,u;return i.length>0&&Co(i[0])&&(l=r,d=null===(s=i[0].data)||void 0===s?void 0:s.streamId,u=t.postId,c=d?l.map((e=>e.streamId===d?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:u,postId:u}):e)):l),Object.assign(Object.assign({},t),{childPosts:i,feedType:o})}));return Object.assign(Object.assign({},a),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:o})},Fi=e=>{var{searchResult:t,polls:n}=e,r=Zt(e,["searchResult","polls"]);const a=Li(r);return Object.assign(Object.assign({},a),{polls:n})},Ki=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=Pe(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;Me(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>je(["post","get",e],{isDeleted:!0})))},$i=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a;if(n.cache){const s=Li(r),{communities:o}=s;if(Gt(s,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&ot("community.updated",{communities:o,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:a}=r.posts[0];Ki(r);try{pn("post",e)}catch(e){return}return a!==n.userId&&xe(["post","get",e]),t(r.posts[0])}const i=Pe(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(a=Re(["post","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===i.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})=>Ue(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=Pe(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&Me(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(i.data)}else t(r.posts[0])}))},Qi=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{if(n.cache){const n=Li(r),{communities:a}=n;Gt(n),(null==a?void 0:a[0])&&!["local.post.updated"].includes(e)&&ot("community.updated",{communities:a,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const s=Pe(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&Ki(r),t(s.data)}else t(r.posts[0])}))},zi=e=>$i("post.created",e),Vi=e=>$i("post.updated",e),Hi=e=>$i("post.deleted",e),Ji=e=>$i("post.approved",e),Wi=e=>$i("post.declined",e),Gi=e=>$i("post.flagged",e),Yi=e=>$i("post.unflagged",e),Zi=e=>{const t=Ee();return st(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Zt(Di("post.addReaction",n),["reactor"]);Gt(t);const r=Pe(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Xi=e=>{const t=Ee();return st(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Zt(Di("post.removeReaction",n),["reactor"]);Gt(t);const r=Pe(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},ec=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a;if(n.cache){const s=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=ji(e,"comment");return Ui(e,"comments",t)})(r):r;Gt(s,void 0,!1);const{comments:o}=s;if(o.length>0){const r=Pe(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||Me(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t)}}const t=null===(a=Re(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>Ue(e,t,{cachedAt:-1})))}t(ti.comment(r.data))}}else t(ti.comment(r.comments[0]))}))},tc=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{var a,s;if(n.cache){const n=r;Gt(n);const{comments:o}=n;if(o.length>0){const n=Pe(["comment","get",o[0].commentId]);if(["local.comment.created"].includes(e)){if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{ot("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Re(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Ue(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(o[0].parentId){const e=Pe(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{ot("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(s=Re(["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})=>Ue(e,t,{cachedAt:-1})))}t(ti.comment(n.data))}}else t(ti.comment(r.comments[0]))}))},nc=e=>ec("comment.created",e),rc=e=>ec("comment.updated",e),ac=e=>ec("comment.deleted",e),sc=e=>ec("comment.flagged",e),oc=e=>ec("comment.unflagged",e),ic=e=>{const t=Ee();return st(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Zt(Di("comment.addReaction",n),["reactor"]);Gt(t);const r=Pe(["comment","get",n.comments[0].commentId]);e(ti.comment(r.data))}else e(ti.comment(n.comments[0]))}))},cc=e=>{const t=Ee();return st(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Zt(Di("comment.removeReaction",n),["reactor"]);Gt(t);const r=Pe(["comment","get",n.comments[0].commentId]);e(ti.comment(r.data))}else e(ti.comment(n.comments[0]))}))},lc=(e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return st(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),Gt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return st(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return st(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return st(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))},dc=(e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return st(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return st(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return st(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return st(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Zt(e,["reactor"]);Gt(n),Gt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))};class uc extends Ws{async getRequest(e,t){const{limit:n=Q,referenceType:r}=e,a=Zt(e,["limit","referenceType"]),s=t?{token:t}:{limit:n};Ee().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new Se("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},a),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:s})});return o}}class hc extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Ee(),a=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=Zt(n,["reactions"]);Gt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:a})}}appendToQueryStream(e,t,n=!1){var r,a,s,o;const i=null!==(a=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==a?a:[];if(n)Me(this.cacheKey,{data:i.map(be("reactor"))});else{const e=null===(s=Pe(this.cacheKey))||void 0===s?void 0:s.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];Me(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(be("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class pc extends to{constructor(e,t){const n=C.default(e),r=["reaction","collection",n];super(new uc(e),n,r,t),this.query=e,this.queryStreamController=new hc(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>lc(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>dc(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return st(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return st(r,"local.post.removeReaction","local.post.removeReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return st(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return st(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ee(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return st(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await _n(e);t.reactions[0]&&(Gt(t),Gt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return st(r,"local.post.addReaction","local.post.addReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return st(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Zt(e,["reactions"]);Gt(n),Gt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return st(r,"local.comment.addReaction","local.comment.addReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["reactor","get",e]))).filter(Boolean).map((({data:e})=>ti.reactor(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var fc=Object.freeze({__proto__:null,addReaction:Ni,removeReaction:Bi,onReactionAdded:(e,t,n)=>{const r=r=>{be(e)(r)===t&&n(r)};if("message"===e){const e=Ee(),t=async e=>{var t;const n=await _n(e),a=Pe(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Gt(n),s&&r(n.messages[0])};return st(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Zi(r):ic(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{be(e)(r)===t&&n(r)};if("message"===e){const e=Ee(),t=async e=>{var t;const n=await _n(e),a=Pe(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Gt(n),s&&r(n.messages[0])};return st(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Xi(r):cc(r)},onReactorAdded:lc,onReactorRemoved:dc,getReactions:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getReactions(tmpid: ${s}) > listen`);const o=new pc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getReactions(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});function mc(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const gc=e=>{const t=Ee(),n=[st(t,"onMessageUpdated","message.updated",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])})),st(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},yc=e=>{const t=Ee(),n=[st(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])})),st(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},vc=e=>{const t=Ee(),n=[st(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Rn(t);Gt(n),e(n.messageFeeds[0])})),st(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function bc(e,t){Me(["channel","get",e.channelId],un(e,t))}const wc=e=>{const t=Ee();return st(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Cc=async(e,t=!1)=>{const n=Ee(),r=await Pn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const a=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Ce(r.data.updatedAt)});return t?setTimeout((()=>{Yt("subChannel",e)}),0):Ue(["subChannel","get",e],a),ot("local.message-feed.deleted",{messageFeeds:[a]}),a},Ic=e=>st(Ee(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Sc=()=>`LOCAL_${$t()}`;let _c;const kc=async(e,t)=>{const n=Ee();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)}`,kn(t)),a=await _n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{messages:o}=a;return ot("local.message.updated",{messages:o}),{data:ti.message(o.find((t=>t.messageId===e))),cachedAt:s}};kc.optimistically=(e,t)=>{const n=Ee();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Pe(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Ue(["message","get",e],a,{cachedAt:-1}),ot("local.message.updated",{messages:[a]}),{data:ti.message(a),cachedAt:-1}};const Oc=async(e,t)=>{const n=Ee();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,kn(t)),a=await _n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{messages:o}=a;return ot("local.message.updated",{messages:o}),{data:ti.message(o.find((t=>t.messageId===e))),cachedAt:s}};Oc.optimistically=(e,t)=>{const n=Ee();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Pe(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Ue(["message","get",e],a,{cachedAt:-1}),ot("local.message.updated",{messages:[a]}),{data:ti.message(a),cachedAt:-1}};const Tc=async e=>{var t;const n=Ee();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=Pe(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return ot("local.message.deleted",{messages:[r]}),ti.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),a=await _n(r);return ot("local.message.deleted",{messages:[a.messages[0]]}),ti.message(a.messages[0])};Tc.optimistically=e=>{Ee().log("message/deleteMessage.optimistically",e);const t=Pe(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ue(["message","get",e],n,{cachedAt:-1}),ot("local.message.deleted",{messages:[n]}),{data:ti.message(n),cachedAt:-1}};const Ec=async e=>{const t=Ee();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Ri(e);return ot("local.message.deleted",{messages:[n.data]}),ti.message(n.data)};Ec.optimistically=e=>{Ee().log("message/softDeleteMessage.optimistically",e);const t=Pe(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ue(["message","get",e],n,{cachedAt:-1}),ot("local.message.deleted",{messages:[n]}),{data:ti.message(n),cachedAt:-1}};const Ac=async e=>{const t=Ee();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,a=Zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},a),{options:{token:ie(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},l),{userFeedMarkers:rn(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ni(i));return{data:u,cachedAt:d,prevPage:ce(o.previous),nextPage:ce(o.next)}};Ac.locally=e=>{var t;const n=Ee();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,a=Zt(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Pe(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ce(null==o?void 0:o.paging.previous),nextPage:ce(null==o?void 0:o.paging.next)}};const Rc=async e=>{const t=Ee();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,a=Zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},a),{options:{token:ie(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},l),{userFeedMarkers:rn(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ni(i));return{data:u,cachedAt:d,prevPage:ce(o.previous),nextPage:ce(o.next)}};Rc.locally=e=>{var t;const n=Ee();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,a=Zt(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Pe(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ce(null==o?void 0:o.paging.previous),nextPage:ce(null==o?void 0:o.paging.next)}};const Pc=e=>{const t=Ee();return st(t,"onMessageFlagged","message.flagged",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},Mc=e=>{const t=Ee();return st(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},jc=e=>{const t=Ee();return st(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await _n(t);Gt(n),e(n.messages[0])}))},Uc=e=>{const t=Ee();return st(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await _n(t,"message.reactionAdded");Gt(n),e(n.messages[0])}))},xc=e=>{const t=Ee();return st(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await _n(t,"message.reactionRemoved");Gt(n),e(n.messages[0])}))},Dc=e=>{const t=Ee();return st(t,"message/onMessageFetched","local.message.fetched",(t=>{Gt(t),e(t.messages[0])}))},qc=e=>{const t=Ee();return st(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;je(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Re(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{je(e.key,{isDeleted:!0})}))}));const a=null===(n=Pe(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))};class Nc extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messages.map(be("message")),query:this.query});else{const n=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,s=null!==(a=null==n?void 0:n.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...e.messages.map(be("message"))])]:[...new Set([...e.messages.map(be("message")),...s])]}))}}reactor(e){return t=>{var n,r,a,s;if("onCreate"===e){const e=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:s}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(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;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=s?s:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=s?s:t.messageId])]),Me(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(s=Pe(this.cacheKey))||void 0===s?void 0:s.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));Me(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bc extends Ws{async getRequest(e,t){const n=On(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 Lc extends to{constructor(e,t){const n=C.default(e),r=["message","collection",n];super(new Bc(e),n,r,t),this.query=e,this.queryStreamController=new Nc(this.query,this.cacheKey,this.notifyChange.bind(this),_n,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ts,action:"onCreate"},{fn:ns,action:"onCreate"},{fn:yc,action:"onDelete"},{fn:gc,action:"onUpdate"},{fn:Pc,action:"onFlagged"},{fn:Mc,action:"onUnflagged"},{fn:jc,action:"onFlagCleared"},{fn:Uc,action:"onReactionAdded"},{fn:xc,action:"onReactionRemoved"},{fn:gi(_s,"contentId","message"),action:"onUpdate"},{fn:gi(ks,"contentId","message"),action:"onUpdate"},{fn:gi(qc,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>(e=>{var t,n;const r=null===(t=Pe(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const a=Re(["message","get"]);return null===(n=null==a?void 0:a.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>ti.message(e))))&&void 0!==a?a:[]);(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 this.query.includeDeleted||(t=De(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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)}}var Fc=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ee();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Ee();if(!r.cache)return;_c=e.referenceId||Sc();const a=Object.assign({messageId:_c,uniqueId:_c},e);r.log("message/createMessage.optimistically",a);const s=Pe(["subChannel","get",e.subChannelId]);if(s&&(Ue(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},s.data),{messageCount:s.data.messageCount+1})),s.data.channelId===s.data.subChannelId)){const e=Pe(["channel","get",s.data.channelId]);(null==e?void 0:e.data)&&Ue(["channel","get",s.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:Xe()._id,channelSegment:(null!==(n=null==s?void 0:s.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},a);return Me(["message","get",i.messageId],i,{cachedAt:-5}),ot("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||_c||Sc();_c=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},kn(e)),{referenceId:r})),a=await _n(n),{messages:s}=a,o=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:o}),ot("local.message.created",{messages:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})]}),{data:ti.message(s[0]),cachedAt:o}}catch(e){throw ot("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:kc,editMessage:Oc,deleteMessage:Tc,softDeleteMessage:Ec,markAsDelivered:async(e,t)=>{const n=Ee();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=r,i=Zt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Gt(Object.assign({userMarkers:a,userEntityMarkers:nn(s),userFeedMarkers:rn(o)},i),{cachedAt:c}),!0},getReadUsers:Ac,getDeliveredUsers:Rc,flagMessage:async(t,n)=>{const r=Ee();r.log("message/flag",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:a?n:e.ContentFlagReasonEnum.Others,detail:a?"":n},{data:o}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,s);if(r.cache){const e=await _n(o);Gt(e)}return ot("message.flagged",o),!!o},unflagMessage:async e=>{const t=Ee();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await _n(n);Gt(e)}return ot("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ee();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:ts,onMessageCreatedLocal:ns,onMessageUpdated:gc,onMessageDeleted:yc,onMessageFlagged:Pc,onMessageUnflagged:Mc,onMessageFlagCleared:jc,onMessageReactionAdded:Uc,onMessageReactionRemoved:xc,onMessageFetched:Dc,getMessage:(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ti.message(e.data):n}))}),"messageId",Ri,[Dc,gc,yc,Pc,Mc,jc,Uc,xc,gi(_s,"contentId","message"),gi(ks,"contentId","message"),gi(qc,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const o=new Lc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:In,prepareMessagePayload:_n,convertParams:kn,convertQueryParams:On});const Kc=e=>{const t=Ee();return st(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class $c extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Zt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Zt(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:o}=a,i=Zt(a,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:yn(o),options:c})});return l}}class Qc extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(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=Pe(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])]),Me(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class zc extends to{constructor(e,t){const n=C.default(e),r=["subChannel","collection",n];super(new $c(e),n,r,t),this.query=e,this.queryStreamController=new Qc(this.query,this.cacheKey,this.notifyChange.bind(this),Rn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Ic,action:"onCreate"},{fn:rs,action:"onCreate"},{fn:as,action:"onDelete"},{fn:e=>vc((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ee();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=cn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Mn(t.updatedAt)>Mn(e.subChannelUpdatedAt)&&Me(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:gi((e=>ts((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Un(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi((e=>ns((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Un(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Is((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Pe(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:gi(Cs,"feedId","subChannel"),action:"onUpdate"},{fn:gi((e=>gc((async t=>{var n;const r=Ee();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&(xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi((e=>yc((async t=>{const n=Ee(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await Pn(t.subChannelId):await xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi(Kc,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ln))&&void 0!==a?a:[]);(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=De(e,"isDeleted",!1)),t.sort(Ye),t}isRelatedCollection(e){var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const Vc={},Hc=async e=>{const t=await(async e=>{const t=Pn.locally(e);if(t)return t.data.channelId;const{data:n}=await Pn(e);return n.channelId})(e),n=ft({channelId:t,subChannelId:e});Vc[e]=Ct(n)};var Jc=Object.freeze({__proto__:null,getSubChannelByIds:Xr,createSubChannel:async e=>{const t=Ee();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Rn(n.data),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),ot("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:a}},updateSubChannel:async(e,t)=>{const n=Ee();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),a=await Rn(r.data),s=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:s}),ot("message-feed.updated",r.data),{data:a.messageFeeds[0],cachedAt:s}},deleteSubChannel:Cc,hardDeleteSubChannel:async e=>{Ee().log("channel/hardDeleteSubChannel",e);return await Cc(e,!0)},softDeleteSubChannel:async e=>{Ee().log("channel/softDeleteSubChannel",e);return await Cc(e,!1)},onSubChannelCreated:rs,onSubChannelUpdated:vc,onSubChannelDeleted:as,getSubChannel:(e,t)=>{const n=Ee();let r;return lo(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:ln(e.data)}),a=Zt(n,["origin"]);return Zn(r,a)?void 0:(r=a,t(n))}),"subChannelId",Pn,[Ic,t=>vc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Nn(r),r.subChannelId===e&&t(r))})),as,gi(Cs,"feedId","subChannel"),t=>Is((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const a=null===(r=Pe(["subChannel","get",e]))||void 0===r?void 0:r.data;a&&t(a)})),gi((t=>ts((async n=>{n.subChannelId===e&&(await Un(n),t(n))}))),"subChannelId","subChannel"),gi((t=>ns((async n=>{n.subChannelId===e&&(await Un(n),t(n))}))),"subChannelId","subChannel"),gi((t=>gc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(xn(r),t(r))}))),"subChannelId","subChannel"),gi((t=>yc((async r=>{const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&r.subChannelId===e&&("message-preview-include-deleted"===a&&await xn(r),"message-preview-not-include-deleted"===a&&await Pn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),gi(Kc,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),a||console.log(V);const o=new zc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:Zr,startMessageReceiptSync:async e=>(await Hc(e),!0),stopMessageReceiptSync:e=>(Vc[e]&&Vc[e](),!0)});const Wc=e=>{const t=Ee();return st(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},Gc=e=>{const t=Ee();return st(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Yc extends Ws{async getRequest(e,t){const{limit:n=Q,displayName:r,membership:a}=e,s=Zt(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:r,filter:a,options:o})});return i}}class Zc extends eo{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Xc extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channels.map(be("channel"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(be("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Zc)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(be("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const el=e=>{const t=Ee();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Da().resolve(e.channelId,"userMessageFeedMarker")}},tl=e=>{const t=Ee();return st(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class nl extends to{constructor(e,t){const n=C.default(e),r=["channel","collection",n],a=nl.getPaginationController(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Xc(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ee();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await zn(e)}catch(e){console.error("Error while preparing unread count info",e)}return $n(e)}),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=null!==(a=s.data.map((e=>Pe(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Fr))&&void 0!==a?a:[];this.paginationController instanceof Yc&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Yc?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof Yc&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ee();let n=e;switch(n=De(n,"isDeleted",this.query.isDeleted),n=qe(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=Be(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ve);break;case"lastCreated":n=n.sort(Je);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Qe);break;default:n=n.sort(Ye)}return n}shouldAbort(e){var t,n;const r=null===(t=Pe(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 Ee().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Zc(e):new Yc(e)}getSubscriptions(){const e=[{fn:gi((e=>ts((t=>{var n,r;const a=Da();(null===(n=Pe(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||a.resolve(t.subChannelId,"userMessageFeedMarker");const s=null===(r=Pe(["channel","get",t.channelId]))||void 0===r?void 0:r.data;s?(bc(s,{lastActivity:t.createdAt}),e(t)):a.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>ns((t=>{var n;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bc(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:lr,action:"onDelete"},{fn:ar,action:"onUpdate"},{fn:vr,action:"onMute"},{fn:e=>hr((t=>{el(t),e(t)})),action:"onJoin"},{fn:e=>mr(((t,n)=>{var r,a;const{userId:s}=Ee();if("member"===this.query.membership&&s===n.userId){const e=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;Me(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(a=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==a?a:[]}))}return e(t)})),action:"onLeft"},{fn:Cr,action:"onMemberAdded"},{fn:_r,action:"onMemberRemoved"},{fn:gi(ws,"entityId","channel"),action:"onUpdate"},{fn:gi(wc,"entityId","channel"),action:"onUpdate"},{fn:gi((e=>ts((async t=>{var n;if("no-message-preview"===await nl.getMessagePreviewSetting())return;if(Dn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>ns((async t=>{var n;if("no-message-preview"===await nl.getMessagePreviewSetting())return;if(Dn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Pe(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>gc((async t=>{"no-message-preview"!==await nl.getMessagePreviewSetting()&&(qn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>yc((async t=>{const n=await nl.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await qn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await mo(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>as((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=an(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await mo(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>vc((async t=>{var n;if("no-message-preview"===await nl.getMessagePreviewSetting())return;(null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data)&&(await Nn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi(rs,"channelId","channel"),action:"onUpdate"},{fn:tl,action:"onResolveChannel"},{fn:e=>(e=>{const t=Ee();return st(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Pe(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:gi(Wc,"channelId","channel"),action:"onUpdate"},{fn:gi((e=>Gc((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Ws?[...e,{fn:e=>tr((t=>{el(t),e(t)})),action:"onCreate"}]:e}}const rl=()=>{var e;const t=Ee();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Re(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class al extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(a.channelId)}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class sl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>be("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>be("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=be("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==a)):r.data.includes(a)||(r.data=[a,...r.data]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ol extends to{constructor(e,t){const n=C.default(e),r=["channelUsers","collection",n];super(new al(e),n,r,t),this.query=e,this.queryStreamController=new sl(this.query,this.cacheKey,this.notifyChange.bind(this),$n),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:hr,action:"onJoin"},{fn:mr,action:"onLeft"},{fn:Cr,action:"onMemberAdded"},{fn:_r,action:"onMemberRemoved"},{fn:Tr,action:"onChannelMemberBanned"},{fn:Rr,action:"onChannelMemberUnbanned"},{fn:jr,action:"onChannelMemberRoleAdded"},{fn:Dr,action:"onChannelMemberRoleRemoved"},{fn:Br,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{var r,a;const s=ua(n);if(0===s.users.length)return;const o=s.users[0];Gt(s);const i=be("channelUsers")({channelId:e,userId:o.userId}),c=null===(r=Pe(["channelUsers","get",i]))||void 0===r?void 0:r.data;Ue(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ti.channelMember))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?Je:Ve),t}}const il=(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new ol(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var cl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ee();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=>ot("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await $n(r);n.cache&&Gt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ee();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=>ot("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await $n(r);n.cache&&Gt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Ne(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Je:Ve),n},getMembers:il,searchMembers:(e,t,n)=>il(e,t)});var ll=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Ee();r.log("channel/addRole",e,t,n);const{data:a}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await $n(a);r.cache&&Gt(s),ot("local.channel-moderator.role-added",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Ee();r.log("channel/removeRole",e,t,n);const{data:a}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await $n(a);r.cache&&Gt(s),ot("local.channel-moderator.role-removed",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ee();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),a=await $n(r),{channelUsers:s}=a,o=n.cache&&Date.now();return n.cache&&Gt(a,{cachedAt:o}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ee();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),a=await $n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{channelUsers:o}=a;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{const r=Ee();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:a}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:s}=a;return s},unmuteMembers:async(e,t)=>{const n=Ee();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:a}=r;return a}}),dl=Object.freeze({__proto__:null,Membership:cl,Moderation:ll,getChannelByIds:Kr,createChannel:fo,updateChannel:async(e,t)=>{const n=Ee();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),a=await $n(r),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{channels:o}=a;return{data:Wn(o.find((t=>t.channelId===e))),cachedAt:s}},deleteChannel:async e=>{const t=Ee();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await mo(e);return Wn(n.data)},joinChannel:async e=>{const t=Ee();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await $n(n);t.cache&&Gt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ee();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await $n(n);t.cache&&Gt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ee();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Ie("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:a}=r;return a},unmuteChannel:async e=>{const t=Ee();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},onChannelCreated:tr,onChannelUpdated:ar,onChannelDeleted:lr,onChannelJoined:hr,onChannelLeft:mr,onChannelSetMuted:vr,onChannelMemberAdded:Cr,onChannelMemberRemoved:_r,onChannelMemberBanned:Tr,onChannelMemberUnbanned:Rr,onChannelMemberRoleAdded:jr,onChannelMemberRoleRemoved:Dr,getChannel:(e,t)=>{const n=Ee();let r;return lo(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Fr(e.data)}),a=Zt(n,["origin"]);return Zn(r,a)?void 0:(r=a,t(n))}),"channelId",mo,[ar,lr,hr,mr,Cr,_r,Tr,Rr,vr,gi(ws,"entityId","channel"),gi(wc,"entityId","channel"),gi((t=>ts((async r=>{await(async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dn(r),r.channelId!==e)return;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;s&&(bc(s,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),gi((t=>ns((async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dn(r),r.channelId!==e)return;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;s&&(bc(s,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),gi((t=>gc((async r=>{var a;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await qn(r),t(r))}))),"channelId","channel"),gi((t=>yc((async r=>{var a;const s=null===(a=Pe(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(xe(["messagePreviewChannel","get",e]),await mo(r.channelId)):await qn(r),t(r))}))),"channelId","channel"),gi((e=>as((async t=>{var r,a;const{channelId:s,subChannelId:o}=t,i=null===(r=Pe(["messagePreviewChannel","get",s]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await mo(s);(null===(a=Pe(["channel","get",s]))||void 0===a?void 0:a.data)&&e(t)}))),"channelId","channel"),gi((t=>vc((async r=>{var a,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Nn(r);const o=null===(a=Pe(["messagePreviewChannel","get",e]))||void 0===a?void 0:a.data;if(!o||o.subChannelId!==r.subChannelId)return;(null===(s=Pe(["channel","get",e]))||void 0===s?void 0:s.data)&&t(r)}))),"channelId","channel"),gi(rs,"channelId","channel"),gi(Wc,"channelId","channel"),gi((e=>Gc((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getChannels(tmpid: ${o}) > listen`);const i=new nl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Xe();if(!t)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ee();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Ts(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(Gc((e=>{const{data:t}=rl();Zn(s,t)||i({loading:!1,data:t})}))),(()=>{const e=fe((async()=>rl()));ge(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===J?(i({data:t,origin:r,loading:!1,error:new Se(H,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e()))}))})(),()=>{a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Bn,isUnreadCountSupport:Ln,convertFromRaw:Fn,preUpdateChannelCache:Kn,prepareChannelPayload:$n});const ul=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Me(["communityUsers","collection",e],n)}))},hl=async(e,t)=>{const n=Ee();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:a}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),s=Ro(a),o=n.cache&&Date.now();return n.cache&&(Gt(s,{cachedAt:o}),ul(s.communities,s.communityUsers)),{data:s.communities.map((e=>ti.community(e))),cachedAt:o}};hl.locally=e=>{var t;const n=Ee();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Pe(["community","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a,cachedAt:s.cachedAt}};const pl=async e=>{const t=Ee();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Ro(n),a=t.cache&&Date.now();t.cache&&(Gt(r,{cachedAt:a}),ul(r.communities,r.communityUsers));const{communities:s}=r;return{data:s.find((t=>t.communityId===e)),cachedAt:a}};pl.locally=e=>{const t=Ee();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Pe(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const fl=(e,t)=>{const n=Ee();return st(n,e,e,(e=>{const r=Ro(e);if(n.cache){Gt(r);const e=Pe(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},ml=e=>fl("community.created",e),gl=e=>fl("community.updated",e),yl=e=>fl("community.deleted",e);class vl extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=Zt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:yn(a.includeDeleted),keyword:a.displayName,filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class bl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var wl,Cl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(wl||(wl={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(Cl||(Cl={}));class Il extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class Sl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=be("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function _l(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function kl(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!_l(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!_l(e,t,"ADD_COMMUNITY_USER")))}const Ol=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{const a=Ro(r),{communities:s,communityUsers:o}=a,i=To(s,o);if(a.communities=i,n.cache){Gt(a,void 0,!1);const n=Pe(["community","get",a.communities[0].communityId]),r=kl(e,a).map((e=>{const t=Pe(["communityUsers","get",be("communityUsers")(e)]);return null==t?void 0:t.data})).filter(no);t(n.data,r)}else t(a.communities[0],kl(e,a))}))},Tl=(e,t)=>{const n=Ee();return st(n,e,e,(r=>{const a=Ro(r),{communities:s,communityUsers:o}=a,i=To(s,o);if(a.communities=i,n.cache){Gt(a,void 0,!1);const n=Pe(["community","get",a.communities[0].communityId]),r=kl(e,a).map((e=>{const t=Pe(["communityUsers","get",be("communityUsers")(e)]);return null==t?void 0:t.data})).filter(no);t(n.data,r)}else t(a.communities[0],kl(e,a))}))},El=e=>Ol("community.userBanned",e),Al=e=>Ol("community.userChanged",e),Rl=e=>Ol("community.userUnbanned",e),Pl=e=>Ol("community.roleAdded",e),Ml=e=>Ol("community.roleRemoved",e),jl=e=>Tl("local.community.userAdded",e),Ul=e=>Tl("local.community.userRemoved",e),xl=e=>Ol("community.joined",e),Dl=e=>Ol("community.left",e),ql=e=>Tl("local.community.joined",e),Nl=e=>Tl("local.community.left",e),Bl=e=>{const t=Ee(),n=[st(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Ll=e=>{const t=Ee();return st(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Fl=e=>{const t=Ee();return st(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Kl=e=>t=>{const n=Ee();return st(n,"user.deleted","user.deleted",(n=>{var r,a;const s=ua(n);if(0===s.users.length)return;const o=s.users[0];Gt(s);const i=be("communityUsers")({communityId:e,userId:o.userId}),c=null===(r=Pe(["communityUsers","get",i]))||void 0===r?void 0:r.data;Me(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Pe(["community","get",e]))||void 0===a?void 0:a.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class $l extends to{constructor(e,t){const n=C.default(e),r=["communityUsers","collection",n];super(new Il(e),n,r,t),this.query=e,this.queryStreamController=new Sl(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:xl,action:Cl.OnCommunityJoined},{fn:ql,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Nl,action:Cl.OnCommunityLeft},{fn:El,action:Cl.OnCommunityUserBanned},{fn:Al,action:Cl.OnCommunityUserChanged},{fn:Pl,action:Cl.OnCommunityUserRoleAdded},{fn:Ml,action:Cl.OnCommunityUserRoleRemoved},{fn:Fl,action:Cl.OnCommunityUserRoleAdded},{fn:Ll,action:Cl.OnCommunityUserRoleRemoved},{fn:Rl,action:Cl.OnCommunityUserUnbanned},{fn:jl,action:Cl.OnCommunityUserAdded},{fn:Ul,action:Cl.onCommunityUserRemoved},{fn:Kl(this.query.communityId),action:Cl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["communityUsers","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(Ve);else t=t.sort(Je);return t}}class Ql extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class zl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>be("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=be("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Vl;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Vl||(Vl={}));class Hl extends to{constructor(e,t){const n=C.default(e),r=["communityUsers","collection",n];super(new Ql(e),n,r,t),this.query=e,this.queryStreamController=new zl(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:xl,action:Vl.OnCommunityJoined},{fn:ql,action:Vl.OnCommunityJoined},{fn:Dl,action:Vl.OnCommunityLeft},{fn:Nl,action:Vl.OnCommunityLeft},{fn:El,action:Vl.OnCommunityUserBanned},{fn:Al,action:Vl.OnCommunityUserChanged},{fn:Ll,action:Vl.OnCommunityUserRoleRemoved},{fn:Ml,action:Vl.OnCommunityUserRoleRemoved},{fn:Rl,action:Vl.OnCommunityUserUnbanned},{fn:Kl(this.query.communityId),action:Vl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["communityUsers","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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=Ne(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=$e(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var Jl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ee();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ot("local.community.userAdded",r);const a=en(r,"communityUsers");n.cache&&Gt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ee();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ot("local.community.userRemoved",r);const a=en(r,"communityUsers");n.cache&&Gt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Ne(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Je:Ve),n},getMembers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new $l(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new Hl(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>Ol("community.userAdded",e),onCommunityUserRemoved:e=>Ol("community.userRemoved",e),onCommunityUserBanned:El,onCommunityUserChanged:Al,onCommunityUserUnbanned:Rl,onCommunityUserRoleAdded:Pl,onCommunityUserRoleRemoved:Ml,onLocalCommunityUserAdded:jl,onLocalCommunityUserRemoved:Ul,onCommunityJoined:xl,onCommunityLeft:Dl,onLocalCommunityJoined:ql,onLocalCommunityLeft:Nl,onLocalCommunityJoin:Bl});class Wl extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new vl(e),n,r,t),this.query=e,this.queryStreamController=new bl(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:yl,action:wl.OnCommunityDeleted},{fn:gl,action:wl.OnCommunityUpdated},{fn:xl,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Al,action:Cl.OnMemberCountChanged},{fn:ql,action:Cl.OnCommunityJoined},{fn:Nl,action:Cl.OnCommunityLeft},{fn:gi(Bl,"targetId","community"),action:wl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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}=Ee();let n=e;return this.query.includeDeleted||(n=De(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=Fe(n,this.query.membership,t)),n}}class Gl extends Ws{async getRequest(e,t){var n;const{limit:r=Q}=e,a=Zt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:yn(a.includeDeleted),filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class Yl extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),ul(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Zl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Zl||(Zl={}));class Xl extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new Gl(e),n,r,t),this.query=e,this.queryStreamController=new Yl(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:ml,action:Zl.OnCommunityCreated},{fn:yl,action:Zl.OnCommunityDeleted},{fn:gl,action:Zl.OnCommunityUpdated},{fn:xl,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Al,action:Cl.OnMemberCountChanged},{fn:ql,action:Cl.OnCommunityJoined},{fn:Nl,action:Cl.OnCommunityLeft},{fn:gi(Bl,"targetId","community"),action:Zl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>ei(e))))&&void 0!==a?a:[];(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}=Ee();let n=e;this.query.includeDeleted||(n=De(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=Fe(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return n=n.sort(r),n}}class ed extends Ws{async getRequest(e,t){const{limit:n=Q,includeDiscoverablePrivateCommunity:r}=e,a=Zt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class td extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),ul(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var nd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(nd||(nd={}));class rd extends to{constructor(e,t){const n=C.default(e),r=["trendingCommunity","collection",n];super(new ed(e),n,r,t),this.query=e,this.queryStreamController=new td(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:yl,action:nd.OnCommunityDeleted},{fn:gl,action:nd.OnCommunityUpdated},{fn:xl,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Al,action:Cl.OnMemberCountChanged},{fn:ql,action:Cl.OnCommunityJoined},{fn:Nl,action:Cl.OnCommunityLeft},{fn:gi(Bl,"targetId","community"),action:nd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>ei(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class ad extends Ws{async getRequest(e,t){const{limit:n=Q,includeDiscoverablePrivateCommunity:r}=e,a=Zt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class sd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&(Gt(t,{cachedAt:r}),ul(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(be("community"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(be("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var od;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(od||(od={}));class id extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new ad(e),n,r,t),this.query=e,this.queryStreamController=new sd(this.query,this.cacheKey,this.notifyChange.bind(this),Ro),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:yl,action:od.OnCommunityDeleted},{fn:gl,action:od.OnCommunityUpdated},{fn:xl,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Al,action:Cl.OnMemberCountChanged},{fn:ql,action:Cl.OnCommunityJoined},{fn:Nl,action:Cl.OnCommunityLeft},{fn:gi(Bl,"targetId","community"),action:od.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Pe(["community","get",e]))).filter(no).map((({data:e})=>ei(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class cd extends Ws{async getRequest(e,t){var n;const{limit:r=Q,communityMembershipStatus:a}=e,s=Zt(e,["limit","communityMembershipStatus"]),o={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:r}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=a?a:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function ld(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class dd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:ld(e)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ld(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Pe(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ud;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(ud||(ud={}));class hd extends to{constructor(e,t){const n=C.default(e),r=["community","collection",n];super(new cd(e),n,r,t),this.query=e,this.queryStreamController=new dd(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:ml,action:ud.OnCommunityCreated},{fn:yl,action:ud.OnCommunityDeleted},{fn:gl,action:ud.OnCommunityUpdated},{fn:xl,action:Cl.OnCommunityJoined},{fn:Dl,action:Cl.OnCommunityLeft},{fn:Al,action:Cl.OnMemberCountChanged},{fn:ql,action:Cl.OnCommunityJoined},{fn:Nl,action:Cl.OnCommunityLeft},{fn:gi(Bl,"targetId","community"),action:ud.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Pe(["community","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]);(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}=Ee();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=Fe(n,this.query.communityMembershipStatus,t)),n}}class pd extends Ws{async getRequest(e,t){const{limit:n=Q,communityIds:r}=e,a=Zt(e,["limit","communityIds"]),s=t?{token:t}:{limit:n},o=r.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},a),{options:s,communityIds:o})});return i}}var fd;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(fd||(fd={}));class md extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>be("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===fd.OnLocalJoinRequestUpdated){if(!r.data.find((e=>a.includes(e))))return}e===fd.OnLocalJoinRequestCreated&&(r.data=[...new Set([...a,...r.data])]),e===fd.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!a.includes(e)))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gd extends to{constructor(e,t){const n=C.default(e),r=["joinRequestList","collection",n];super(new pd(e),n,r,t),this.query=e,this.queryStreamController=new md(this.query,this.cacheKey,this.notifyChange.bind(this),Po),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bo,action:fd.OnLocalJoinRequestCreated},{fn:Lo,action:fd.OnLocalJoinRequestUpdated},{fn:Fo,action:fd.OnLocalJoinRequestUpdated},{fn:Bl,action:fd.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Pe(["joinRequest","get",e]))).filter(no).map((({data:e})=>e)).map(xo));(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;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}var yd;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(yd||(yd={}));var vd=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Ee();r.log("community/moderation/addRoles",e,t,n);const{data:a}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=Mo(a);r.cache&&Gt(s),ot("local.community.roleAdded",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Ee();r.log("community/moderation/removeRoles",e,t,n);const{data:a}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=Mo(a);r.cache&&Gt(s),ot("local.community.roleRemoved",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ee();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Ee();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}}}),bd=Object.freeze({__proto__:null,Moderation:vd,Membership:Jl,getCommunityByIds:hl,createCommunity:async e=>{const t=Ee();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",jo(e));ot("community.created",n);const r=Ro(n),a=t.cache&&Date.now();t.cache&&(Gt(r,{cachedAt:a}),ul(r.communities,r.communityUsers));const{communities:s}=r;return{data:ti.community(s[0]),cachedAt:a}},updateCommunity:async(e,t)=>{const n=Ee();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,jo(t));ot("community.updated",r);const a=Ro(r),s=n.cache&&Date.now();n.cache&&(Gt(a,{cachedAt:s}),ul(a.communities,a.communityUsers));const{communities:o}=a;return{data:ti.community(o.find((t=>t.communityId===e))),cachedAt:s}},deleteCommunity:async e=>{const t=Ee();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await pl(e);return ot("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),ti.community(n.data)},joinCommunity:async e=>{const t=Ee();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ot("local.community.joined",n);const r=Ro(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ee();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ot("local.community.left",n);const r=Ro(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:ml,onCommunityUpdated:gl,onCommunityDeleted:yl,searchCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`searchCommunities(tmpid: ${s}) > listen`);const o=new Wl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCommunities(tmpid: ${s}) > listen`);const o=new Xl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>lo(e,t,"communityId",pl,[gl,yl,xl,Dl,ql,Nl,El,Rl,Al,gi(Bl,"targetId","community")],{callbackDataSelector:e=>e?ti.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new rd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>xe(l))),()=>{r(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new id(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>xe(l))),()=>{r(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`semanticSearchCommunities(tmpid: ${s}) > listen`);const o=new hd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`semanticSearchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getJoinRequestList: (tmpid: ${s}) > listen`);const o=new gd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getJoinRequestList (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return yd}});const wd=async e=>{const t=Ee();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&&Gt(n,{cachedAt:r});const{categories:a}=n;return{data:ti.category(a.find((t=>t.categoryId===e))),cachedAt:r}};wd.locally=e=>{const t=Ee();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Pe(["category","get",e]);return n?{data:ti.category(n.data),cachedAt:n.cachedAt}:void 0};const Cd=async e=>{const t=Ee();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:a,includeDeleted:s}=n,o=Zt(n,["page","limit","includeDeleted"]),i=r?{token:r}:a?{limit:a}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:yn(s),options:i})}),{paging:l}=c,d=Zt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Gt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:s,options:i})];Me(e,{categories:null==u?void 0:u.map(be("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};Cd.locally=e=>{var t,n;const r=Ee();if(r.log("category/queryCategories.locally",e),!r.cache)return;const a=null!=e?e:{},{page:s,limit:o=10}=a,i=Zt(a,["page","limit"]),c=s?{token:s}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Pe(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Pe(["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 Id=Object.freeze({__proto__:null,getCategory:wd,getCategories:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:o}=e,i=Zt(e,["limit"]),c=null!=o?o:Q,{policy:l=z}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,a;const s=null===(r=Pe(u))||void 0===r?void 0:r.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];if(!n&&o.length>0&&!(null==s?void 0:s.params.page))return;const d=fe(Cd,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));ge(d,(({data:n,error:r,loading:a,paging:s})=>{const i={loading:a,error:r,params:{page:null==s?void 0:s.next},data:o};n&&(i.data=[...new Set([...o,...n.map(be("category"))])]),Me(u,i),(n=>{var r,a;let s=null!==(r=n.data.map((e=>Pe(["category","get",e]))).filter(Boolean).map((({data:e})=>ti.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(s=De(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(Ve);break;case"lastCreated":s=s.sort(Je);break;default:s=s.sort(ze)}t({onNextPage:h,data:s,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})})(i)}),me(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Sd=async e=>{const t=Ee();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:a}=n,s=Zt(n,["queryToken","dataTypes"]),o=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})}),{paging:c}=i,l=Zt(i,["paging"]),d=en(l,"communityUsers"),{posts:u}=d,{communities:h}=Ro(d),p=t.cache&&Date.now();if(t.cache){Gt(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:o})];Me(e,{posts:u.map(be("post")),paging:c})}return{data:u.map(ti.post),cachedAt:p,paging:c}};Sd.locally=e=>{var t,n;const r=Ee();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const a=Zt(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=Pe(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Pe(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ti.post),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};class _d extends Ws{async getRequest(e,t){const{limit:n}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:a})});return s}}var kd;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(kd||(kd={}));class Od extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===kd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===kd.OnPostCreated||e===kd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===kd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Td=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("comment",e)})),t}const a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.comments.map((e=>ti.comment(e))),cachedAt:a}};Td.locally=e=>{var t;const n=Ee();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Pe(["comment","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a.map((e=>ti.comment(e))),cachedAt:s.cachedAt}};const Ed=(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})},Ad=async e=>{const t=Ee();t.log("story/getStoryByStoryId",e);const n=Pe(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;pn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Ed(n.data)}catch(t){throw ne(null==t?void 0:t.code)&&Yt("story",e),t}const a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:r.stories[0],cachedAt:a}};Ad.locally=e=>{const t=Ee();t.log("story/getStorybyStoryId",e);const n=Pe(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;pn("story",e)}const r=t.cache&&Date.now(),a=Pe(["story","get",e]);if(a)return{data:a.data,cachedAt:r}};const Rd=async(e,t=!1)=>{var n;const r=Ee(),a=await Mi(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});if(t?rt((()=>Yt("comment",e))):Ue(["comment","get",e],{isDeleted:!0}),"story"===a.data.referenceType){const e=await Ad(a.data.referenceId);ot("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Pe(["post","get",a.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=s.parentId?1:s.childrenNumber+1,e.commentsCount-=t,ot("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return ot("local.comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),s},Pd=async e=>{const t=Ee();let n;t.log("comment/getComment",e),pn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{comments:a}=n;return{data:a.find((t=>t.commentId===e)),cachedAt:r}};Pd.locally=e=>{const t=Ee();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Pe(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Md=e=>tc("local.comment.deleted",e),jd=e=>{const t=Ee();return st(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(Ue(["comment","get",n.commentId],n),e(bo(n))):e(n)}))},Ud=e=>{const t=Ee();return st(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(Ue(["comment","get",n.commentId],n),e(bo(n))):e(n)}))};class xd extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r}=e,a=Zt(e,["limit","includeDeleted"]),s={type:a.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},a),{isDeleted:yn(r),options:o})});return i}}var Dd;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(Dd||(Dd={}));class qd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.comments.map(be("comment"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(be("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===Dd.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Nd=e=>tc("local.comment.created",e);class Bd extends to{constructor(e,t){const n=C.default(e),r=["comments","collection",n];super(new xd(e),n,r,t),this.query=e,this.queryStreamController=new qd(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Nd,action:Dd.OnCommentCreated},{fn:Md,action:Dd.OnCommentDeleted},{fn:nc,action:Dd.OnCommentCreated},{fn:rc,action:Dd.OnCommentUpdated},{fn:ac,action:Dd.OnCommentDeleted},{fn:sc,action:Dd.OnCommentFlagged},{fn:oc,action:Dd.OnCommentUnflagged},{fn:ic,action:Dd.OnCommentReactionAdded},{fn:cc,action:Dd.OnCommentReactionRemoved},{fn:jd,action:Dd.OnCommentReactionAdded},{fn:Ud,action:Dd.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["comment","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.comment);(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;if(this.query.includeDeleted||(t=De(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],a=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return a.length===r.length&&r.every(((e,t)=>e===a[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(Ve);else t=t.sort(Je);return t}}var Ld=Object.freeze({__proto__:null,getCommentByIds:Td,createComment:async e=>{var t;const n=Ee();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:a}=r;if(0===a.length)throw new Error("Comment not created");const s=n.cache&&Date.now();if(n.cache&&Gt(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const n=null===(t=Pe(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,ot("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Pe(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Pe(["story","get",t.data]);(null==e?void 0:e.data)&&ot("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,a[0].commentId])]})],categories:[],comments:a,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return ot("local.comment.created",r),{data:ti.comment(a[0]),cachedAt:s}},updateComment:async(e,t)=>{const n=Ee();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a}),ot("comment.updated",r);const{comments:s}=r;return{data:ti.comment(s.find((t=>t.commentId===e))),cachedAt:a}},deleteComment:Rd,softDeleteComment:async e=>{Ee().log("comment/softDeleteComment",e);return Rd(e)},hardDeleteComment:async e=>{Ee().log("comment/hardDeleteComment",e);return Rd(e,!0)},flagComment:async(t,n)=>{const r=Ee();r.log("comment/flagComment",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,s);return r.cache&&Gt(o),ot("comment.flagged",o),!!o},unflagComment:async e=>{const t=Ee();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Gt(n),ot("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ee();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:nc,onCommentUpdated:rc,onCommentDeleted:ac,onCommentFlagged:sc,onCommentUnflagged:oc,onCommentReactionAdded:ic,onCommentReactionRemoved:cc,getComment:(e,t)=>lo(e,t,"commentId",Pd,[Md,ac,sc,ic,cc,oc,rc,jd,Ud]),getComments:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const o=new Bd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Fd=async e=>{const t=Ee();let n;t.log("post/getPost",e),pn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ne(null==t?void 0:t.code)&&Yt("post",e),t}const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};Fd.locally=e=>{const t=Ee();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Pe(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kd=e=>Qi("local.post.deleted",e),$d=e=>{const t=Ee();return st(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(Ue(["post","get",n.postId],n),e(n)):e(n)}))},Qd=e=>{const t=Ee();return st(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(Ue(["post","get",n.postId],n),e(n)):e(n)}))},zd=e=>Qi("local.post.updated",e),Vd=e=>[nc,ac,ic,cc,Nd,Md,jd,Ud].map((t=>({fn:gi((n=>((e,t,n)=>t((async t=>{var r;const a=null===(r=Pe(n))||void 0===r?void 0:r.data;a&&a.data.includes(t.referenceId)&&(await Fd(t.referenceId),e(t))})))(n,t,e)),"referenceId","post"),action:kd.OnPostUpdated}))),Hd=e=>[{fn:zi,action:kd.OnPostCreated},{fn:Vi,action:kd.OnPostUpdated},{fn:zd,action:kd.OnPostUpdated},{fn:Hi,action:kd.OnPostDeleted},{fn:Gi,action:kd.OnPostFlagged},{fn:Yi,action:kd.OnPostUnflagged},{fn:Ji,action:kd.OnPostApproved},{fn:Wi,action:kd.OnPostDeclined},{fn:Zi,action:kd.OnPostReactionAdded},{fn:Xi,action:kd.OnPostReactionRemoved},{fn:$d,action:kd.OnPostReactionAdded},{fn:Qd,action:kd.OnPostReactionRemoved},{fn:Kd,action:kd.OnPostDeleted},...Vd(e)];class Jd extends to{constructor(e,t){const n=C.default(e),r=["customRankingGlobalFeed","collection",n];super(new _d(e),n,r,t),this.query=e,this.queryStreamController=new Od(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(Hd(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Wd extends Ws{async getRequest(e,t){const{limit:n,dataTypes:r}=e,a=Zt(e,["limit","dataTypes"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:s})});return o}}class Gd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===kd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===kd.OnPostCreated||e===kd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===kd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yd extends to{constructor(e,t){const n=C.default(e),r=["globalFeed","collection",n];super(new Wd(e),n,r,t),this.query=e,this.queryStreamController=new Gd(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(Hd(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Zd extends Ws{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:a,includeDeleted:s,matchingOnlyParentPost:o,limit:i=Q}=e,c=Zt(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit"]),l=t?{token:t}:{limit:i},{data:d}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:l,dataTypes:(null==a?void 0:a.length)?a:void 0,includePostedFeed:r,isDeleted:yn(s),matchingOnlyParentPost:null!=o?o:!(null==a?void 0:a.length)})});return d}}class Xd extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(this.query.dataTypes&&0!==this.query.dataTypes.length||a.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(e===kd.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}if(e===kd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e===kd.OnPostCreated||e===kd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class eu extends to{constructor(e,t){const n=C.default(e),r=["userFeed","collection",n];super(new Zd(e),n,r,t),this.query=e,this.queryStreamController=new Xd(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:zi,action:kd.OnPostCreated},{fn:Vi,action:kd.OnPostUpdated},{fn:zd,action:kd.OnPostUpdated},{fn:Hi,action:kd.OnPostDeleted},{fn:Gi,action:kd.OnPostFlagged},{fn:Yi,action:kd.OnPostUnflagged},{fn:Ji,action:kd.OnPostApproved},{fn:Wi,action:kd.OnPostDeclined},{fn:Zi,action:kd.OnPostReactionAdded},{fn:Xi,action:kd.OnPostReactionRemoved},{fn:$d,action:kd.OnPostReactionAdded},{fn:Qd,action:kd.OnPostReactionRemoved},{fn:Kd,action:kd.OnPostDeleted},{fn:gi((e=>nc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fd(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated},{fn:gi((e=>ac((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fd(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var tu=Object.freeze({__proto__:null,queryGlobalFeed:Sd,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${s}) > listen`);const o=new Jd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getGlobalFeed(tmpid: ${s}) > listen`);const o=new Yd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getUserFeed(tmpid: ${s}) > listen`);const o=new eu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getUserFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const nu=async e=>{const t=Ee();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=>{ne(null==t?void 0:t.code)&&Yt("post",e)})),t}const a=en(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Gt(a,{cachedAt:s}),{data:a.posts.map(ti.post),cachedAt:s}};nu.locally=e=>{var t;const n=Ee();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Pe(["post","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=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:a.map(ti.post),cachedAt:s.cachedAt}};const ru=async(e,t=!1)=>{var n;const r=Ee(),a=await Pi(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===a.data.targetType){const e=await pl(a.data.targetId),t=(null!==(n=Re(["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));ot("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});return t?setTimeout((()=>{Yt("post",e)}),0):Ue(["post","get",e],{isDeleted:!0}),ot("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),ti.post(s)};class au extends Ws{async getRequest(e,t){const{limit:n=Q,includeDeleted:r,matchingOnlyParentPost:a}=e,s=Zt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:o}=s,i={type:s.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},s),{isDeleted:yn(r),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:c})});return l}}class su extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===kd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==kd.OnPostCreated&&e!==kd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ou=({cacheKey:e,resolveId:t})=>[nc,ac,ic,cc,Nd,Md,jd,Ud].map((n=>({fn:gi((r=>((e,t,n,r)=>t((async t=>{var a;const s=null===(a=Pe(n))||void 0===a?void 0:a.data;s&&s.data.includes(r?r(t.referenceId):t.referenceId)&&(await Fd(t.referenceId),e(t))})))(r,n,e,t)),"referenceId","post"),action:kd.OnPostUpdated})));class iu extends to{constructor(e,t){const n=C.default(e),r=["posts","collection",n];super(new au(e),n,r,t),this.query=e,this.queryStreamController=new su(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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((e=this.cacheKey,[{fn:zi,action:kd.OnPostCreated},{fn:Vi,action:kd.OnPostUpdated},{fn:zd,action:kd.OnPostUpdated},{fn:Hi,action:kd.OnPostDeleted},{fn:Gi,action:kd.OnPostFlagged},{fn:Yi,action:kd.OnPostUnflagged},{fn:Ji,action:kd.OnPostApproved},{fn:Wi,action:kd.OnPostDeclined},{fn:Zi,action:kd.OnPostReactionAdded},{fn:Xi,action:kd.OnPostReactionRemoved},{fn:$d,action:kd.OnPostReactionAdded},{fn:Qd,action:kd.OnPostReactionRemoved},{fn:Kd,action:kd.OnPostDeleted},...ou({cacheKey:e})]));var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=De(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Le(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Ke(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ve);else n=n.sort(Je);return n}}class cu extends Ws{async getRequest(e,t){const n=Zt(e,["limit"]),{communityId:r,placement:a}=n,s=a?`/api/v1/pinned-posts/communities/${r}/${a}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(s);return o}}class lu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(Tn):[]});Gt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(be("pin"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(be("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===kd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class du extends to{constructor(e,t){const n=C.default(e),r=["pinnedPosts","collection",n];super(new cu(e),n,r,t),this.query=e,this.queryStreamController=new lu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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(ou({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=(null!==(a=s.data.map((e=>Pe(["pin","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Je({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class uu extends Ws{async getRequest(e,t){Zt(e,["limit"]);const{data:n}=await this.http.get("/api/v1/pinned-posts/global");return n}}class hu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(Tn)});Gt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(be("pin"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(be("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===kd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class pu extends to{constructor(e,t){const n=C.default(e),r=["pinnedPosts","collection",n];super(new uu(e),n,r,t),this.query=e,this.queryStreamController=new hu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:Kd,action:kd.OnPostDeleted},{fn:Hi,action:kd.OnPostDeleted},...ou({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["pin","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class fu extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:s})});return o}}function mu(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function gu(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class yu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:mu(e)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...mu(e)])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===kd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==kd.OnPostCreated&&e!==kd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vu extends to{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=C.default(n),a=["posts","collection",r];super(new fu(n),r,a,t),this.query=n,this.queryStreamController=new yu(this.query,this.cacheKey,this.notifyChange.bind(this),Fi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Vi,action:kd.OnPostUpdated},{fn:Hi,action:kd.OnPostDeleted},{fn:Gi,action:kd.OnPostFlagged},{fn:Yi,action:kd.OnPostUnflagged},{fn:Ji,action:kd.OnPostApproved},{fn:Wi,action:kd.OnPostDeclined},{fn:Zi,action:kd.OnPostReactionAdded},{fn:Xi,action:kd.OnPostReactionRemoved},{fn:gi((e=>nc((async t=>{const n=Pe(this.cacheKey);gu(null==n?void 0:n.data).includes(t.referenceId)||(await Pi(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated},{fn:gi((e=>ac((async t=>{const n=Pe(this.cacheKey);gu(null==n?void 0:n.data).includes(t.referenceId)||(await Pi(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(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.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=Ke(t,this.query.dataTypes)),t}}class bu extends Ws{async getRequest(e,t){const{limit:n=Q,matchingOnlyParentPost:r,hashtags:a,dataTypes:s,targetType:o="all"}=e,i=Zt(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:i.sortBy||e.limit?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},i),{hashtags:a,dataTypes:s,targetType:o,matchingOnlyParentPost:null!=r?r:!(null==s?void 0:s.length),options:l})});return d}}class wu extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(be("post"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(be("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Pe(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}e===kd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==kd.OnPostCreated&&e!==kd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Cu extends to{constructor(e,t){const n=C.default(e),r=["posts","collection",n];super(new bu(e),n,r,t),this.query=e,this.queryStreamController=new wu(this.query,this.cacheKey,this.notifyChange.bind(this),Li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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:zi,action:kd.OnPostCreated},{fn:Vi,action:kd.OnPostUpdated},{fn:zd,action:kd.OnPostUpdated},{fn:Hi,action:kd.OnPostDeleted},{fn:Gi,action:kd.OnPostFlagged},{fn:Yi,action:kd.OnPostUnflagged},{fn:Ji,action:kd.OnPostApproved},{fn:Wi,action:kd.OnPostDeclined},{fn:Zi,action:kd.OnPostReactionAdded},{fn:Xi,action:kd.OnPostReactionRemoved},{fn:$d,action:kd.OnPostReactionAdded},{fn:Qd,action:kd.OnPostReactionRemoved},{fn:Kd,action:kd.OnPostDeleted},{fn:gi((e=>nc((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fd(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated},{fn:gi((e=>ac((async t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fd(t.referenceId),e(t))}))),"referenceId","post"),action:kd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["post","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Ke(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ve);else n=n.sort(Je);return n}}var Iu=Object.freeze({__proto__:null,getPostByIds:nu,createPost:async e=>{const t=Ee();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);ot("post.created",n);const r=Li(n),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:ti.post(s[0]),cachedAt:a}},editPost:async(e,t)=>{const n=Ee();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),a=en(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Gt(a,{cachedAt:s}),ot("local.post.updated",a);const{posts:o}=a;return{data:ti.post(o.find((t=>t.postId===e))),cachedAt:s}},deletePost:ru,softDeletePost:async e=>{Ee().log("post/softDeletePost",e);const t=await ru(e,!1);return ti.post(t)},hardDeletePost:async e=>{Ee().log("post/hardDeletePost",e);const t=await ru(e,!0);return ti.post(t)},approvePost:async e=>{const t=Ee();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ot("post.approved",n),"community"===n.posts[0].targetType&&ot("community.updated",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:ti.post(r.posts.find((t=>t.postId===e))),cachedAt:a}},declinePost:async e=>{const t=Ee();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ot("community.updated",n),ot("post.declined",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Gt(r,{cachedAt:a}),{data:ti.post(n.posts.find((t=>t.postId===e))),cachedAt:a}},flagPost:async(t,n)=>{const r=Ee();r.log("post/flagPost",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,s);return r.cache&&Gt(en(o,"communityUsers")),ot("post.flagged",o),!!o},unflagPost:async e=>{const t=Ee();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Gt(en(n,"communityUsers")),ot("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ee();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Ee();t.log("post/createPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ot("post.created",n);const r=en(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Gt(r,{cachedAt:a});const{posts:s}=r;return{data:ti.post(s[0]),cachedAt:a}},onPostCreated:zi,onPostUpdated:Vi,onPostDeleted:Hi,onPostApproved:Ji,onPostDeclined:Wi,onPostFlagged:Gi,onPostUnflagged:Yi,onPostReactionAdded:Zi,onPostReactionRemoved:Xi,getPost:(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ti.post(e.data):n}))}),"postId",Pi,[Ji,Wi,$d,Qd,t=>Hi((n=>{var r;let a=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Pe(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Me(["post","get",e.postId],e),a=e)}t(a)})),Gi,e=>Zi((t=>{e(t)})),e=>Xi((t=>{e(t)})),Yi,Vi,zd,Kd,gi((t=>nc((async n=>{n.referenceId===e&&(await Pi(e),t(n))}))),"referenceId","post"),gi((t=>ac((async n=>{n.referenceId===e&&(await Pi(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const o=new iu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getPinnedPosts(tmpid: ${s}) > listen`);const o=new du(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Ee(),s=Date.now();r(`getGlobalPinnedPosts(tmpid: ${s}) > listen`);const o=new pu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`semanticSearchPosts(tmpid: ${s}) > listen`);const o=new vu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`searchPostsByHashtag(tmpid: ${s}) > listen`);const o=new Cu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`searchPostsByHashtag(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Su=async e=>{const t=Ee();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}};Su.locally=e=>{const t=Ee();if(t.log("stream/getStream",e),!t.cache)return;const n=Pe(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _u=e=>{const t=Ee();return st(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Gt(t),e(t.videoStreamings[0])}))},ku=e=>{const t=Ee();return st(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Gt(t),e(t.videoStreamings[0])}))},Ou=e=>{const t=Ee();return st(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Gt(t),e(t.videoStreamings[0])}))},Tu=e=>{const t=Ee();return st(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Gt(t),e(t.videoStreamings[0])}))},Eu=e=>{const t=Ee();return st(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Gt(t),e(t.videoStreamings[0])}))},Au=(e,t)=>lo(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?ti.stream(e.data):n}))}),"streamId",Su,[Ou,_u,ku,Tu,Eu,qc]);Au.locally=e=>{const t=Ee();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Pe(["stream","get",e]);return n?{data:ti.stream(n.data),cachedAt:n.cachedAt}:void 0};const Ru=async e=>{const t=Ee();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:a}=n,s=Zt(n,["page","limit"]),o=r?{token:r}:a?{limit:a}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Gt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Pu=Object.freeze({__proto__:null,createStream:async e=>{const t=Ee();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:ti.stream(a[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Ee();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{videoStreamings:s}=r;return{data:ti.stream(s.find((t=>t.streamId===e))),cachedAt:a}},deleteStream:async e=>{const t=Ee();t.log("stream/deleteStream",e);const n=await Su(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Ue(["stream","get",e],s),a},disposeStream:async e=>{const t=Ee();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&&Gt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Ee();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{videoStreamings:s}=r;return{data:ti.stream(s.find((t=>t.streamId===e))),cachedAt:a}},onStreamStarted:_u,onStreamStopped:ku,onStreamRecorded:Ou,onStreamFlagged:Tu,onStreamTerminated:Eu,onStreamViewerBanned:qc,onStreamViewerUnbanned:e=>{const t=Ee();return st(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>Su(e))));const a=null===(n=Pe(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))},getStreamById:Au,getStreams:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getStreams(tmpid: ${s}) > listen`);const{limit:o}=e,i=Zt(e,["limit"]),c=null!=o?o:Q,{policy:l=z}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=De(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Je:Ve),n},p=(e,n=!1)=>{var r,a;const s=null!==(r=e.data.map((e=>Pe(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(s):s,hasNextPage:!!(null===(a=e.params)||void 0===a?void 0:a.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Pe(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Me(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=Pe(u))||void 0===t?void 0:t.data,a=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null==r?void 0:r.params.page))return;const s=fe(Ru,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ge(s,(({data:e,error:t,loading:n,paging:r})=>{const s={loading:n,error:t,params:{page:null==r?void 0:r.next},data:a};e&&(s.data=[...new Set([...a,...e.map(be("stream"))])]),Me(u,s),p(s)}),me(l))};return d.push(Ou(f()),_u(f()),ku(f())),m(!0),()=>{r(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Mu=async e=>{const t=Ee();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}};Mu.locally=e=>{const t=Ee();if(t.log("poll/getPoll",e),!t.cache)return;const n=Pe(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ju=e=>{const t=Ee();return st(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Gt(n),e(n.polls[0])}))},Uu=e=>{const t=Ee();return st(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Gt(n),e(n.polls[0])}))};var xu=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ee();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r});const{polls:a}=n;return{data:a[0],cachedAt:r}},closePoll:async e=>{const t=Ee();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&&Gt(n,{cachedAt:r}),ot("poll.updated",n);const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=Ee();t.log("poll/deletePoll",e);const n=await Mu(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Ue(["poll","get",e],s),ot("poll.deleted",{polls:[s],users:[]}),a},votePoll:async(e,t)=>{const n=Ee();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),a=n.cache&&Date.now();n.cache&&Gt(r,{cachedAt:a});const{polls:s}=r;return ot("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:a}},unvotePoll:async e=>{const t=Ee();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Gt(n,{cachedAt:r}),ot("poll.updated",n)},onPollUpdated:ju,onPollDeleted:Uu,getPoll:(e,t)=>lo(e,t,"pollId",Mu,[ju,Uu])});const Du={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function qu(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function Nu(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,Du,!1,["sign"])}async function Bu({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const a=e();if(a.length)try{const n=(new Date).toISOString(),s=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(),a=`nonceStr=${r}&timestamp=${e}&data=${n}==`,s=(new TextEncoder).encode(a),o=await Nu("-----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:qu(await crypto.subtle.sign(Du,o,s)),nonceStr:r}}({timestamp:n,streams:a});if(!s||!s.signature)throw new Error("Signature is undefined");const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:a},i=Ee();return await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||r(),!0}catch(e){return a.forEach((e=>n(e))),!1}}class Lu{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((()=>{Bu({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Fu=null;class Ku{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Fu||(Fu=new Lu,Fu),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(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(qc((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var $u=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(!I.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Su(t),{watcherUrl:r,status:a,recordings:s=[],resolution:o}=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 I.default;if(c.attachMedia(i),"recorded"!==a){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new Ku(i,o,t).registerEvents(),i}});const Qu=e=>{const t=(e=>{var t;const n=Ee(),r=new Date,a=r.getTime()+31536e6,s=new Date(a).toISOString();let o=null===(t=Pe(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Gt({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(a).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Gt(t),t},zu=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const a=t.getAll("files")[0]||void 0;if(!a)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:a.uri})});return n&&(s.data.videoFileId={original:void 0}),r(Qu(s))}return r(Qu(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},Vu=async e=>{const t=Ee();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Ed(n.data);t.cache&&Gt(r),Me(["story-sync-state",e.targetId],"synced"),ot("local.story.created",r);const a=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:a}},Hu=async({targetId:e,targetType:t})=>{var n,r;if(!Pe(["storyTarget","get",e])){let a={targetId:e,targetType:t};if("community"===t){const t=await pl(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await ci(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Me(["storyTarget","get",e],a)}},Ju=e=>e?Pe(["story","get",e]):{data:void 0,cachedAt:void 0},Wu=async(e,t=!1)=>{var n,r,a;const s=Ee();let o;if(s.log("story/deleteStory",e),s.cache&&(o=Ju(e),null==o?void 0:o.data)){const{data:s}=o;if(ot("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},s),{isDeleted:!0})]}),"synced"!==s.syncState){t?xe(["story","get",e]):Me(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const r=null===(n=Re(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Me(["story-expire",o.data.targetId],e.toISOString())}else xe(["story-expire",o.data.targetId]);return!0}const i=null===(r=Pe(["storyTarget","get",s.targetId]))||void 0===r?void 0:r.data,c=null===(a=Re(["story","get"]))||void 0===a?void 0:a.filter((e=>"synced"===e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Me(["storyTarget","get",s.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await s.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Gu=e=>{const t=Ee(),n=[st(t,"onStoryUpdated","story.updated",(async t=>{const n=Ed(t);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Yu=e=>{const t=Ee(),n=[st(t,"onStoryUpdated","local.story.updated",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Zu=e=>{const t=Ee(),n=[st(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Zt(t,["reactions"]),a=Ed(r),s=qi("story.reactionAdded",Object.assign(Object.assign({},a),{reactions:n}));Gt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Xu=e=>{const t=Ee(),n=[st(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Gt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},eh=e=>{const t=Ee(),n=[st(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Zt(t,["reactions"]),a=Ed(r),s=qi("story.reactionRemoved",Object.assign(Object.assign({},a),{reactions:n}));Gt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},th=e=>{const t=Ee(),n=[st(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Gt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},nh=e=>{e.forEach((e=>{const t=Pe(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Me(["story-expire",e.targetId],n.toISOString())}))},rh=e=>{e.forEach((e=>{Me(["story-reference",e.storyId],e.referenceId)}))},ah=async({targetType:e,targetId:t,options:n})=>{const r=Ee();r.log("story/getActiveStoriesByTarget");const a=r.cache&&Date.now(),s=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=Ed(s.data);return r.cache&&(Gt(o),nh(o.stories),rh(o.stories)),{data:o.stories,cachedAt:a,paging:{next:void 0,previous:void 0}}},sh=e=>{const t=Ee(),n=[st(t,"onStoryCreated","story.created",(async t=>{const n=Ed(t,!0);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},oh=e=>{const t=Ee(),n=[st(t,"onStoryCreated","local.story.created",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ih=e=>{const t=Ee(),n=[st(t,"onStoryDeleted","story.deleted",(async t=>{const n=Ed(t);Gt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},ch=e=>{const t=Ee(),n=[st(t,"onStoryDeleted","local.story.deleted",(async t=>{Gt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},lh=e=>{const t=Ee();return st(t,"onStoryError","local.story.error",(async t=>{Gt(t),e(t.stories)}))},dh=e=>t=>e((e=>t(e[0]))),uh=async e=>{const t=Ee();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Gt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class hh extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now(),r=Ed(e);t.cache&&(Gt(r,{cachedAt:n}),nh(r.stories),rh(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(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=Pe(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])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ph extends eo{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class fh extends to{constructor(e,t){const n=C.default(e),r=["story-target-ids","collection",n],a=new ph(e);super(a,n,r,t),this.query=e,this.queryStreamController=new hh(this.query,this.cacheKey,this.notifyChange.bind(this),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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 a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let s=a.data.map((e=>Pe(["story","get",e]))).filter(Boolean).map((e=>ti.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,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(Ve):r.sort(Je)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:sh,action:"onCreate"},{fn:Gu,action:"onUpdate"},{fn:ih,action:"onDelete"},{fn:lh,action:"onError"}])}}const mh=(e,t)=>{var n,r;const a=null===(n=Pe(e))||void 0===n?void 0:n.data,s=null!==(r=null==a?void 0:a.data)&&void 0!==r?r:[];Me(e,Object.assign(Object.assign({},a),{data:[...new Set([...s,...t])]}))};class gh extends Ys{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=a}saveToMainDB(e){const t=Ee(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Gt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Me(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):mh(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&mh(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 yh extends Ws{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:a="unseen"}=e,s=await this.createRequest({seenState:"smart"===a?this.smartFilterState:a,limit:r,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==a)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=o,{categories:(i=s).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 vh extends to{constructor(e,t){const n=C.default(e),r=["story-global-feed","collection",n],a=new yh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new gh(this.query,this.cacheKey,this.notifyChange.bind(this),a,(e=>{const t=Zt(Ro(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(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 a=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=a.data,o=Re(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{a.data.includes(e[2])||s.push(e[2])})));let i=s.map((e=>Pe(["storyTarget","get",e]))).filter(Boolean).map((e=>ti.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>Zt(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(He);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(He)||[],r=t.unseen.sort(He)||[],a=t.seen.sort(He)||[];return n.concat(r,a)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:sh,action:"onCreate"},{fn:Gu,action:"onUpdate"},{fn:ih,action:"onDelete"},{fn:oh,action:"onCreate"},{fn:Yu,action:"onUpdate"},{fn:ch,action:"onDelete"},{fn:lh,action:"onError"}])}}var bh=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},a="fit",s=[])=>{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:a},syncState:"syncing",referenceId:$t(),dataType:"image",items:s,targetType:e,targetId:t,metadata:r};const i=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),zu({payload:o,formData:n},(e=>{ot("local.story.created",e)}));try{const{data:r}=await Oi(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:a}=r[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:a})}),Hu({targetId:t,targetType:e}),zu({payload:o,formData:n},(e=>{ot("local.story.created",e)}));const s=await Vu(o);return s.data?Object.assign(Object.assign({},s),{data:ti.story(s.data)}):s}catch(e){throw Me(["story-sync-state",t],"error"),zu({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{ot("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},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},syncState:"syncing",referenceId:$t(),dataType:"video",items:a,targetType:e,targetId:t,metadata:r};const o=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),Hu({targetId:t,targetType:e}),zu({payload:s,formData:n,isVideo:!0},(e=>{ot("local.story.created",e)}));try{const{data:e}=await ki(n,P.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),zu({payload:s,formData:n,isVideo:!0},(e=>{ot("local.story.created",e)}));const r=await Vu(s);return r.data?Object.assign(Object.assign({},r),{data:ti.story(r.data)}):r}catch(e){throw Me(["story-sync-state",t],"error"),zu({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{ot("local.story.error",e)})),e}},hardDeleteStory:async e=>await Wu(e,!0),softDeleteStory:async e=>await Wu(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Ee(),a=[],s=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),r||console.log(V);const i=t=>{var n,r;const a=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===a?"asc"===s?t.sort(Ve):t.sort(Je):"asc"===s?t.sort(We):t.sort(Ge)},c=e=>{var n;const r=e.data.map((e=>{const t=Ju(e);if(null==t?void 0:t.data)return ti.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),a=[];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")||[]);a.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);a.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);a.push(...t)}}t({onNextPage:()=>!1,data:a||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,a=!1,o=!1)=>{var i;const l=Pe(s),d={loading:a,error:o,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(be("story")):[...new Set([...d.data,...t.map(be("story"))])];const u=null===(i=Re(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>be("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Me(s,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=fe(ah,e);ge(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),a.push(sh(d("onCreate")),Gu(d("onUpdate")),ih(d("onDelete")),Zu(d("onReactionAdded")),eh(d("onReactionRemoved")),lh(d("onError")),oh(d("onCreate")),Yu(d("onUpdate")),ch(d("onDelete")),Xu(d("onReactionAdded")),th(d("onReactionRemoved")),(e=>{const t=Ee();return st(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Pe(s);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)})),(()=>xe(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>lo(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:ti.story(e.data)})):t(e)}),"storyId",Ad,[dh(Gu),dh(ih),dh(Zu),dh(eh),dh(lh),dh(Yu),dh(ch),dh(Xu),dh(th)]),getTargetById:(e,t)=>lo(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:ti.storyTarget(e.data[0])})):t(e)}),"query",(e=>uh([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Ee(),a=[],s=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),r||console.log(V);const i=(e,n=!1,r=!1,a=!1)=>{const o=Pe(s),i={loading:r,error:a,params:{page:void 0},data:[]};e&&(i.data=n?e.map(be("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(be("storyTarget"))])]),Me(s,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Pe(["storyTarget","get",e]);if(null==t?void 0:t.data)return ti.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=fe(uh,e);ge(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),a.push((()=>xe(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new fh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:a,userId:s}=Ee();a||console.log(V);const o=Date.now();r(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new vh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{xe(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const wh=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Ch=e=>Object.assign({},e);var Ih=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ee(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(wh),r=t.advertisers.map(Ch);return Gt({ads:n,advertisers:r,files:t.files}),Me(["ad","setting"],t.settings),{ads:n.map(ti.ad),settings:t.settings}}});const Sh=async()=>{const e=Ee();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Me(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};Sh.locally=()=>{var e;const t=Ee();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=Pe(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const _h=e=>{const t=Ee(),n=[st(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class kh extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class Oh extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.notificationTrayItems.map(be("notificationTrayItem"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(be("notificationTrayItem"))])]}))}}}const Th=e=>{const t=e.users.map(Tn);return Object.assign(Object.assign({},e),{users:t})};class Eh extends to{constructor(e,t){const n=C.default(e),r=["notificationTrayItem","collection",n];super(new kh(e),n,r,t),this.query=e,this.queryStreamController=new Oh(this.query,this.cacheKey,this.notifyChange.bind(this),Th),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Pe(["notificationTrayItem","get",e]))).filter(no).map((({data:e})=>e)))&&void 0!==a?a:[]).map(ti.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Ah=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Xe();return lo(t,e,"userId",Sh,[_h],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Mn(e.lastTraySeenAt)>Mn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getNotificationTrayItems(tmpid: ${s}) > listen`);const o=new Eh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>xe(c))),()=>{r(`getNotificationTrayItems(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ee();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=Pe(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const a=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Me(["notificationTrayItem","get"],a,{cachedAt:e})}return a})).filter(Boolean);ot("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Ee();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),a=null===(t=Pe(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,s={userId:n.userId,lastTraySeenAt:r.lastSeenAt},o=Object.assign(Object.assign({},a),s),i=n.cache&&Date.now();return n.cache&&Me(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),ot("local.notificationTraySeen.updated",s),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:_h});class Rh extends Ws{async getRequest(e,t){const{limit:n=Q}=e,r=Zt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:a})});return await hl(s.invitations.map((e=>e.communityId))),s}}class Ph extends Ys{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ee(),r=n.cache&&Date.now();n.cache&&Gt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(be("invitation"))});else{const t=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(be("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Pe(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Ho.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===Ho.OnLocalInvitationCreated){const e=Ee(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===Ho.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mh extends to{constructor(e,t){const n=C.default(e),r=["invitation","collection",n];super(new Rh(e),n,r,t),this.query=e,this.queryStreamController=new Ph(this.query,this.cacheKey,this.notifyChange.bind(this),zo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Pe(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Go,action:Ho.OnLocalInvitationCreated},{fn:Yo,action:Ho.OnLocalInvitationUpdated},{fn:Zo,action:Ho.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Pe(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Pe(["invitation","get",e]))).filter(no).map((({data:e})=>Vo(e))))&&void 0!==a?a:[]);(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;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ve:Je)();return t=t.sort(n),t}}var jh=Object.freeze({__proto__:null,onLocalInvitationCreated:Go,onLocalInvitationUpdated:Yo,onLocalInvitationDeleted:Zo,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:a}=Ee();a||console.log(V);const s=Date.now();r(`getMyCommunityInvitations: (tmpid: ${s}) > listen`);const o=new Mh(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{xe(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Uh=e=>{const t=Ee();return st(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var xh=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r})=>{const a=Ee();a.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n});const s=La(),o={reactionName:n,referencePublicId:e,referenceType:t,streamId:r,occurredAt:(new Date).toISOString()};return s.createLiveReaction(o),ot("local.liveReaction.created",[Object.assign(Object.assign({},o),{userId:a.userId,referenceId:e})]),!0},onLiveReactionCreated:Uh,getReactions:(e,t)=>{const{_id:n}=Xe();if(!n)throw new Ie("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ee();r(`getReactions(tmpid: ${Date.now()}) > listen`);const a=[],s=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return a.push(Uh(s)),a.push((e=>{const t=Ee();return st(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(s)),()=>{a.forEach((e=>e()))}}});return e.API_REGIONS=Ot,e.AdRepository=Ih,e.CategoryRepository=Id,e.ChannelRepository=dl,e.Client=As,e.CommentRepository=Ld,e.CommunityPostSettingMaps=A,e.CommunityPostSettings=E,e.CommunityRepository=bd,e.ContentFeedType=P,e.DefaultCommunityPostSetting=R,e.FeedRepository=tu,e.FileRepository=Ti,e.FileType=S,e.GET_WATCHER_URLS=go,e.InvitationRepository=jh,e.LiveReactionRepository=xh,e.LiveStreamPlayer=$u,e.MessageContentType=j,e.MessageRepository=Fc,e.PollRepository=xu,e.PostContentType=U,e.PostRepository=Iu,e.ReactionRepository=fc,e.StoryRepository=bh,e.StreamRepository=Pu,e.SubChannelRepository=Jc,e.UserRepository=Si,e.VERSION=$,e.VideoResolution=_,e.VideoSize=O,e.VideoTranscodingStatus=k,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:a}=Ee();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${a}`,JSON.stringify(s)),!0)},e.createQuery=fe,e.createReport=async(e,t)=>{const n=Ee();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await ua(n);Gt(e)}return ot("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await _n(n);Gt(e)}return ot("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Li(n);Gt(e)}return ot("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await mc(n);Gt(e)}return ot("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await zt(),a=Vt(),s=xt(Et("http",t)),{data:o}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},a),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=Ee();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await ua(n);Gt(e)}return ot("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await _n(n);Gt(e)}return ot("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Li(n);Gt(e)}return ot("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await mc(n);Gt(e)}return ot("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ee();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=xe,e.enableCache=(e={},t)=>{const n=Ee();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Be,e.filterByCommunityMembership=Fe,e.filterByFeedType=Le,e.filterByPostDataTypes=Ke,e.filterByPropEquality=De,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Ne,e.filterBySearchTerm=$e,e.filterByStringComparePartially=qe,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Xe();return`${ht(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>ut(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=wt,e.getMarkedMessageTopic=ft,e.getMarkerUserFeedTopic=mt,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Xe();return`${ht(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Xe();return`${ht(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=gt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Ai,e.getSmartFeedChannelTopic=yt,e.getSmartFeedMessageTopic=bt,e.getSmartFeedSubChannelTopic=vt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Xe();return`${ht(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=pt,e.isAfterBefore=ae,e.isAfterBeforeRaw=se,e.isCachable=he,e.isFetcher=le,e.isFresh=pe,e.isLocal=e=>he(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=de,e.isOffline=ue,e.isPaged=oe,e.isReportedByMe=async(e,t)=>{const n=Ee();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=re,e.mergeInCache=je,e.notificationTray=Ah,e.onChannelMarkerFetched=ws,e.onFeedMarkerFetched=e=>{const t=Ee();return st(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ee();return st(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Gt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=ks,e.onMessageMarkerFetched=_s,e.onSubChannelMarkerFetched=Cs,e.onSubChannelMarkerUpdated=Is,e.onUserMarkerFetched=Ss,e.onUserMarkerFetchedLegacy=e=>{const t=Ee();return st(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Pe,e.pushToCache=Me,e.queryCache=Re,e.queryOptions=me,e.queryRoles=Ei,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ee();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 a={};try{a=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},a),n.cache.data),!0},e.runQuery=ge,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Qe,e.sortByFirstCreated=Ve,e.sortByFirstUpdated=We,e.sortByLastActivity=Ye,e.sortByLastCreated=Je,e.sortByLastUpdated=Ge,e.sortByLocalSortingDate=He,e.sortByName=ze,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Ct,e.toPage=ce,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return se(n)?n:void 0},e.toToken=ie,e.upsertInCache=Ue,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Ee();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,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);