PageSourceSearch

https://app.mybasecommunity.com/_next/static/chunks/0lf6fawv~sc5p.js

js mybasecommunity.com collected 2026-10-02 16:03:27 UTC 321,715 bytes, 1 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,92571,e=>{"use strict";var t=e.i(19273);function s(e,{pages:t,pageParams:i}){let a=t.length-1;return t.length>0?e.getNextPageParam(t[a],t,i[a],i):void 0}function i(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}e.s(["hasNextPage",0,function(e,t){return!!t&&null!=s(e,t)},"hasPreviousPage",0,function(e,t){return!!t&&!!e.getPreviousPageParam&&null!=i(e,t)},"infiniteQueryBehavior",0,function(e){return{onFetch:(a,n)=>{let r=a.options,o=a.fetchOptions?.meta?.fetchMore?.direction,l=a.state.data?.pages||[],d=a.state.data?.pageParams||[],c={pages:[],pageParams:[]},h=0,u=async()=>{let n=!1,u=(0,t.ensureQueryFn)(a.options,a.fetchOptions),g=async(e,s,i)=>{let r;if(n)return Promise.reject();if(null==s&&e.pages.length)return Promise.resolve(e);let o=(r={client:a.client,queryKey:a.queryKey,pageParam:s,direction:i?"backward":"forward",meta:a.options.meta},(0,t.addConsumeAwareSignal)(r,()=>a.signal,()=>n=!0),r),l=await u(o),{maxPages:d}=a.options,c=i?t.addToStart:t.addToEnd;return{pages:c(e.pages,l,d),pageParams:c(e.pageParams,s,d)}};if(o&&l.length){let e="backward"===o,t={pages:l,pageParams:d},a=(e?i:s)(r,t);c=await g(t,a,e)}else{let t=e??l.length;do{let e=0===h?d[0]??r.initialPageParam:s(r,c);if(h>0&&null==e)break;c=await g(c,e),h++}while(h<t)}return c};a.options.persister?a.fetchFn=()=>a.options.persister?.(u,{client:a.client,queryKey:a.queryKey,meta:a.options.meta,signal:a.signal},n):a.fetchFn=u}}}])},7417,e=>{"use strict";var t=e.i(94583);function s(e){let t=e.cid||e.channel?.cid,s=e.channel_id||e.channel?.id||"",i=e.channel?.data??{};return t?.startsWith("messaging:space-")||s.startsWith("space-")?"space":!0===i.vent||s.startsWith("vent-")?null:"dm"}function i(e){return e.cid||e.channel?.cid||null}function a(e,...t){for(let s of t){let t=e[s];if("string"==typeof t&&t.trim())return t.trim()}}function n(e){let t=s(e);if(!t)return null;let i=e.message?.user?.name||"Someone",n=(e.message?.text||"").trim();if("space"===t){let t=e.channel?.data??{},s=a(t,"spaceName","space_name"),r=a(t,"communityName","community_name"),o=s&&r?`${s} (${r})`:s||r||"space";return{title:`${i} in ${o}`,description:n.length>0?n:`${i} sent a message`}}return{title:"New message",description:n.length>0?`${i}: ${n}`:`${i} sent a message`}}async function r(){return await navigator.serviceWorker.register("/web-push-sw.js"),navigator.serviceWorker.ready}async function o(e,s){let i=await e.pushManager.getSubscription();i||(i=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),s=globalThis.atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),i=new Uint8Array(s.length);for(let e=0;e<s.length;e+=1)i[e]=s.charCodeAt(e);return i}("BJZYSxsBvKGBTmj5m9nxBCqXKWgGduQs2OKME83KFzuMHnGYXGTJOdqUazmoDUrtKDySwvPA95Lym1SkZqIXdeY").buffer}));let a=i.toJSON();await (0,t.invokeEdgeFunction)("web-push-subscribe",{endpoint:a.endpoint,keys:a.keys??{},userAgent:navigator.userAgent,streamUserId:s})}async function l(e){if(!("serviceWorker"in navigator)||"granted"!==Notification.permission)return;let t=function(e){let t=n(e),a=function(e){let t=s(e);if(!t)return null;let a=i(e);if(!a)return null;if("space"===t){let t=e.channel?.data?.communityId,s=e.channel?.data?.spaceId;if("string"==typeof t&&"string"==typeof s)return`/communities/${t}/spaces/${s}`}return`/dm/group/${encodeURIComponent(a)}`}(e);if(!t||!a)return null;let r="string"==typeof e.message?.id&&e.message.id.trim()?e.message.id.trim():void 0,o=i(e);return{title:t.title,body:t.description,route:a,messageId:r,tag:r?`msg:${r}`:o?`cid:${o}`:`chat:${Date.now()}`,sentAt:Date.now()}}(e);if(!t)return;let a=await r();await a.showNotification(t.title,{body:t.body,icon:"/icons/icon-192.png",badge:"/icons/icon-192.png",tag:t.tag,data:{route:t.route,messageId:t.messageId,sentAt:t.sentAt}})}async function d(e){if(!("serviceWorker"in navigator)||!("PushManager"in window)||!("Notification"in window))return;let t=await r();"granted"===Notification.permission&&await o(t,e)}
1async function c(e){if(!("serviceWorker"in navigator)||!("PushManager"in window)||!("Notification"in window)||"granted"!==await Notification.requestPermission())return!1;let t=await r();return await o(t,e),!0}async function h(){if(!("serviceWorker"in navigator))return;let e=await r().catch(()=>void 0),s=await e?.pushManager.getSubscription();if(!s)return;let i=s.endpoint;await s.unsubscribe(),await (0,t.invokeEdgeFunction)("web-push-unsubscribe",{endpoint:i})}e.s(["buildForegroundNotificationText",0,n,"getNotificationPermissionState",0,function(){return"Notification"in window?Notification.permission:"unsupported"},"isBrowserPushSupported",0,function(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window},"isWebPushEnvConfigured",0,function(){return!0},"listenForWebPushResubscribe",0,function(e){if("u"<typeof navigator||!("serviceWorker"in navigator))return()=>{};let t=t=>{let s=t.data;s?.type==="WEB_PUSH_RESUBSCRIBE"&&e&&d(e).catch(e=>{console.error("Web push re-subscribe after subscription change failed",e)})};return navigator.serviceWorker.addEventListener("message",t),()=>navigator.serviceWorker.removeEventListener("message",t)},"registerWebPushSubscription",0,d,"removeWebPushSubscription",0,h,"requestAndRegisterWebPush",0,c,"shouldIgnoreNotificationEvent",0,function(e,t,a){if(!s(e))return!0;let n=e.message?.user?.id||e.user?.id;if(n&&t&&n===t)return!0;let r=i(e);return!!r&&!!a&&r===a&&"visible"===document.visibilityState},"showNativeNotificationForEvent",0,l])},98412,e=>{"use strict";e.s(["canViewCommunityContent",0,function(e){return e.hasAccess||"open"===e.joinPermission},"communityRestrictedMessage",0,function(e){return"invite"===e?"This community doesn't exist or is invite-only.":"request"===e?"This community is private. Request access or wait for an invite to join.":"You don't have access to this community."},"redactCommunity",0,function(e){return{...e,name:"",description:null,communityPhoto:null}}])},34582,(e,t,s)=>{"use strict";s.byteLength=function(e){var t=d(e),s=t[0],i=t[1];return(s+i)*3/4-i},s.toByteArray=function(e){var t,s,i=d(e),r=i[0],o=i[1],l=new n((r+o)*3/4-o),c=0,h=o>0?r-4:r;for(s=0;s<h;s+=4)t=a[e.charCodeAt(s)]<<18|a[e.charCodeAt(s+1)]<<12|a[e.charCodeAt(s+2)]<<6|a[e.charCodeAt(s+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===o&&(t=a[e.charCodeAt(s)]<<2|a[e.charCodeAt(s+1)]>>4,l[c++]=255&t),1===o&&(t=a[e.charCodeAt(s)]<<10|a[e.charCodeAt(s+1)]<<4|a[e.charCodeAt(s+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},s.fromByteArray=function(e){for(var t,s=e.length,a=s%3,n=[],r=0,o=s-a;r<o;r+=16383)n.push(function(e,t,s){for(var a,n=[],r=t;r<s;r+=3)a=(e[r]<<16&0xff0000)+(e[r+1]<<8&65280)+(255&e[r+2]),n.push(i[a>>18&63]+i[a>>12&63]+i[a>>6&63]+i[63&a]);return n.join("")}(e,r,r+16383>o?o:r+16383));return 1===a?n.push(i[(t=e[s-1])>>2]+i[t<<4&63]+"=="):2===a&&n.push(i[(t=(e[s-2]<<8)+e[s-1])>>10]+i[t>>4&63]+i[t<<2&63]+"="),n.join("")};for(var i=[],a=[],n="u">typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,l=r.length;o<l;++o)i[o]=r[o],a[r.charCodeAt(o)]=o;function d(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=t);var i=s===t?0:4-s%4;return[s,i]}a[45]=62,a[95]=63},3765,(e,t,s)=>{"use strict";t.exports="object"==typeof self?self.FormData:window.FormData},43270,31487,53364,28367,e=>{"use strict";let t,s,i,a;var n,r,o,l,d,c,h,u=e.i(47167),g=e.i(18050),p=e.i(66347),m=e.i(3922),f=e.i(7417),y=e.i(98412);let b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _(e){let t=(e.message??"").toLowerCase();return!!("PGRST204"===e.code||t.includes("streamuserid")&&t.includes("schema cache")||t.includes("streamuserid")&&t.includes("could not find")||t.includes("stream_user_id")&&t.includes("schema cache")||t.includes("stream_user_id")&&t.includes("could not find"))}function w(e){let t=(e.message??"").toLowerCase();return!!("PGRST204"===e.code||t.includes("firebase_uid")&&t.includes("schema cache")||t.includes("firebase_uid")&&t.includes("could not find"))}function v(e,t){t.set(e.id,e.id),"string"==typeof e.streamUserId&&e.streamUserId&&t.set(e.streamUserId,e.id),"string"==typeof e.firebase_uid&&e.firebase_uid&&t.set(e.firebase_uid,e.id)}async function C(e){let t=new Map,s=[...new Set(e.filter(Boolean))];if(0===s.length)return t;for(let e of s)b.test(e)&&t.set(e,e);let i=s.filter(e=>!t.has(e));if(0===i.length)return t;let a=i.filter(e=>b.test(e));if(a.length>0){let e=await m.supabase.from("users").select("id, streamUserId, firebase_uid").in("id",a);if(e.error?.message?.includes("firebase_uid")&&(e=await m.supabase.from("users").select("id, streamUserId").in("id",a)),e.error&&_(e.error)&&(e=await m.supabase.from("users").select("id").in("id",a)),e.error)throw e.error;for(let s of e.data??[])v(s,t)}let n=i.filter(e=>!t.has(e));if(0===n.length)return t;let r=await m.supabase.from("users").select("id, streamUserId, firebase_uid").in("streamUserId",n);if(r.error?.message?.includes("firebase_uid")&&(r=await m.supabase.from("users").select("id, streamUserId").in("streamUserId",n)),r.error&&_(r.error)&&(r=await m.supabase.from("users").select("id").in("streamUserId",n)),r.error)if(_(r.error));else if(w(r.error));else throw r.error;else for(let e of r.data??[])v(e,t);if(0===(n=i.filter(e=>!t.has(e))).length)return t;let o=await m.supabase.from("users").select("id, streamUserId, firebase_uid").in("firebase_uid",n);if(o.error?.message?.includes("firebase_uid"))return t;if(o.error){if(w(o.error))return t;throw o.error}for(let e of o.data??[])v(e,t);return t}async function S(e,t){let s={streamUserId:t.streamUserId},i=null!=t.firebaseUid&&t.firebaseUid.length>0?{...s,firebase_uid:t.firebaseUid}:s,{error:a}=await m.supabase.from("users").update(i).eq("id",e);if(a){if((!(a.message??"").toLowerCase().includes("firebase_uid")||({error:a}=await m.supabase.from("users").update(s).eq("id",e),a))&&!_(a)){if(w(a)&&({error:a}=await m.supabase.from("users").update(s).eq("id",e),!a||_(a)))return;console.warn("syncMyChatIdentityIds",a.message)}}}async function R(e){let t=new Map,s=[...new Set(e.filter(Boolean).filter(e=>b.test(e)))];if(0===s.length)return t;let i=await m.supabase.from("users").select("id, streamUserId, firebase_uid").in("id",s);i.error?.message?.includes("firebase_uid")&&(i=await m.supabase.from("users").select("id, streamUserId").in("id",s));let{data:a,error:n}=i;if(n){if(_(n)){let{data:e,error:i}=await m.supabase.from("users").select("id").in("id",s);if(i)throw i;for(let s of e??[])t.set(s.id,s.id);return t}throw n}for(let e of a??[])v(e,t);return t}async function U(e){let{data:t,error:s}=await m.supabase.from("communities").select("communityId, name, description, communityPhoto, joinPermission, createdBy").or(`createdBy.eq.${e},admins.cs.["${e}"],members.cs.["${e}"]`).order("updatedAt",{ascending:!1});if(s)throw s;return(t??[]).map(e=>({...e,hasAccess:!0,hasPendingInvite:!1,hasPendingRequest:!1}))}async function I(e,t){let{data:s,error:i}=await m.supabase.from("communities").select("communityId, joinPermission, createdBy, admins, members").eq("communityId",e).single();if(i)throw i;let a=Array.isArray(s.admins)?s.admins:[],n=Array.isArray(s.members)?s.members:[],r=s.createdBy===t||a.includes(t)||n.includes(t),[{data:o},{data:l}]=await Promise.all([m.supabase.from("community_join_requests").select("communityId").eq("communityId",e).eq("userId",t).eq("status","pen
1ding").maybeSingle(),m.supabase.from("community_invites").select("communityId").eq("communityId",e).eq("invitedUserId",t).eq("status","pending").maybeSingle()]);return{communityId:s.communityId,joinPermission:s.joinPermission,createdBy:s.createdBy,hasAccess:r,hasPendingRequest:!!o,hasPendingInvite:!!l}}async function x(e,t){let{data:s,error:i}=await m.supabase.from("communities").select("communityId, name, description, communityPhoto, joinPermission, createdBy, admins, members").eq("communityId",e).maybeSingle();if(i)throw i;if(!s)return null;let a=Array.isArray(s.admins)?s.admins:[],n=Array.isArray(s.members)?s.members:[],r=s.createdBy===t||a.includes(t)||n.includes(t),[{data:o},{data:l}]=await Promise.all([m.supabase.from("community_join_requests").select("communityId").eq("communityId",e).eq("userId",t).eq("status","pending").maybeSingle(),m.supabase.from("community_invites").select("communityId").eq("communityId",e).eq("invitedUserId",t).eq("status","pending").maybeSingle()]),d={communityId:s.communityId,name:s.name,description:s.description,communityPhoto:s.communityPhoto,joinPermission:s.joinPermission,createdBy:s.createdBy,hasAccess:r,hasPendingRequest:!!o,hasPendingInvite:!!l};return(0,y.canViewCommunityContent)({joinPermission:d.joinPermission,hasAccess:!!d.hasAccess})?d:(0,y.redactCommunity)(d)}function L(e){return[...new Set(e.filter(Boolean))]}function M(e){return e.username||[e.firstName,e.lastName].filter(Boolean).join(" ")||"Member"}async function E(e){let t=new Map,s=e.filter(e=>b.test(e));if(0===s.length)return t;for(let e=0;e<s.length;e+=100){let i=s.slice(e,e+100),{data:a,error:n}=await m.supabase.from("users").select("id, username, firstName, lastName, avatar").in("id",i);if(n)throw n;for(let e of a??[])t.set(e.id,{id:e.id,username:e.username,firstName:e.firstName,lastName:e.lastName,avatar:e.avatar})}return t}async function A(e){return E(e)}async function k(e,t){let{data:s,error:i}=await m.supabase.from("communities").select("communityId, name, description, communityPhoto, joinPermission, createdBy, admins, members, updatedAt").eq("communityId",e).single();if(i)throw i;let a=Array.isArray(s.admins)?s.admins:[],n=Array.isArray(s.members)?s.members:[],r=s.createdBy===t||a.includes(t)||n.includes(t),o=L([s.createdBy,...a,...n]),l=[];if(r&&o.length>0){let e=await E(o);(l=o.map(t=>{let i=e.get(t)??{id:t,username:null,firstName:null,lastName:null,avatar:null},n="member";return t===s.createdBy?n="owner":a.includes(t)&&(n="admin"),{...i,role:n}})).sort((e,t)=>{let s=e=>"owner"===e?0:"admin"===e?1:2,i=s(e.role)-s(t.role);return 0!==i?i:M(e).localeCompare(M(t),void 0,{sensitivity:"base"})})}let d={communityId:s.communityId,joinPermission:s.joinPermission,hasAccess:r,hasPendingRequest:!1,hasPendingInvite:!1},[{data:c},{data:h}]=await Promise.all([m.supabase.from("community_join_requests").select("communityId").eq("communityId",e).eq("userId",t).eq("status","pending").maybeSingle(),m.supabase.from("community_invites").select("communityId").eq("communityId",e).eq("invitedUserId",t).eq("status","pending").maybeSingle()]);d.hasPendingRequest=!!c,d.hasPendingInvite=!!h;let u=(0,y.canViewCommunityContent)(d);return{communityId:s.communityId,name:u?s.name:"",description:u?s.description:null,communityPhoto:u?s.communityPhoto:null,joinPermission:s.joinPermission,createdBy:s.createdBy,updatedAt:s.updatedAt,createdAt:null,hasAccess:r,hasPendingRequest:d.hasPendingRequest,hasPendingInvite:d.hasPendingInvite,memberProfiles:l,memberCount:r?o.length:0}}async function D(e){let{data:t,error:s}=await m.supabase.from("communities").select("communityId").or(`createdBy.eq.${e},admins.cs.["${e}"],members.cs.["${e}"]`);if(s)throw s;let i=(t??[]).map(e=>e.communityId);if(0===i.length)return[];let{data:a,error:n}=await m.supabase.from("spaces").select("spaceId, name, description, spacePhoto, joinPermission, communityId, createdBy, admins").in("communityId",i).order("name",{ascending:!0});if(n)throw n;let r=a??[],o=r.map(e=>e.spaceId);if(0===o.length)return[];let{data:l,error:d}=await m.supabase.from("space_members").select("spaceId").eq("userId",e).in("spaceId",o);if(d)throw d;let{data:c,error:h}=await m.supabase.from("space_join_requests").select("spaceId").eq("userId",e).eq("status","pen
1ding").in("spaceId",o);if(h)throw h;let{data:u,error:g}=await m.supabase.from("space_invites").select("spaceId").eq("invitedUserId",e).eq("status","pending").in("spaceId",o);if(g)throw g;let p=new Set((l??[]).map(e=>e.spaceId)),f=new Set((c??[]).map(e=>e.spaceId)),y=new Set((u??[]).map(e=>e.spaceId));return r.map(t=>{let s=Array.isArray(t.admins)?t.admins:[],i=t.createdBy===e||s.includes(e)||p.has(t.spaceId);return{spaceId:t.spaceId,name:t.name,description:t.description,spacePhoto:t.spacePhoto,joinPermission:t.joinPermission,communityId:t.communityId,createdBy:t.createdBy,hasAccess:i,hasPendingRequest:f.has(t.spaceId),hasPendingInvite:y.has(t.spaceId)}})}async function T(e,t){let s=await I(e,t);if(!(0,y.canViewCommunityContent)(s))return[];let{data:i,error:a}=await m.supabase.from("spaces").select("spaceId, name, description, spacePhoto, joinPermission, communityId, createdBy, admins").eq("communityId",e).order("name",{ascending:!0});if(a)throw a;let n=i??[],r=n.map(e=>e.spaceId);if(0===r.length)return[];let{data:o,error:l}=await m.supabase.from("space_members").select("spaceId").eq("userId",t).in("spaceId",r);if(l)throw l;let{data:d,error:c}=await m.supabase.from("space_join_requests").select("spaceId").eq("userId",t).eq("status","pending").in("spaceId",r);if(c)throw c;let{data:h,error:u}=await m.supabase.from("space_invites").select("spaceId").eq("invitedUserId",t).eq("status","pending").in("spaceId",r);if(u)throw u;let g=new Set((o??[]).map(e=>e.spaceId)),p=new Set((d??[]).map(e=>e.spaceId)),f=new Set((h??[]).map(e=>e.spaceId));return n.map(e=>{let s=Array.isArray(e.admins)?e.admins:[],i=e.createdBy===t||s.includes(t)||g.has(e.spaceId);return{spaceId:e.spaceId,name:e.name,description:e.description,spacePhoto:e.spacePhoto,joinPermission:e.joinPermission,communityId:e.communityId,createdBy:e.createdBy,hasAccess:i,hasPendingRequest:p.has(e.spaceId),hasPendingInvite:f.has(e.spaceId)}})}async function P(e){let{data:t,error:s}=await m.supabase.from("spaces").select("spaceId, name, description, spacePhoto, joinPermission, communityId, createdBy").eq("spaceId",e).single();if(s)throw s;return t}async function O(e,t){let{data:s,error:i}=await m.supabase.from("spaces").select("spaceId, name, description, spacePhoto, joinPermission, communityId, createdBy, admins").eq("spaceId",e).maybeSingle();if(i)throw i;if(!s)return null;let a=await I(s.communityId,t);if(!(0,y.canViewCommunityContent)(a))return null;let n=Array.isArray(s.admins)?s.admins:[],[{data:r},{data:o},{data:l}]=await Promise.all([m.supabase.from("space_members").select("spaceId").eq("spaceId",e).eq("userId",t).maybeSingle(),m.supabase.from("space_join_requests").select("spaceId").eq("spaceId",e).eq("userId",t).eq("status","pending").maybeSingle(),m.supabase.from("space_invites").select("spaceId").eq("spaceId",e).eq("invitedUserId",t).eq("status","pending").maybeSingle()]),d=s.createdBy===t||n.includes(t)||!!r;return{spaceId:s.spaceId,name:s.name,description:s.description,spacePhoto:s.spacePhoto,joinPermission:s.joinPermission,communityId:s.communityId,createdBy:s.createdBy,hasAccess:d,hasPendingRequest:!!o,hasPendingInvite:!!l}}async function N(e,t){let[s,i]=await Promise.all([m.supabase.from("spaces").select("spaceId, communityId, name, description, spacePhoto, joinPermission, createdBy, admins").eq("spaceId",e).single(),m.supabase.from("space_members").select("userId",{count:"exact",head:!0}).eq("spaceId",e)]);if(s.error)throw s.error;let a=s.data,n=Array.isArray(a.admins)?a.admins:[],r=L([a.createdBy,...n]).length,o=i.count??0;return{spaceId:a.spaceId,communityId:a.communityId,name:a.name,description:a.description,spacePhoto:a.spacePhoto,joinPermission:a.joinPermission,createdBy:a.createdBy,memberCount:r+o}}async function F(e,t){let{data:s,error:i}=await m.supabase.from("spaces").select("createdBy, admins").eq("spaceId",e).single();if(i)throw i;let a=s.createdBy,n=L([a,...Array.isArray(s.admins)?s.admins:[]]),r=[];if(0===t&&n.length>0){let e=await E(n);for(let t of n){let s=e.get(t);r.push({...s??{id:t,username:null,firstName:null,lastName:null,avatar:null},role:t===a?"owner":"admin"})}}let o=20-r.length,l=0===t?0:t-n.length,{data:d,error:c}=await m.supabase.from("space_members").select("userId").eq("spaceId",e).not("userId","in",`(${n.join(",")})`).range(l,l+o);if(c)throw c;let h=(d??[]).length>o,u=(d??[]).slice(0,o).map(e=>e.userId);if(u.length>0){let e=await E(u);for(let t of u){let s=e.get(t);r.push({...s??{id:t,username:null,firstName:null,lastName:null,avatar:null},role:"member"})}}return{members:r,nextOffset:h?0===t?n.length+u.length:t+u.length:null}}async function q(e){let{data:t,error:s}=await m.supabase.from("users").select("id, username, firstName, lastName, avatar, headline").eq("id",e).single();if(s)throw s;return t}async function j(e){let{data:t,error:s}=await m.supabase.from("users").select("id, email, username, firstName, lastName, avatar, headline").eq("id",e).single();if(s)throw s;return t}async function B(e){let{data:t,error:s}=await m.supabase.from("connections").select("id, requesterId, addresseeId, status, user:users!connections_addresseeId_fkey(id, username, firstName, lastName, avatar)").eq("requesterId",e).eq("status","accepted");if(s)throw s;let{data:i,error:a}=await m.supabase.from("connections").select("id, requesterId, addresseeId, status, user:users!connections_requesterId_fkey(id, username, firstName, lastName, avatar)").eq("addresseeId",e).eq("status","accepted");if(a)throw a;return[...t??[],...i??[]].map(e=>({...e,user:Array.isArray(e.user)?e.user[0]:e.user})).filter(e=>!!e.user)}e.s(["buildPeerStreamLookupFromSupabaseUserIds",0,R,"communityMemberDis
1playName",0,M,"getAcceptedConnections",0,B,"getAllSpacesForUser",0,D,"getCommunityDetails",0,k,"getCommunityForUser",0,x,"getMyAccount",0,j,"getSpaceById",0,P,"getSpaceDetails",0,N,"getSpaceForUser",0,O,"getSpaceMembersPage",0,F,"getSpacesByCommunityForUser",0,T,"getUserCommunities",0,U,"getUserPublicProfile",0,q,"getUserSummariesByIds",0,A,"resolveStreamUserIdsToSupabaseIds",0,C,"syncMyChatIdentityIds",0,S],31487);let $=["firebase_uid","firebaseUid","firebase_user_id","legacy_uid"];function V(e){if(!e)return null;let t=e.user_metadata;if(t)for(let e of $){let s=t[e];if("string"==typeof s&&s.length>0)return s.trim()}for(let t of e.identities??[])if("firebase"===t.provider&&"string"==typeof t.id&&t.id)return t.id.trim();return null}var W=e.i(67034),H=e.i(34582);function z(e,t){return function(){return e.apply(t,arguments)}}let{toString:Q}=Object.prototype,{getPrototypeOf:K}=Object,{iterator:J,toStringTag:G}=Symbol,Y=(t=Object.create(null),e=>{let s=Q.call(e);return t[s]||(t[s]=s.slice(8,-1).toLowerCase())}),X=e=>(e=e.toLowerCase(),t=>Y(t)===e),Z=e=>t=>typeof t===e,{isArray:ee}=Array,et=Z("undefined");function es(e){return null!==e&&!et(e)&&null!==e.constructor&&!et(e.constructor)&&en(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}let ei=X("ArrayBuffer"),ea=Z("string"),en=Z("function"),er=Z("number"),eo=e=>null!==e&&"object"==typeof e,el=e=>{if("object"!==Y(e))return!1;let t=K(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(G in e)&&!(J in e)},ed=X("Date"),ec=X("File"),eh=X("Blob"),eu=X("FileList"),eg="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:e.g,ep=void 0!==eg.FormData?eg.FormData:void 0,em=X("URLSearchParams"),[ef,ey,eb,e_]=["ReadableStream","Request","Response","Headers"].map(X);function ew(e,t,{allOwnKeys:s=!1}={}){let i,a;if(null!=e)if("object"!=typeof e&&(e=[e]),ee(e))for(i=0,a=e.length;i<a;i++)t.call(null,e[i],i,e);else{let a;if(es(e))return;let n=s?Object.getOwnPropertyNames(e):Object.keys(e),r=n.length;for(i=0;i<r;i++)a=n[i],t.call(null,e[a],a,e)}}function ev(e,t){let s;if(es(e))return null;t=t.toLowerCase();let i=Object.keys(e),a=i.length;for(;a-- >0;)if(t===(s=i[a]).toLowerCase())return s;return null}let eC="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:e.g,eS=e=>!et(e)&&e!==eC,eR=(s="u">typeof Uint8Array&&K(Uint8Array),e=>s&&e instanceof s),eU=X("HTMLFormElement"),eI=(({hasOwnProperty:e})=>(t,s)=>e.call(t,s))(Object.prototype),ex=X("RegExp"),eL=(e,t)=>{let s=Object.getOwnPropertyDescriptors(e),i={};ew(s,(s,a)=>{let n;!1!==(n=t(s,a,e))&&(i[a]=n||s)}),Object.defineProperties(e,i)},eM=X("AsyncFunction"),eE=(n="function"==typeof setImmediate,r=en(eC.postMessage),n?setImmediate:r?(o=`axios@${Math.random()}`,l=[],eC.addEventListener("message",({source:e,data:t})=>{e===eC&&t===o&&l.length&&l.shift()()},!1),e=>{l.push(e),eC.postMessage(o,"*")}):e=>setTimeout(e)),eA="u">typeof queueMicrotask?queueMicrotask.bind(eC):void 0!==u.default&&u.default.nextTick||eE,ek={isArray:ee,isArrayBuffer:ei,isBuffer:es,isFormData:e=>{let t;return e&&(ep&&e instanceof ep||en(e.append)&&("formdata"===(t=Y(e))||"object"===t&&en(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){return"u">typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ei(e.buffer)},isString:ea,isNumber:er,isBoolean:e=>!0===e||!1===e,isObject:eo,isPlainObject:el,isEmptyObject:e=>{if(!eo(e)||es(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:ef,isRequest:ey,isResponse:eb,isHeaders:e_,isUndefined:et,isDate:ed,isFile:ec,isReactNativeBlob:e=>!!(e&&void 0!==e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:eh,isRegExp:ex,isFunction:en,isStream:e=>eo(e)&&en(e.pipe),isURLSearchParams:em,isTypedArray:eR,isFileList:eu,forEach:ew,merge:function e(){let{caseless:t,skipUndefined:s}=eS(this)&&this||{},i={},a=(a,n)=>{if("__proto__"===n||"constructor"===n||"prototype"===n)return;let r=t&&ev(i,n)||n;el(i[r])&&el(a)?i[r]=e(i[r],a):el(a)?i[r]=e({},a):ee(a)?i[r]=a.slice():s&&et(a)||(i[r]=a)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&ew(arguments[e],a);return i},extend:(e,t,s,{allOwnKeys:i}={})=>(ew(t,(t,i)=>{s&&en(t)?Object.defineProperty(e,i,{value:z(t,s),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,s,i)=>
1{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),s&&Object.assign(e.prototype,s)},toFlatObject:(e,t,s,i)=>{let a,n,r,o={};if(t=t||{},null==e)return t;do{for(n=(a=Object.getOwnPropertyNames(e)).length;n-- >0;)r=a[n],(!i||i(r,e,t))&&!o[r]&&(t[r]=e[r],o[r]=!0);e=!1!==s&&K(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype)return t},kindOf:Y,kindOfTest:X,endsWith:(e,t,s)=>{e=String(e),(void 0===s||s>e.length)&&(s=e.length),s-=t.length;let i=e.indexOf(t,s);return -1!==i&&i===s},toArray:e=>{if(!e)return null;if(ee(e))return e;let t=e.length;if(!er(t))return null;let s=Array(t);for(;t-- >0;)s[t]=e[t];return s},forEachEntry:(e,t)=>{let s,i=(e&&e[J]).call(e);for(;(s=i.next())&&!s.done;){let i=s.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let s,i=[];for(;null!==(s=e.exec(t));)i.push(s);return i},isHTMLForm:eU,hasOwnProperty:eI,hasOwnProp:eI,reduceDescriptors:eL,freezeMethods:e=>{eL(e,(t,s)=>{if(en(e)&&-1!==["arguments","caller","callee"].indexOf(s))return!1;if(en(e[s])){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},toObjectSet:(e,t)=>{let s={};return(ee(e)?e:String(e).split(t)).forEach(e=>{s[e]=!0}),s},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,s){return t.toUpperCase()+s}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e*=1)?e:t,findKey:ev,global:eC,isContextDefined:eS,isSpecCompliantForm:function(e){return!!(e&&en(e.append)&&"FormData"===e[G]&&e[J])},toJSONObject:e=>{let t=Array(10),s=(e,i)=>{if(eo(e)){if(t.indexOf(e)>=0)return;if(es(e))return e;if(!("toJSON"in e)){t[i]=e;let a=ee(e)?[]:{};return ew(e,(e,t)=>{let n=s(e,i+1);et(n)||(a[t]=n)}),t[i]=void 0,a}}return e};return s(e,0)},isAsyncFn:eM,isThenable:e=>e&&(eo(e)||en(e))&&en(e.then)&&en(e.catch),setImmediate:eE,asap:eA,isIterable:e=>null!=e&&en(e[J])};class eD extends Error{static from(e,t,s,i,a,n){let r=new eD(e.message,t||e.code,s,i,a);return r.cause=e,r.name=e.name,null!=e.status&&null==r.status&&(r.status=e.status),n&&Object.assign(r,n),r}constructor(e,t,s,i,a){super(e),Object.defineProperty(this,"message",{value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),s&&(this.config=s),i&&(this.request=i),a&&(this.response=a,this.status=a.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ek.toJSONObject(this.config),code:this.code,status:this.status}}}eD.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",eD.ERR_BAD_OPTION="ERR_BAD_OPTION",eD.ECONNABORTED="ECONNABORTED",eD.ETIMEDOUT="ETIMEDOUT",eD.ERR_NETWORK="ERR_NETWORK",eD.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",eD.ERR_DEPRECATED="ERR_DEPRECATED",eD.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",eD.ERR_BAD_REQUEST="ERR_BAD_REQUEST",eD.ERR_CANCELED="ERR_CANCELED",eD.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",eD.ERR_INVALID_URL="ERR_INVALID_URL";let eT=eD;function eP(e){return ek.isPlainObject(e)||ek.isArray(e)}function eO(e){return ek.endsWith(e,"[]")?e.slice(0,-2):e}function eN(e,t,s){return e?e.concat(t).map(function(e,t){return e=eO(e),!s&&t?"["+e+"]":e}).join(s?".":""):t}let eF=ek.toFlatObject(ek,{},null,function(e){return/^is[A-Z]/.test(e)}),eq=function(e,t,s){if(!ek.isObject(e))throw TypeError("target must be an object");t=t||new FormData;let i=(s=ek.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!ek.isUndefined(t[e])})).metaTokens,a=s.visitor||d,n=s.dots,r=s.indexes,o=(s.Blob||"u">typeof Blob&&Blob)&&ek.isSpecCompliantForm(t);if(!ek.isFunction(a))throw TypeError("visitor must be a function");function l(e){if(null===e)return"";if(ek.isDate(e))return e.toISOString();if(ek.isBoolean(e))return e.toString();if(!o&&ek.isBlob(e))throw new eT("Blob is not supported. Use a Buffer instead.");return ek.isArrayBuffer(e)||ek.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):W.Buffer.from(e):e}function d(e,s,a){let o=e;if(ek.isReactNative(t)&&ek.isReactNativeBlob(e))return t.append(eN(a,s,n),l(e)),!1;if(e&&!a&&"object"==typeof e)if(ek.endsWith(s,"{}"))s=i?s:s.slice(0,-2),e=JSON.stringify(e);else{var d;
1if(ek.isArray(e)&&(d=e,ek.isArray(d)&&!d.some(eP))||(ek.isFileList(e)||ek.endsWith(s,"[]"))&&(o=ek.toArray(e)))return s=eO(s),o.forEach(function(e,i){ek.isUndefined(e)||null===e||t.append(!0===r?eN([s],i,n):null===r?s:s+"[]",l(e))}),!1}return!!eP(e)||(t.append(eN(a,s,n),l(e)),!1)}let c=[],h=Object.assign(eF,{defaultVisitor:d,convertValue:l,isVisitable:eP});if(!ek.isObject(e))throw TypeError("data must be an object");return!function e(s,i){if(!ek.isUndefined(s)){if(-1!==c.indexOf(s))throw Error("Circular reference detected in "+i.join("."));c.push(s),ek.forEach(s,function(s,n){!0===(!(ek.isUndefined(s)||null===s)&&a.call(t,s,ek.isString(n)?n.trim():n,i,h))&&e(s,i?i.concat(n):[n])}),c.pop()}}(e),t};function ej(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function eB(e,t){this._pairs=[],e&&eq(e,this,t)}let e$=eB.prototype;function eV(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function eW(e,t,s){let i;if(!t)return e;let a=s&&s.encode||eV,n=ek.isFunction(s)?{serialize:s}:s,r=n&&n.serialize;if(i=r?r(t,n):ek.isURLSearchParams(t)?t.toString():new eB(t,n).toString(a)){let t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}e$.append=function(e,t){this._pairs.push([e,t])},e$.toString=function(e){let t=e?function(t){return e.call(this,t,ej)}:ej;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};let eH=class{constructor(){this.handlers=[]}use(e,t,s){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!s&&s.synchronous,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ek.forEach(this.handlers,function(t){null!==t&&e(t)})}},ez={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},eQ="u">typeof URLSearchParams?URLSearchParams:eB,eK="u">typeof FormData?FormData:null,eJ="u">typeof Blob?Blob:null,eG="u">typeof window&&"u">typeof document,eY="object"==typeof navigator&&navigator||void 0,eX=eG&&(!eY||0>["ReactNative","NativeScript","NS"].indexOf(eY.product)),eZ="u">typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,e0=eG&&window.location.href||"http://localhost";e.s(["hasBrowserEnv",0,eG,"hasStandardBrowserEnv",0,eX,"hasStandardBrowserWebWorkerEnv",0,eZ,"navigator",0,eY,"origin",0,e0],57536);let e1={...e.i(57536),isBrowser:!0,classes:{URLSearchParams:eQ,FormData:eK,Blob:eJ},protocols:["http","https","file","blob","url","data"]},e2=function(e){if(ek.isFormData(e)&&ek.isFunction(e.entries)){let t={};return ek.forEachEntry(e,(e,s)=>{!function e(t,s,i,a){let n=t[a++];if("__proto__"===n)return!0;let r=Number.isFinite(+n),o=a>=t.length;return(n=!n&&ek.isArray(i)?i.length:n,o)?ek.hasOwnProp(i,n)?i[n]=[i[n],s]:i[n]=s:(i[n]&&ek.isObject(i[n])||(i[n]=[]),e(t,s,i[n],a)&&ek.isArray(i[n])&&(i[n]=function(e){let t,s,i={},a=Object.keys(e),n=a.length;for(t=0;t<n;t++)i[s=a[t]]=e[s];return i}(i[n]))),!r}(ek.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0]),s,t,0)}),t}return null},e3={transitional:ez,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){let s,i=t.getContentType()||"",a=i.indexOf("application/json")>-1,n=ek.isObject(e);if(n&&ek.isHTMLForm(e)&&(e=new FormData(e)),ek.isFormData(e))return a?JSON.stringify(e2(e)):e;if(ek.isArrayBuffer(e)||ek.isBuffer(e)||ek.isStream(e)||ek.isFile(e)||ek.isBlob(e)||ek.isReadableStream(e))return e;if(ek.isArrayBufferView(e))return e.buffer;if(ek.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(n){if(i.indexOf("application/x-www-form-urlencoded")>-1){var r,o;return(r=e,o=this.formSerializer,eq(r,new e1.classes.URLSearchParams,{visitor:function(e,t,s,i){return e1.isNode&&ek.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...o})).toString()}if((s=ek.isFileList(e))||i.indexOf("multipart/form-data")>-1){let t=this.env&&this.env.FormData;return eq(s?{"files[]":e}
1:e,t&&new t,this.formSerializer)}}if(n||a){t.setContentType("application/json",!1);var l=e;if(ek.isString(l))try{return(0,JSON.parse)(l),ek.trim(l)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(l)}return e}],transformResponse:[function(e){let t=this.transitional||e3.transitional,s=t&&t.forcedJSONParsing,i="json"===this.responseType;if(ek.isResponse(e)||ek.isReadableStream(e))return e;if(e&&ek.isString(e)&&(s&&!this.responseType||i)){let s=t&&t.silentJSONParsing;try{return JSON.parse(e,this.parseReviver)}catch(e){if(!s&&i){if("SyntaxError"===e.name)throw eT.from(e,eT.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:e1.classes.FormData,Blob:e1.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ek.forEach(["delete","get","head","post","put","patch"],e=>{e3.headers[e]={}});let e4=ek.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),e5=Symbol("internals");function e6(e){return e&&String(e).trim().toLowerCase()}function e8(e){return!1===e||null==e?e:ek.isArray(e)?e.map(e8):String(e)}function e7(e,t,s,i,a){if(ek.isFunction(i))return i.call(this,t,s);if(a&&(t=s),ek.isString(t)){if(ek.isString(i))return -1!==t.indexOf(i);if(ek.isRegExp(i))return i.test(t)}}class e9{constructor(e){e&&this.set(e)}set(e,t,s){let i=this;function a(e,t,s){let a=e6(t);if(!a)throw Error("header name must be a non-empty string");let n=ek.findKey(i,a);n&&void 0!==i[n]&&!0!==s&&(void 0!==s||!1===i[n])||(i[n||t]=e8(e))}let n=(e,t)=>ek.forEach(e,(e,s)=>a(e,s,t));if(ek.isPlainObject(e)||e instanceof this.constructor)n(e,t);else{let i;if(ek.isString(e)&&(e=e.trim())&&(i=e,!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(i.trim()))){var r;let s,i,a,o;n((o={},(r=e)&&r.split("\n").forEach(function(e){a=e.indexOf(":"),s=e.substring(0,a).trim().toLowerCase(),i=e.substring(a+1).trim(),!s||o[s]&&e4[s]||("set-cookie"===s?o[s]?o[s].push(i):o[s]=[i]:o[s]=o[s]?o[s]+", "+i:i)}),o),t)}else if(ek.isObject(e)&&ek.isIterable(e)){let s={},i,a;for(let t of e){if(!ek.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[a=t[0]]=(i=s[a])?ek.isArray(i)?[...i,t[1]]:[i,t[1]]:t[1]}n(s,t)}else null!=e&&a(t,e,s)}return this}get(e,t){if(e=e6(e)){let s=ek.findKey(this,e);if(s){let e=this[s];if(!t)return e;if(!0===t){let t,s=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1for(;t=i.exec(e);)s[t[1]]=t[2];return s}if(ek.isFunction(t))return t.call(this,e,s);if(ek.isRegExp(t))return t.exec(e);throw TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=e6(e)){let s=ek.findKey(this,e);return!!(s&&void 0!==this[s]&&(!t||e7(this,this[s],s,t)))}return!1}delete(e,t){let s=this,i=!1;function a(e){if(e=e6(e)){let a=ek.findKey(s,e);a&&(!t||e7(s,s[a],a,t))&&(delete s[a],i=!0)}}return ek.isArray(e)?e.forEach(a):a(e),i}clear(e){let t=Object.keys(this),s=t.length,i=!1;for(;s--;){let a=t[s];(!e||e7(this,this[a],a,e,!0))&&(delete this[a],i=!0)}return i}normalize(e){let t=this,s={};return ek.forEach(this,(i,a)=>{let n=ek.findKey(s,a);if(n){t[n]=e8(i),delete t[a];return}let r=e?a.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,s)=>t.toUpperCase()+s):String(a).trim();r!==a&&delete t[a],t[r]=e8(i),s[r]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return ek.forEach(this,(s,i)=>{null!=s&&!1!==s&&(t[i]=e&&ek.isArray(s)?s.join(", "):s)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let s=new this(e);return t.forEach(e=>s.set(e)),s}static accessor(e){let t=(this[e5]=this[e5]={accessors:{}}).accessors,s=this.prototype;function i(e){let i=e6(e);if(!t[i]){let a;a=ek.toCamelCase(" "+e),["get","set","has"].forEach(t=>{Object.defineProperty(s,t+a,{value:function(s,i,a){return this[t].call(this,e,s,i,a)},configurable:!0})}),t[i]=!0}}return ek.isArray(e)?e.forEach(i):i(e),this}}function te(e,t){let s=this||e3,i=t||s,a=e9.from(i.headers),n=i.data;return ek.forEach(e,function(e){n=e.call(s,n,a.normalize(),t?t.status:void 0)}),a.normalize(),n}function tt(e){return!!(e&&e.__CANCEL__)}e9.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ek.reduceDescriptors(e9.prototype,({value:e},t)=>{let s=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[s]=e}}}),ek.freezeMethods(e9);let ts=class extends eT{constructor(e,t,s){super(null==e?"canceled":e,eT.ERR_CANCELED,t,s),this.name="CanceledError",this.__CANCEL__=!0}};function ti(e,t,s){let i=s.config.validateStatus;!s.status||!i||i(s.status)?e(s):t(new eT("Request failed with status code "+s.status,[eT.ERR_BAD_REQUEST,eT.ERR_BAD_RESPONSE][Math.floor(s.status/100)-4],s.config,s.request,s))}let ta=function(e,t){let s,i=Array(e=e||10),a=Array(e),n=0,r=0;return t=void 0!==t?t:1e3,function(o){let l=Date.now(),d=a[r];s||(s=l),i[n]=o,a[n]=l;let c=r,h=0;for(;c!==n;)h+=i[c++],c%=e;if((n=(n+1)%e)===r&&(r=(r+1)%e),l-s<t)return;let u=d&&l-d;return u?Math.round(1e3*h/u):void 0}},tn=function(e,t){let s,i,a=0,n=1e3/t,r=(t,n=Date.now())=>{a=n,s=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{let t=Date.now(),o=t-a;o>=n?r(e,t):(s=e,i||(i=setTimeout(()=>{i=null,r(s)},n-o)))},()=>s&&r(s)]},tr=(e,t,s=3)=>{let i=0,a=ta(50,250);return tn(s=>{let n=s.loaded,r=s.lengthComputable?s.total:void 0,o=n-i,l=a(o);i=n,e({loaded:n,total:r,progress:r?n/r:void 0,bytes:o,rate:l||void 0,estimated:l&&r&&n<=r?(r-n)/l:void 0,event:s,lengthComputable:null!=r,[t?"download":"upload"]:!0})},s)},to=(e,t)=>{let s=null!=e;return[i=>t[0]({lengthComputable:s,total:e,loaded:i}),t[1]]},tl=e=>(...t)=>ek.asap(()=>e(...t)),td=e1.hasStandardBrowserEnv?(i=new URL(e1.origin),a=e1.navigator&&/(msie|trident)/i.test(e1.navigator.userAgent),e=>(e=new URL(e,e1.origin),i.protocol===e.protocol&&i.host===e.host&&(a||i.port===e.port))):()=>!0,tc=e1.hasStandardBrowserEnv?{write(e,t,s,i,a,n,r){if("u"<typeof document)return;let o=[`${e}=${encodeURIComponent(t)}`];ek.isNumber(s)&&o.push(`expires=${new Date(s).toUTCString()}`),ek.isString(i)&&o.push(`path=${i}`),ek.isString(a)&&o.push(`domain=${a}`),!0===n&&o.push("secure"),ek.isString(r)&&o.push(`SameSite=${r}`),document.cookie=o.join("; ")},read(e){if("u"<typeof document)return null;let t=document.cookie.match(RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function th(e,t,s){let i=!("string"==typeof t&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t));return e&&(i||!1==s)?t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e:t}let tu=e=>e instanceof e9?{...e}:e;function tg(e,t){t=t||{};let s={};function i(e,t,s,i){return ek.isPlainObject(e)&&ek.isPlainObject(t)?ek.merge.call({caseless:i},e,t):ek.isPlainObject(t)?ek.merge({},t):ek.isArray(t)?t.slice():t}function a(e,t,s,a){return ek.isUndefined(t)?ek.isUndefined(e)?void 0:i(void 0,e,s,a):i(e,t,s,a)}function n(e,t){if(!ek.isUndefined(t))return i(void 0,t)}function r(e,t){return ek.isUndefined(t)?ek.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(s,a,n){return n in t?i(s,a):n in e?i(void 0,s):void 0}let l={url:n,method:n,data:n,baseURL:r,transformRequest:r,transformResponse:r,paramsSerializer:r,timeout:r,timeoutMessage:r,withCredentials:r,withXSRFToken:r,adapter:r,responseType:r,xsrfCookieName:r,xsrfHeaderName:r,onUploadProgress:r,onDownloadProgress:r,decompress:r,maxContentLength:r,maxBodyLength:r,beforeRedirect:r,transport:r,httpAgent:r,httpsAgent:r,cancelToken:r,socketPath:r,responseEncoding:r,validateStatus:o,headers:(e,t,s)=>a(tu(e),tu(t),s,!0)};
1return ek.forEach(Object.keys({...e,...t}),function(i){if("__proto__"===i||"constructor"===i||"prototype"===i)return;let n=ek.hasOwnProp(l,i)?l[i]:a,r=n(e[i],t[i],i);ek.isUndefined(r)&&n!==o||(s[i]=r)}),s}let tp=e=>{let t=tg({},e),{data:s,withXSRFToken:i,xsrfHeaderName:a,xsrfCookieName:n,headers:r,auth:o}=t;if(t.headers=r=e9.from(r),t.url=eW(th(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&r.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),ek.isFormData(s)){if(e1.hasStandardBrowserEnv||e1.hasStandardBrowserWebWorkerEnv)r.setContentType(void 0);else if(ek.isFunction(s.getHeaders)){let e=s.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,s])=>{t.includes(e.toLowerCase())&&r.set(e,s)})}}if(e1.hasStandardBrowserEnv&&(i&&ek.isFunction(i)&&(i=i(t)),i||!1!==i&&td(t.url))){let e=a&&n&&tc.read(n);e&&r.set(a,e)}return t},tm="u">typeof XMLHttpRequest&&function(e){return new Promise(function(t,s){var i;let a,n,r,o,l,d,c=tp(e),h=c.data,u=e9.from(c.headers).normalize(),{responseType:g,onUploadProgress:p,onDownloadProgress:m}=c;function f(){o&&o(),l&&l(),c.cancelToken&&c.cancelToken.unsubscribe(a),c.signal&&c.signal.removeEventListener("abort",a)}let y=new XMLHttpRequest;function b(){if(!y)return;let i=e9.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders());ti(function(e){t(e),f()},function(e){s(e),f()},{data:g&&"text"!==g&&"json"!==g?y.response:y.responseText,status:y.status,statusText:y.statusText,headers:i,config:e,request:y}),y=null}y.open(c.method.toUpperCase(),c.url,!0),y.timeout=c.timeout,"onloadend"in y?y.onloadend=b:y.onreadystatechange=function(){!y||4!==y.readyState||(0!==y.status||y.responseURL&&0===y.responseURL.indexOf("file:"))&&setTimeout(b)},y.onabort=function(){y&&(s(new eT("Request aborted",eT.ECONNABORTED,e,y)),y=null)},y.onerror=function(t){let i=new eT(t&&t.message?t.message:"Network Error",eT.ERR_NETWORK,e,y);i.event=t||null,s(i),y=null},y.ontimeout=function(){let t=c.timeout?"timeout of "+c.timeout+"ms exceeded":"timeout exceeded",i=c.transitional||ez;c.timeoutErrorMessage&&(t=c.timeoutErrorMessage),s(new eT(t,i.clarifyTimeoutError?eT.ETIMEDOUT:eT.ECONNABORTED,e,y)),y=null},void 0===h&&u.setContentType(null),"setRequestHeader"in y&&ek.forEach(u.toJSON(),function(e,t){y.setRequestHeader(t,e)}),ek.isUndefined(c.withCredentials)||(y.withCredentials=!!c.withCredentials),g&&"json"!==g&&(y.responseType=c.responseType),m&&([r,l]=tr(m,!0),y.addEventListener("progress",r)),p&&y.upload&&([n,o]=tr(p),y.upload.addEventListener("progress",n),y.upload.addEventListener("loadend",o)),(c.cancelToken||c.signal)&&(a=t=>{y&&(s(!t||t.type?new ts(null,e,y):t),y.abort(),y=null)},c.cancelToken&&c.cancelToken.subscribe(a),c.signal&&(c.signal.aborted?a():c.signal.addEventListener("abort",a)));let _=(i=c.url,(d=/^([-+\w]{1,25})(:?\/\/|:)/.exec(i))&&d[1]||"");_&&-1===e1.protocols.indexOf(_)?s(new eT("Unsupported protocol "+_+":",eT.ERR_BAD_REQUEST,e)):y.send(h||null)})},tf=function*(e,t){let s,i=e.byteLength;if(!t||i<t)return void(yield e);let a=0;for(;a<i;)s=a+t,yield e.slice(a,s),a=s},ty=async function*(e,t){for await(let s of tb(e))yield*tf(s,t)},tb=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);let t=e.getReader();try{for(;;){let{done:e,value:s}=await t.read();if(e)break;yield s}}finally{await t.cancel()}},t_=(e,t,s,i)=>{let a,n=ty(e,t),r=0,o=e=>{!a&&(a=!0,i&&i(e))};return new ReadableStream({async pull(e){try{let{done:t,value:i}=await n.next();if(t){o(),e.close();return}let a=i.byteLength;if(s){let e=r+=a;s(e)}e.enqueue(new Uint8Array(i))}catch(e){throw o(e),e}},cancel:e=>(o(e),n.return())},{highWaterMark:2})},{isFunction:tw}=ek,tv=(({Request:e,Response:t})=>({Request:e,Response:t}))(ek.global),{ReadableStream:tC,TextEncoder:tS}=ek.global,tR=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},tU=e=>{let t,{fetch:s,Request:i,Response:a}=e=ek.merge.call({skipUndefined:!0},tv,e),n=s?tw(s):"function"==typeof fetch,r=tw(i),o=tw(a);if(!n)return!1;let l=n&&tw(tC),d=n&&("function"==typeof tS?(t=new tS,e=>t.encode(e)):async e=>new Uint8Array(await new i(e).arrayBuffer())),c=r&&l&&tR(()=>{let e=!1,t=new i(e1.origin,{body:new tC,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),h=o&&l&&tR(()=>
1ek.isReadableStream(new a("").body)),u={stream:h&&(e=>e.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{u[e]||(u[e]=(t,s)=>{let i=t&&t[e];if(i)return i.call(t);throw new eT(`Response type '${e}' is not supported`,eT.ERR_NOT_SUPPORT,s)})});let g=async e=>{if(null==e)return 0;if(ek.isBlob(e))return e.size;if(ek.isSpecCompliantForm(e)){let t=new i(e1.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ek.isArrayBufferView(e)||ek.isArrayBuffer(e)?e.byteLength:(ek.isURLSearchParams(e)&&(e+=""),ek.isString(e))?(await d(e)).byteLength:void 0},p=async(e,t)=>{let s=ek.toFiniteNumber(e.getContentLength());return null==s?g(t):s};return async e=>{let t,{url:n,method:o,data:l,signal:d,cancelToken:g,timeout:m,onDownloadProgress:f,onUploadProgress:y,responseType:b,headers:_,withCredentials:w="same-origin",fetchOptions:v}=tp(e),C=s||fetch;b=b?(b+"").toLowerCase():"text";let S=((e,t)=>{let{length:s}=e=e?e.filter(Boolean):[];if(t||s){let s,i=new AbortController,a=function(e){if(!s){s=!0,r();let t=e instanceof Error?e:this.reason;i.abort(t instanceof eT?t:new ts(t instanceof Error?t.message:t))}},n=t&&setTimeout(()=>{n=null,a(new eT(`timeout of ${t}ms exceeded`,eT.ETIMEDOUT))},t),r=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(a):e.removeEventListener("abort",a)}),e=null)};e.forEach(e=>e.addEventListener("abort",a));let{signal:o}=i;return o.unsubscribe=()=>ek.asap(r),o}})([d,g&&g.toAbortSignal()],m),R=null,U=S&&S.unsubscribe&&(()=>{S.unsubscribe()});
1try{if(y&&c&&"get"!==o&&"head"!==o&&0!==(t=await p(_,l))){let e,s=new i(n,{method:"POST",body:l,duplex:"half"});if(ek.isFormData(l)&&(e=s.headers.get("content-type"))&&_.setContentType(e),s.body){let[e,i]=to(t,tr(tl(y)));l=t_(s.body,65536,e,i)}}ek.isString(w)||(w=w?"include":"omit");let s=r&&"credentials"in i.prototype,d={...v,signal:S,method:o.toUpperCase(),headers:_.normalize().toJSON(),body:l,duplex:"half",credentials:s?w:void 0};R=r&&new i(n,d);let g=await (r?C(R,v):C(n,d)),m=h&&("stream"===b||"response"===b);if(h&&(f||m&&U)){let e={};["status","statusText","headers"].forEach(t=>{e[t]=g[t]});let t=ek.toFiniteNumber(g.headers.get("content-length")),[s,i]=f&&to(t,tr(tl(f),!0))||[];g=new a(t_(g.body,65536,s,()=>{i&&i(),U&&U()}),e)}b=b||"text";let I=await u[ek.findKey(u,b)||"text"](g,e);return!m&&U&&U(),await new Promise((t,s)=>{ti(t,s,{data:I,headers:e9.from(g.headers),status:g.status,statusText:g.statusText,config:e,request:R})})}catch(t){if(U&&U(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new eT("Network Error",eT.ERR_NETWORK,e,R,t&&t.response),{cause:t.cause||t});throw eT.from(t,t&&t.code,e,R,t&&t.response)}}},tI=new Map,tx=e=>{let t=e&&e.env||{},{fetch:s,Request:i,Response:a}=t,n=[i,a,s],r=n.length,o,l,d=tI;for(;r--;)o=n[r],void 0===(l=d.get(o))&&d.set(o,l=r?new Map:tU(t)),d=l;return l};tx();let tL={http:null,xhr:tm,fetch:{get:tx}};ek.forEach(tL,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});let tM=e=>`- ${e}`,tE=e=>ek.isFunction(e)||null===e||!1===e,tA=function(e,t){let s,i,{length:a}=e=ek.isArray(e)?e:[e],n={};for(let r=0;r<a;r++){let a;if(i=s=e[r],!tE(s)&&void 0===(i=tL[(a=String(s)).toLowerCase()]))throw new eT(`Unknown adapter '${a}'`);if(i&&(ek.isFunction(i)||(i=i.get(t))))break;n[a||"#"+r]=i}if(!i){let e=Object.entries(n).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new eT("There is no suitable adapter to dispatch the request "+(a?e.length>1?"since :\n"+e.map(tM).join("\n"):" "+tM(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function tk(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ts(null,e)}function tD(e){return tk(e),e.headers=e9.from(e.headers),e.data=te.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),tA(e.adapter||e3.adapter,e)(e).then(function(t){return tk(e),t.data=te.call(e,e.transformResponse,t),t.headers=e9.from(t.headers),t},function(t){return!tt(t)&&(tk(e),t&&t.response&&(t.response.data=te.call(e,e.transformResponse,t.response),t.response.headers=e9.from(t.response.headers))),Promise.reject(t)})}let tT="1.13.6",tP={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{tP[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});let tO={};tP.transitional=function(e,t,s){function i(e,t){return"[Axios v"+tT+"] Transitional option '"+e+"'"+t+(s?". "+s:"")}return(s,a,n)=>{if(!1===e)throw new eT(i(a," has been removed"+(t?" in "+t:"")),eT.ERR_DEPRECATED);return t&&!tO[a]&&(tO[a]=!0,console.warn(i(a," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(s,a,n)}},tP.spelling=function(e){return(t,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};let tN=function(e,t,s){if("object"!=typeof e)throw new eT("options must be an object",eT.ERR_BAD_OPTION_VALUE);let i=Object.keys(e),a=i.length;for(;a-- >0;){let n=i[a],r=t[n];if(r){let t=e[n],s=void 0===t||r(t,n,e);if(!0!==s)throw new eT("option "+n+" must be "+s,eT.ERR_BAD_OPTION_VALUE);continue}if(!0!==s)throw new eT("Unknown option "+n,eT.ERR_BAD_OPTION)}};class tF{constructor(e){this.defaults=e||{},this.interceptors={request:new eH,response:new eH}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=Error();let s=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?s&&!String(e.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+s):e.stack=s}catch(e){}}throw e}}_request(e,t){let s,i;"string"==typeof e?(t=t||{}).url=e:t=e||{};let{transitional:a,paramsSerializer:n,headers:r}=t=tg(this.defaults,t);void 0!==a&&tN(a,{silentJSONParsing:tP.transitional(tP.boolean),forcedJSONParsing:tP.transitional(tP.boolean),clarifyTimeoutError:tP.transitional(tP.boolean),legacyInterceptorReqResOrdering:tP.transitional(tP.boolean)}
1,!1),null!=n&&(ek.isFunction(n)?t.paramsSerializer={serialize:n}:tN(n,{encode:tP.function,serialize:tP.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),tN(t,{baseUrl:tP.spelling("baseURL"),withXsrfToken:tP.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&ek.merge(r.common,r[t.method]);r&&ek.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=e9.concat(o,r);let l=[],d=!0;this.interceptors.request.forEach(function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;d=d&&e.synchronous;let s=t.transitional||ez;s&&s.legacyInterceptorReqResOrdering?l.unshift(e.fulfilled,e.rejected):l.push(e.fulfilled,e.rejected)});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let h=0;if(!d){let e=[tD.bind(this),void 0];for(e.unshift(...l),e.push(...c),i=e.length,s=Promise.resolve(t);h<i;)s=s.then(e[h++],e[h++]);return s}i=l.length;let u=t;for(;h<i;){let e=l[h++],t=l[h++];try{u=e(u)}catch(e){t.call(this,e);break}}try{s=tD.call(this,u)}catch(e){return Promise.reject(e)}for(h=0,i=c.length;h<i;)s=s.then(c[h++],c[h++]);return s}getUri(e){return eW(th((e=tg(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}
1ek.forEach(["delete","get","head","options"],function(e){tF.prototype[e]=function(t,s){return this.request(tg(s||{},{method:e,url:t,data:(s||{}).data}))}}),ek.forEach(["post","put","patch"],function(e){function t(t){return function(s,i,a){return this.request(tg(a||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}tF.prototype[e]=t(),tF.prototype[e+"Form"]=t(!0)});class tq{constructor(e){let t;if("function"!=typeof e)throw TypeError("executor must be a function.");this.promise=new Promise(function(e){t=e});const s=this;this.promise.then(e=>{if(!s._listeners)return;let t=s._listeners.length;for(;t-- >0;)s._listeners[t](e);s._listeners=null}),this.promise.then=e=>{let t,i=new Promise(e=>{s.subscribe(e),t=e}).then(e);return i.cancel=function(){s.unsubscribe(t)},i},e(function(e,i,a){s.reason||(s.reason=new ts(e,i,a),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new tq(function(t){e=t}),cancel:e}}}let tj={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,Parti
1alContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(tj).forEach(([e,t])=>{tj[t]=e});let tB=function e(t){let s=new tF(t),i=z(tF.prototype.request,s);return ek.extend(i,tF.prototype,s,{allOwnKeys:!0}),ek.extend(i,s,null,{allOwnKeys:!0}),i.create=function(s){return e(tg(t,s))},i}(e3);tB.Axios=tF,tB.CanceledError=ts,tB.CancelToken=tq,tB.isCancel=tt,tB.VERSION=tT,tB.toFormData=eq,tB.AxiosError=eT,tB.Cancel=tB.CanceledError,tB.all=function(e){return Promise.all(e)},tB.spread=function(e){return function(t){return e.apply(null,t)}},tB.isAxiosError=function(e){return ek.isObject(e)&&!0===e.isAxiosError},tB.mergeConfig=tg,tB.AxiosHeaders=e9,tB.formToJSON=e=>e2(ek.isHTMLForm(e)?new FormData(e):e),tB.getAdapter=tA,tB.HttpStatusCode=tj,tB.default=tB;var t$=e.i(3765);let tV="numeric",tW="ascii",tH="alpha",tz="asciinumeric",tQ="alphanumeric",tK="domain",tJ="emoji",tG="whitespace";function tY(e,t,s){for(let i in t[tV]&&(t[tz]=!0,t[tQ]=!0),t[tW]&&(t[tz]=!0,t[tH]=!0),t[tz]&&(t[tQ]=!0),t[tH]&&(t[tQ]=!0),t[tQ]&&(t[tK]=!0),t[tJ]&&(t[tK]=!0),t){let t=(i in s||(s[i]=[]),s[i]);0>t.indexOf(e)&&t.push(e)}}function tX(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}tX.groups={},tX.prototype={accepts(){return!!this.t},go(e){let t=this.j[e];if(t)return t;for(let t=0;t<this.jr.length;t++){let s=this.jr[t][0],i=this.jr[t][1];if(i&&s.test(e))return i}return this.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,s,i){for(let a=0;a<e.length;a++)this.tt(e[a],t,s,i)},tr(e,t,s,i){let a;return i=i||tX.groups,t&&t.j?a=t:(a=new tX(t),s&&i&&tY(t,s,i)),this.jr.push([e,a]),a},ts(e,t,s,i){let a=this,n=e.length;if(!n)return a;for(let t=0;t<n-1;t++)a=a.tt(e[t]);return a.tt(e[n-1],t,s,i)},tt(e,t,s,i){if(i=i||tX.groups,t&&t.j)return this.j[e]=t,t;let a,n=this.go(e);return n?(Object.assign((a=new tX).j,n.j),a.jr.push.apply(a.jr,n.jr),a.jd=n.jd,a.t=n.t):a=new tX,t&&(i&&(a.t&&"string"==typeof a.t?tY(t,Object.assign(function(e,t){let s={};for(let i in t)t[i].indexOf(e)>=0&&(s[i]=!0);return s}(a.t,i),s),i):s&&tY(t,s,i)),a.t=t),this.j[e]=a,a}};let tZ=(e,t,s,i,a)=>e.ta(t,s,i,a),t0=(e,t,s,i,a)=>e.tr(t,s,i,a),t1=(e,t,s,i,a)=>e.ts(t,s,i,a),t2=(e,t,s,i,a)=>e.tt(t,s,i,a),t3="WORD",t4="UWORD",t5="ASCIINUMERICAL",t6="ALPHANUMERICAL",t8="LOCALHOST",t7="UTLD",t9="SCHEME",se="SLASH_SCHEME",st="OPENBRACE",ss="CLOSEBRACE",si="OPENBRACKET",sa="CLOSEBRACKET",sn="OPENPAREN",sr="CLOSEPAREN",so="OPENANGLEBRACKET",sl="CLOSEANGLEBRACKET",sd="FULLWIDTHLEFTPAREN",sc="FULLWIDTHRIGHTPAREN",sh="LEFTCORNERBRACKET",su="RIGHTCORNERBRACKET",sg="LEFTWHITECORNERBRACKET",sp="RIGHTWHITECORNERBRACKET",sm="FULLWIDTHLESSTHAN",sf="FULLWIDTHGREATERTHAN",sy="AMPERSAND",sb="APOSTROPHE",s_="ASTERISK",sw="BACKSLASH",sv="BACKTICK",sC="CARET",sS="COLON",sR="COMMA",sU="DOLLAR",sI="EQUALS",sx="EXCLAMATION",sL="HYPHEN",sM="PERCENT",sE="PIPE",sA="PLUS",sk="POUND",sD="QUERY",sT="QUOTE",sP="FULLWIDTHMIDDLEDOT",sO="SEMI",sN="SLASH",sF="TILDE",sq="UNDERSCORE",sj="EMOJI";var sB=Object.freeze({__proto__:null,ALPHANUMERICAL:t6,AMPERSAND:sy,APOSTROPHE:sb,ASCIINUMERICAL:t5,ASTERISK:s_,AT:"AT",BACKSLASH:sw,BACKTICK:sv,CARET:sC,CLOSEANGLEBRACKET:sl,CLOSEBRACE:ss,CLOSEBRACKET:sa,CLOSEPAREN:sr,COLON:sS,COMMA:sR,DOLLAR:sU,DOT:"DOT",EMOJI:sj,EQUALS:sI,EXCLAMATION:sx,FULLWIDTHGREATERTHAN:sf,FULLWIDTHLEFTPAREN:sd,FULLWIDTHLESSTHAN:sm,FULLWIDTHMIDDLEDOT:sP,FULLWIDTHRIGHTPAREN:sc,HYPHEN:sL,LEFTCORNERBRACKET:sh,LEFTWHITECORNERBRACKET:sg,
1LOCALHOST:t8,NL:"NL",NUM:"NUM",OPENANGLEBRACKET:so,OPENBRACE:st,OPENBRACKET:si,OPENPAREN:sn,PERCENT:sM,PIPE:sE,PLUS:sA,POUND:sk,QUERY:sD,QUOTE:sT,RIGHTCORNERBRACKET:su,RIGHTWHITECORNERBRACKET:sp,SCHEME:t9,SEMI:sO,SLASH:sN,SLASH_SCHEME:se,SYM:"SYM",TILDE:sF,TLD:"TLD",UNDERSCORE:sq,UTLD:t7,UWORD:t4,WORD:t3,WS:"WS"});let s$=/[a-z]/,sV=/\p{L}/u,sW=/\p{Emoji}/u,sH=/\d/,sz=/\s/,sQ=null,sK=null;function sJ(e,t){let s=function(e){let t=[],s=e.length,i=0;for(;i<s;){let a,n=e.charCodeAt(i),r=n<55296||n>56319||i+1===s||(a=e.charCodeAt(i+1))<56320||a>57343?e[i]:e.slice(i,i+2);t.push(r),i+=r.length}return t}(t.replace(/[A-Z]/g,e=>e.toLowerCase())),i=s.length,a=[],n=0,r=0;for(;r<i;){let o=e,l=null,d=0,c=null,h=-1,u=-1;for(;r<i&&(l=o.go(s[r]));)(o=l).accepts()?(h=0,u=0,c=o):h>=0&&(h+=s[r].length,u++),d+=s[r].length,n+=s[r].length,r++;n-=h,r-=u,d-=h,a.push({t:c.t,v:t.slice(n-d,n),s:n-d,e:n})}return a}function sG(e,t,s,i,a){let n,r=t.length;for(let s=0;s<r-1;s++){let r=t[s];e.j[r]?n=e.j[r]:((n=new tX(i)).jr=a.slice(),e.j[r]=n),e=n}return(n=new tX(s)).jr=a.slice(),e.j[t[r-1]]=n,n}function sY(e){let t=[],s=[],i=0;for(;i<e.length;){let a=0;for(;"0123456789".indexOf(e[i+a])>=0;)a++;if(a>0){t.push(s.join(""));for(let t=parseInt(e.substring(i,i+a),10);t>0;t--)s.pop();i+=a}else s.push(e[i]),i++}return t}let sX={defaultProtocol:"http",events:null,format:s0,formatHref:s0,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function sZ(e,t=null){let s=Object.assign({},sX);e&&(s=Object.assign(s,e instanceof sZ?e.o:e));let i=s.ignoreTags,a=[];for(let e=0;e<i.length;e++)a.push(i[e].toUpperCase());this.o=s,t&&(this.defaultRender=t),this.ignoreTags=a}function s0(e){return e}function s1(e,t){this.t="token",this.v=e,this.tk=t}function s2(e,t){class s extends s1{constructor(t,s){super(t,s),this.t=e}}for(let e in t)s.prototype[e]=t[e];return s.t=e,s}sZ.prototype={o:sX,ignoreTags:[],defaultRender:e=>e,check(e){return this.get("validate",e.toString(),e)},get(e,t,s){let i=null!=t,a=this.o[e];return a&&("object"==typeof a?"function"==typeof(a=s.t in a?a[s.t]:sX[e])&&i&&(a=a(t,s)):"function"==typeof a&&i&&(a=a(t,s.t,s))),a},getObj(e,t,s){let i=this.o[e];return"function"==typeof i&&null!=t&&(i=i(t,s.t,s)),i},render(e){let t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}},s1.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),s=e.get("truncate",t,this),i=e.get("format",t,this);return s&&i.length>s?i.substring(0,s)+"…":i},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=sX.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){let t=this.toHref(e.get("defaultProtocol")),s=e.get("formatHref",t,this),i=e.get("tagName",t,this),a=this.toFormattedString(e),n={},r=e.get("className",t,this),o=e.get("target",t,this),l=e.get("rel",t,this),d=e.getObj("attributes",t,this),c=e.getObj("events",t,this);return n.href=s,r&&(n.class=r),o&&(n.target=o),l&&(n.rel=l),d&&Object.assign(n,d),{tagName:i,attributes:n,content:a,eventListeners:c}}};let s3=s2("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),s4=s2("text"),s5=s2("nl"),s6=s2("url",{isLink:!0,toHref(e=sX.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){let e=this.tk;return e.length>=2&&e[0].t!==t8&&e[1].t===sS}}),s8=e=>new tX(e);function s7(e,t,s){let i=s[0].s,a=s[s.length-1].e;return new e(t.slice(i,a),s)}let s9={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function ie(e){return s9.initialized||function(){s9.scanner=function(e=[]){let t={};tX.groups=t;let s=new tX;null==sQ&&(sQ=sY("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2
1ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==sK&&(sK=sY("ελ1υ2бг1ел3дети4ею2католик6ом3мÐ
1ºÐ´2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3Õ°Õ¡Õµ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1ì»´2삼성2한국2")),t2(s,"'",sb),t2(s,"{",st),t2(s,"}",ss),t2(s,"[",si),t2(s,"]",sa),t2(s,"(",sn),t2(s,")",sr),t2(s,"<",so),t2(s,">",sl),t2(s,"(",sd),t2(s,")",sc),t2(s,"「",sh),t2(s,"」",su),t2(s,"『",sg),t2(s,"』",sp),t2(s,"<",sm),t2(s,">",sf),t2(s,"&",sy),t2(s,"*",s_),t2(s,"@","AT"),t2(s,"`",sv),t2(s,"^",sC),t2(s,":",sS),t2(s,",",sR),t2(s,"$",sU),t2(s,".","DOT"),t2(s,"=",sI),t2(s,"!",sx),t2(s,"-",sL),t2(s,"%",sM),t2(s,"|",sE),t2(s,"+",sA),t2(s,"#",sk),t2(s,"?",sD),t2(s,'"',sT),t2(s,"/",sN),t2(s,";",sO),t2(s,"~",sF),t2(s,"_",sq),t2(s,"\\",sw),t2(s,"・",sP);let i=t0(s,sH,"NUM",{[tV]:!0});t0(i,sH,i);let a=t0(i,s$,t5,{[tz]:!0}),n=t0(i,sV,t6,{[tQ]:!0}),r=t0(s,s$,t3,{[tW]:!0});t0(r,sH,a),t0(r,s$,r),t0(a,sH,a),t0(a,s$,a);let o=t0(s,sV,t4,{[tH]:!0});t0(o,s$),t0(o,sH,n),t0(o,sV,o),t0(n,sH,n),t0(n,s$),t0(n,sV,n);let l=t2(s,"\n","NL",{[tG]:!0}),d=t2(s,"\r","WS",{[tG]:!0}),c=t0(s,sz,"WS",{[tG]:!0});t2(s,"",c),t2(d,"\n",l),t2(d,"",c),t0(d,sz,c),t2(c,"\r"),t2(c,"\n"),t0(c,sz,c),t2(c,"",c);let h=t0(s,sW,sj,{[tJ]:!0});t2(h,"#"),t0(h,sW,h),t2(h,"️",h);let u=t2(h,"‍");t2(u,"#"),t0(u,sW,h);let g=[[s$,r],[sH,a]],p=[[s$,null],[sV,o],[sH,n]];for(let e=0;e<sQ.length;e++)sG(s,sQ[e],"TLD",t3,g);for(let e=0;e<sK.length;e++)sG(s,sK[e],t7,t4,p);tY("TLD",{tld:!0,ascii:!0},t),tY(t7,{utld:!0,alpha:!0},t),sG(s,"file",t9,t3,g),sG(s,"mailto",t9,t3,g),sG(s,"http",se,t3,g),sG(s,"https",se,t3,g),sG(s,"ftp",se,t3,g),sG(s,"ftps",se,t3,g),tY(t9,{scheme:!0,ascii:!0},t),tY(se,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let i=e[t][0],a=e[t][1]?{scheme:!0}:{slashscheme:!0};i.indexOf("-")>=0?a[tK]=!0:s$.test(i)?sH.test(i)?a[tz]=!0:a[tW]=!0:a[tV]=!0,t1(s,i,i,a)}return t1(s,"localhost",t8,{ascii:!0}),s.jd=new tX("SYM"),{start:s,tokens:Object.assign({groups:t},sB)}}(s9.customSchemes);for(let e=0;e<s9.tokenQueue.length;e++)s9.tokenQueue[e][1]({scanner:s9.scanner});s9.parser=function({groups:e}){let t=e.domain.concat([sy,s_,"AT",sw,sv,sC,sU,sI,sL,"NUM",sM,sE,sA,sk,sN,"SYM",sF,sq]),s=[sb,sS,sR,"DOT",sx,sM,sD,sT,sO,so,sl,st,ss,sa,si,sn,sr,sd,sc,sh,su,sg,sp,sm,sf],i=[sy,sb,s_,sw,sv,sC,sU,sI,sL,st,ss,sM,sE,sA,sk,sD,sN,"SYM",sF,sq],a=s8(),n=t2(a,sF);tZ(n,i,n),tZ(n,e.domain,n);let r=s8(),o=s8(),l=s8();tZ(a,e.domain,r),tZ(a,e.scheme,o),tZ(a,e.slashscheme,l),tZ(r,i,n),tZ(r,e.domain,r);let d=t2(r,"AT");t2(n,"AT",d),t2(o,"AT",d),t2(l,"AT",d);let c=t2(n,"DOT");tZ(c,i,n),tZ(c,e.domain,n);let h=s8();tZ(d,e.domain,h),tZ(h,e.domain,h);let u=t2(h,"DOT");tZ(u,e.domain,h);let g=s8(s3);tZ(u,e.tld,g),tZ(u,e.utld,g),t2(d,t8,g);let p=t2(h,sL);t2(p,sL,p),tZ(p,e.domain,h),tZ(g,e.domain,h),t2(g,"DOT",u),t2(g,sL,p),tZ(t2(g,sS),e.numeric,s3);let m=t2(r,sL),f=t2(r,"DOT");t2(m,sL,m),tZ(m,e.domain,r),tZ(f,i,n),tZ(f,e.domain,r);let y=s8(s6);tZ(f,e.tld,y),tZ(f,e.utld,y),tZ(y,e.domain,r),tZ(y,i,n),t2(y,"DOT",f),t2(y,sL,m),t2(y,"AT",d);let b=t2(y,sS),_=s8(s6);tZ(b,e.numeric,_);let w=s8(s6),v=s8();
1tZ(w,t,w),tZ(w,s,v),tZ(v,t,w),tZ(v,s,v),t2(y,sN,w),t2(_,sN,w);let C=t2(o,sS),S=t2(l,sS),R=t2(S,sN),U=t2(R,sN);tZ(o,e.domain,r),t2(o,"DOT",f),t2(o,sL,m),tZ(l,e.domain,r),t2(l,"DOT",f),t2(l,sL,m),tZ(C,e.domain,w),t2(C,sN,w),t2(C,sD,w),tZ(U,e.domain,w),tZ(U,t,w),t2(U,sN,w);let I=[[st,ss],[si,sa],[sn,sr],[so,sl],[sd,sc],[sh,su],[sg,sp],[sm,sf]];for(let e=0;e<I.length;e++){let[i,a]=I[e],n=t2(w,i);t2(v,i,n),t2(n,a,w);let r=s8(s6);tZ(n,t,r);let o=s8();tZ(n,s),tZ(r,t,r),tZ(r,s,o),tZ(o,t,r),tZ(o,s,o),t2(r,a,w),t2(o,a,w)}return t2(a,t8,y),t2(a,"NL",s5),{start:a,tokens:sB}}(s9.scanner.tokens);for(let e=0;e<s9.pluginQueue.length;e++)s9.pluginQueue[e][1]({scanner:s9.scanner,parser:s9.parser});s9.initialized=!0}(),function(e,t,s){let i=s.length,a=0,n=[],r=[];for(;a<i;){let o=e,l=null,d=null,c=0,h=null,u=-1;for(;a<i&&!(l=o.go(s[a].t));)r.push(s[a++]);for(;a<i&&(d=l||o.go(s[a].t));)l=null,(o=d).accepts()?(u=0,h=o):u>=0&&u++,a++,c++;if(u<0)(a-=c)<i&&(r.push(s[a]),a++);else{r.length>0&&(n.push(s7(s4,t,r)),r=[]),a-=u,c-=u;let e=h.t,i=s.slice(a-c,a);n.push(s7(e,t,i))}}return r.length>0&&n.push(s7(s4,t,r)),n}(s9.parser.start,e,sJ(s9.scanner.start,e))}function it(e,t=null,s=null){if(t&&"object"==typeof t){if(s)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);s=t,t=null}let i=new sZ(s),a=ie(e),n=[];for(let e=0;e<a.length;e++){let s=a[e];s.isLink&&(!t||s.t===t)&&i.check(s)&&n.push(s.toFormattedObject(i))}return n}ie.scan=sJ,e.s(["find",0,it,"test",0,function(e,t=null){let s=ie(e);return 1===s.length&&s[0].isLink&&(!t||s[0].t===t)}],53364);var is=null;let ii=is="u">typeof WebSocket?WebSocket:"u">typeof MozWebSocket?MozWebSocket:e.g.WebSocket||e.g.MozWebSocket,{Axios:ia,AxiosError:ir,CanceledError:io,isCancel:il,CancelToken:id,VERSION:ic,all:ih,Cancel:iu,isAxiosError:ig,spread:ip,toFormData:im,AxiosHeaders:iy,HttpStatusCode:ib,formToJSON:i_,getAdapter:iw,mergeConfig:iv}=tB;var iC=Object.create,iS=Object.defineProperty,iR=Object.getOwnPropertyDescriptor,iU=Object.getOwnPropertyNames,iI=Object.getPrototypeOf,ix=Object.prototype.hasOwnProperty,iL=(e,t)=>function(){return t||(0,e[iU(e)[0]])((t={exports:{}}).exports,t),t.exports},iM=(e,t,s)=>(s=null!=e?iC(iI(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of iU(t))ix.call(e,a)||a===s||iS(e,a,{get:()=>t[a],enumerable:!(i=iR(t,a))||i.enumerable});return e})(!t&&e&&e.__esModule?s:iS(s,"default",{value:e,enumerable:!0}),e)),iE=iL({"(disabled):https"(){}}),iA=iL({"(disabled):node_modules/jsonwebtoken/index.js"(){}}),ik=iL({"(disabled):crypto"(){}});function iD(e){return"string"==typeof e}var iT=class{constructor(e,t,s){this.client=e,this.id=t,this.data=s}
1async create(){let e={id:this.id,message_template:this.data?.message_template,segment_ids:this.data?.segment_ids,sender_id:this.data?.sender_id,sender_mode:this.data?.sender_mode,sender_visibility:this.data?.sender_visibility,channel_template:this.data?.channel_template,create_channels:this.data?.create_channels,show_channels:this.data?.show_channels,description:this.data?.description,name:this.data?.name,skip_push:this.data?.skip_push,skip_webhook:this.data?.skip_webhook,user_ids:this.data?.user_ids},t=await this.client.createCampaign(e);return this.id=t.campaign.id,this.data=t.campaign,t}verifyCampaignId(){if(!this.id)throw Error("Campaign id is missing. Either create the campaign using campaign.create() or set the id during instantiation - const campaign = client.campaign(id)")}async start(e){return this.verifyCampaignId(),await this.client.startCampaign(this.id,e)}update(e){return this.verifyCampaignId(),this.client.updateCampaign(this.id,e)}async delete(){return this.verifyCampaignId(),await this.client.deleteCampaign(this.id)}stop(){return this.verifyCampaignId(),this.client.stopCampaign(this.id)}get(e){return this.verifyCampaignId(),this.client.getCampaign(this.id,e)}},iP=class{constructor(e){this.client=e}async addMembers(e,t){return await this.client.updateChannelsBatch({operation:"addMembers",filter:e,members:t})}async removeMembers(e,t){return await this.client.updateChannelsBatch({operation:"removeMembers",filter:e,members:t})}async inviteMembers(e,t){return await this.client.updateChannelsBatch({operation:"inviteMembers",filter:e,members:t})}async addModerators(e,t){return await this.client.updateChannelsBatch({operation:"addModerators",filter:e,members:t})}async demoteModerators(e,t){return await this.client.updateChannelsBatch({operation:"demoteModerators",filter:e,members:t})}async assignRoles(e,t){return await this.client.updateChannelsBatch({operation:"assignRoles",filter:e,members:t})}async hide(e){return await this.client.updateChannelsBatch({operation:"hide",filter:e})}async show(e){return await this.client.updateChannelsBatch({operation:"show",filter:e})}async archive(e){return await this.client.updateChannelsBatch({operation:"archive",filter:e})}async unarchive(e){return await this.client.updateChannelsBatch({operation:"unarchive",filter:e})}async updateData(e,t){return await this.client.updateChannelsBatch({operation:"updateData",filter:e,data:t})}},iO=iM(iE()),iN=Object.freeze({hasNext:!1,hasPrev:!1}),iF=Object.freeze({created_at:!0,deleted_at:!0,pinned_at:!0,updated_at:!0,command:!0,mentioned_users:!0,quoted_message:!0,latest_reactions:!0,own_reactions:!0,reaction_counts:!0,reply_count:!0,i18n:!0,t
1ype:!0,html:!0,__html:!0,user:!0}),iq=Object.freeze({error:!0});function ij(e,t){e.then().catch(e=>{console.warn(`failed to do ${t}, ran into error: `,e)})}var iB=e=>new Promise(t=>setTimeout(t,e));function i$(e){return"function"==typeof e||e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function iV(e){let t=[];for(let s of Array.isArray(e)?e:[e]){let e=Object.entries(s);for(let[s,i]of(e.length>1&&console.warn("client._buildSort() - multiple fields in a single sort object detected. Object's field order is not guaranteed"),e))t.push({field:s,direction:i})}return t}function iW(e){let t=Math.min(500+2e3*e,25e3),s=Math.min(Math.max(250,(e-1)*2e3),25e3);return Math.floor(Math.random()*(t-s)+s)}function iH(e){let t="";for(let s=0;s<e.length;s++)t+=e[s].toString(16).padStart(2,"0");return t}function iz(){let e,t=(iQ(e=new Uint8Array(16)),e);return t[6]=15&t[6]|64,t[8]=191&t[8]|128,iH(t.subarray(0,4))+"-"+iH(t.subarray(4,6))+"-"+iH(t.subarray(6,8))+"-"+iH(t.subarray(8,10))+"-"+iH(t.subarray(10,16))}var iQ="u">typeof crypto&&void 0!==crypto?.getRandomValues?crypto.getRandomValues.bind(crypto):"u">typeof msCrypto?msCrypto.getRandomValues.bind(msCrypto):function(e){let t=Math.pow(2,8*e.byteLength/e.length);for(let s=0;s<e.length;s++)e[s]=Math.random()*t};function iK(e){"u">typeof window&&window.addEventListener&&(window.addEventListener("offline",e),window.addEventListener("online",e))}function iJ(e){"u">typeof window&&window.removeEventListener&&(window.removeEventListener("offline",e),window.removeEventListener("online",e))}var iG=e=>{let t=[];for(let s in e)void 0!==e[s]&&(Array.isArray(e[s])||"object"==typeof e[s]?t.push(`${s}=${encodeURIComponent(JSON.stringify(e[s]))}`):t.push(`${s}=${encodeURIComponent(e[s])}`));return t.join("&")};function iY(e){let t=e=>e?{...e,created_at:e.created_at?new Date(e.created_at):new Date,deleted_at:e.deleted_at?new Date(e.deleted_at):null,pinned_at:e.pinned_at?new Date(e.pinned_at):null,reaction_groups:function(e,t,s){if(e)return e;if(t&&s){let e={};for(let i of Object.keys(t))e[i]={count:t[i],sum_scores:s[i]};return e}return null}(e.reaction_groups,e.reaction_counts,e.reaction_scores),status:e.status||"received",updated_at:e.updated_at?new Date(e.updated_at):new Date}:null;return{...t(e),error:e.error??null,quoted_message:t(e.quoted_message)}}var iX=e=>{let t={...iF,...iq};return{...Object.fromEntries(Object.entries(e).filter(([e])=>!t[e])),pinned:!!e.pinned_at,mentioned_users:e.mentioned_users?.map(e=>"string"==typeof e?e:e.id)}},iZ=({message:e,deletedAt:t,hardDelete:s=!1})=>s?{attachments:[],cid:e.cid,created_at:e.created_at,deleted_at:t,id:e.id,latest_reactions:[],mentioned_users:[],own_reactions:[],parent_id:e.parent_id,reply_count:e.reply_count,status:e.status,thread_participants:e.thread_participants,type:"deleted",updated_at:e.updated_at,user:e.user}:{...e,attachments:[],type:"deleted",deleted_at:t},i0=({messages:e,user:t,hardDelete:s=!1,deletedAt:i})=>{for(let a=0;a<e.length;a++){let n=e[a];n.user?.id===t.id&&(e[a]="deleted"===n.type?n:iZ({message:n,hardDelete:s,deletedAt:i})),n.quoted_message?.user?.id===t.id&&(e[a].quoted_message="deleted"===n.quoted_message.type?n.quoted_message:iZ({message:e[a].quoted_message,hardDelete:s,deletedAt:i}))}},i1=({needle:e,sortedArray:t,selectKey:s,selectValueToCompare:i=e=>e,sortDirection:a="ascending"})=>
1{if(!t.length)return 0;let n=0,r=t.length-1,o=0,l=()=>{o=Math.round((n+r)/2)},d=i(e);for(;n<=r;){l();let e=i(t[o]);"ascending"===a&&d<e||"descending"===a&&d>=e?r=o-1:n=o+1}if(s){let r=s(e),o="ascending"===a?-1:1;for(let e=n+o;0<=e&&e<t.length&&i(t[e])===d;e+=o)if(s(t[e])===r)return e}return n};function i2(e,t,s=!1,i="created_at",a=!0){let n=a||s,r=[...e];if(s&&(r=r.filter(e=>!(e.id&&t.id===e.id))),0===r.length&&n)return r.concat(t);if(0===r.length)return r;let o=t[i].getTime(),l=r.at(-1)[i].getTime()<o;if(l&&n)return r.concat(t);if(l)return r;let d=i1({needle:t,sortedArray:r,sortDirection:"ascending",selectValueToCompare:e=>e[i].getTime(),selectKey:e=>e.id});return!s&&t.id&&r[d]&&t.id===r[d].id?r[d]=t:n&&r.splice(d,0,t),r}var i3=(e,t=0,{leading:s=!1,trailing:i=!0}={})=>{let a,n=null,r=null,o=(...o)=>(n?clearTimeout(n):s&&(a=e(...o)),i&&(r=o),n=setTimeout(()=>{r&&(a=e(...r),r=null),n=null},t),a);return o.cancel=()=>{n&&clearTimeout(n)},o.flush=()=>(n&&(clearTimeout(n),n=null,r&&(a=e(...r))),a),o},i4=(e,t=200,{leading:s=!0,trailing:i=!1}={})=>{let a=null,n=null;return(...r)=>{if(a){i&&(n=r);return}s&&e(...r);let o=()=>{if(n){e(...n),n=null,a=setTimeout(o,t);return}a=null};a=setTimeout(o,t)}},i5=e=>{let t=e.returnedPage.filter(({shadowed:e})=>e);return e.parentSet.messages.length+t.length<e.returnedPage.length?(e.logger?.("error","Corrupted message set state: parent set size < returned page size"),e.parentSet.pagination):e.messagePaginationOptions?.created_at_around?(({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{let a,n,r,o,l={...e.pagination};if(!i?.created_at_around)return l;let d=new Date(i.created_at_around),[c,h]=[s[0],s.slice(-1)[0]],u=!!c?.created_at&&new Date(c.created_at)>d,g=!!h?.created_at&&new Date(h.created_at)<d,p=t>e.messages.length&&t>s.length,m=(t>e.messages.length||e.messages.length>=s.length)&&t>s.length;if(u)a=!1,r=!0,p&&(n=!1,o=!0);else if(g)n=!1,o=!0,p&&(a=!1,r=!0);else if(m)n=a=!1,r=o=!0;else{let[t,i]=[c?.id&&c.id===e.messages[0]?.id,h?.id&&h.id===e.messages.slice(-1)[0]?.id];r=t,o=i;let l=Math.floor(s.length/2),u=function(e,t){let s=0,i=e.length-1;for(;s<=i;){let a=Math.floor((s+i)/2),n=e[a].created_at;if(!n){s+=1;continue}let r=new Date(n);if(r.getTime()===t.getTime())return a;r.getTime()<t.getTime()?s=a+1:i=a-1}return s}(s,d);-1!==u&&(a=l<=u,n=l>=u)}return r&&void 0!==a&&(l.hasPrev=a),o&&void 0!==n&&(l.hasNext=n),l})(e):e.messagePaginationOptions?.id_around?(({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{let a,n,r={...e.pagination},{id_around:o}=i||{};if(!o)return r;let[l,d]=[s[0],s.slice(-1)[0]],[c,h]=[l?.id===e.messages[0]?.id,d?.id===e.messages.slice(-1)[0]?.id],u=c,g=h,p=Math.floor(s.length/2);if((t>e.messages.length||e.messages.length>=s.length)&&t>s.length)n=a=!1,u=g=!0;else if(!s[p])return r;else if(s[p].id===o)a=n=!0;else{let e,t=[s.slice(0,p),s.slice(p)];a=n=!0;for(let s=0;s<t.length;s++)(e=t[s].find(e=>e.id===o))&&0===s&&(a=!1),e&&1===s&&(n=!1)}return u&&void 0!==a&&(r.hasPrev=a),g&&void 0!==n&&(r.hasNext=n),r})(e):(({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{let a,n,r={...e.pagination},[o,l]=[s[0],s.slice(-1)[0]],[d,c]=[o?.id&&o.id===e.messages[0]?.id,l?.id&&l.id===e.messages.slice(-1)[0]?.id],h=i&&(i.created_at_after_or_equal||i.created_at_after||i.id_gt||i.id_gte),u=void 0===i||i.created_at_before_or_equal||i.created_at_before||i.id_lt||i.id_lte||i.offset,g=!h&&!u&&!i?.id_around&&!i?.created_at_around,p=s.length>=t;(void 0!==u||g)&&(a=p),void 0!==h&&(n=p);let m=0===s.length;return(d||m)&&void 0!==a&&(r.hasPrev=a),(c||m)&&void 0!==n&&(r.hasNext=n),r})(e)},i6={},i8=async({channel:e,client:t,id:s,members:i,options:a,type:n})=>{if(!e&&!n)throw Error("Channel or channel type have to be provided to query a channel.");let r=e||t.channel(n,s,{members:i}),o=r.id?r.cid:i&&i.length?i7(r.type,i):void 0;if(!o)throw Error("Channel ID or channel members array have to be provided to query a channel.");let l=i6[o];if(l)await l;else try{i6[o]=r.watch(a),await i6[o]}finally{delete i6[o]}return r},i7=(e,t)=>{if(!t)return;let s=[...t].sort().join(",");if(s)return`${e}:!members-${s}`},i9=e=>{if(!e)return!1;let t=e.state.membership;return!!t?.pinned_at},ae=e=>{if(!e)return!1;let t=e.state.membership;return!!t?.archived_at},at=e=>!!e&&"boolean"==typeof e.archived,as=({atIndex:e,sort:t,targetKey:s})=>{if(!t)return null;let i=null;if(Array.isArray(t))i=t[e]??null;else{let a=0;for(let n in t){if(a!==e){a++;continue}if(n!==s)return null;i=t;break}}return i?.[s]??null},ai=e=>{let t=aa({sort:e});return"number"==typeof t&&1===Math.abs(t)},aa=({sort:e})=>as({atIndex:0,sort:e,targetKey:"pinned_at"}),an=({channels:e})=>{let t=null;for(let s of e){if(!i9(s))break;"number"==typeof t?t++:t=0}return t},ar=({channels:e,channelToMove:t,channelToMoveIndexWithinChannels:s,sort:i})=>{let a=s??e.findIndex(e=>e.cid===t.cid),n=a>=0,r=0===a,o=ai(i),l=i9(t);if(r||o&&l)return e;let d=[...e];n&&d.splice(a,1);let c=null;return o&&(c=an({channels:d})),d.splice("number"==typeof c?c+1:0,0,t),d},ao=e=>"error"===e.type&&(e.moderation_details?.action==="MESSAGE_RESPONSE_ACTION_REMOVE"||e.moderation?.action==="remove"),al=(e,t)=>({newestMessageA:new Date(e[0]?.created_at??0),oldestMessageA:new Date(e.slice(-1)[0]?.created_at??0),newestMessageB:new Date(t[0]?.created_at??0),oldestMessageB:new Date(t.slice(-1)[0]?.created_at??0)}),ad=(e,t)=>{let{newestMessageA:s,newestMessageB:i,oldestMessageA:a,oldestMessageB:n}=al(e,t);return s>=i&&n>=a},ac=(e,t)=>{let{newestMessageA:s,newestMessageB:i,oldestMessageA:a,oldestMessageB:n}=al(e,t);return a<n&&n<s&&s<i},ah=class{constructor(e){this.messageSets=[],this.formatMessage=e=>iY(e),this.setIsUpToDate=e=>{this.isUpToDate=e},this.removeMessageFromArray=(e,t)=>{let s=e.filter(e=>!(e.id&&t.id&&e.id===t.id));return{removed:s.length<e.length,result:s}},this.updateUserMessages=e=>{let t=(e,t)=>{for(let s=0;s<e.length;s++){let i=e[s];i.user?.id===t.id&&(e[s]={...i,user:t})}};
1for(let s in this.messageSets.forEach(s=>t(s.messages,e)),this.threads)t(this.threads[s],e);t(this.pinnedMessages,e)},this.deleteUserMessages=(e,t=!1,s)=>{for(let i in this.messageSets.forEach(({messages:i})=>i0({messages:i,user:e,hardDelete:t,deletedAt:s??null})),this.threads)i0({messages:this.threads[i],user:e,hardDelete:t,deletedAt:s??null});i0({messages:this.pinnedMessages,user:e,hardDelete:t,deletedAt:s??null})},this.findMessageSetByOldestTimestamp=e=>{let t=0,s=this.messageSets.length;for(;t<s;){let i=t+s>>>1,a=this.messageSets[i];if(0===a.messages.length)return -1;a.messages[0].created_at.getTime()<=e?s=i:t=i+1}return t},this._channel=e,this.watcher_count=0,this.typing={},this.read={},this.initMessages(),this.pinnedMessages=[],this.pending_messages=[],this.threads={},this.mutedUsers=[],this.watchers={},this.members={},this.membership={},this.unreadCount=0,this.isUpToDate=!0,this.last_message_at=e?.state?.last_message_at!=null?new Date(e.state.last_message_at):null}get messages(){return this.messageSets.find(e=>e.isCurrent)?.messages||[]}set messages(e){let t=this.messageSets.findIndex(e=>e.isCurrent);this.messageSets[t].messages=e}get latestMessages(){return this.messageSets.find(e=>e.isLatest)?.messages||[]}set latestMessages(e){let t=this.messageSets.findIndex(e=>e.isLatest);this.messageSets[t].messages=e}get messagePagination(){return this.messageSets.find(e=>e.isCurrent)?.pagination||iN}pruneOldest(e){let t=this.messageSets.findIndex(e=>e.isCurrent);if(this.messageSets[t].isLatest){let s=this.messageSets[t].messages;this.messageSets[t].messages=s.slice(-e),this.messageSets[t].pagination.hasPrev=!0}}addMessageSorted(e,t=!1,s=!0,i="latest"){return this.addMessagesSorted([e],t,!1,s,i)}addMessagesSorted(e,t=!1,s=!1,i=!0,a="current"){let{messagesToAdd:n,targetMessageSetIndex:r}=this.findTargetMessageSet(e,i,a);for(let e=0;e<n.length;e+=1){let a;if(n[e].shadowed)continue;n[e].created_at instanceof Date?a=n[e]:((a=this.formatMessage(n[e])).user&&this._channel?.cid&&this._channel.getClient().state.updateUserReference(a.user,this._channel.cid),s&&a.id&&this.threads[a.id]&&!this._channel.getClient().preventThreadCleanup&&delete this.threads[a.id],!(this._channel.getConfig()?.skip_last_msg_update_for_system_msgs&&"system"===a.type)&&(!this.last_message_at||a.created_at.getTime()>this.last_message_at.getTime())&&(this.last_message_at=new Date(a.created_at.getTime())));let o=a.parent_id;if((!o||a.show_in_channel)&&-1!==r&&(this.messageSets[r].messages=this._addToMessageList(this.messageSets[r].messages,a,t,"created_at",i)),o&&!s){let e=this.threads[o]||[];this.threads[o]=this._addToMessageList(e,a,t,"created_at",i)}}return{messageSet:this.messageSets[r]}}addPinnedMessages(e){for(let t=0;t<e.length;t+=1)this.addPinnedMessage(e[t])}addPinnedMessage(e){this.pinnedMessages=this._addToMessageList(this.pinnedMessages,this.formatMessage(e),!1,"pinned_at")}removePinnedMessage(e){let{result:t}=this.removeMessageFromArray(this.pinnedMessages,e);this.pinnedMessages=t}addReaction(e,t,s){let i;if(t||(i=this.findMessage(e.message_id)),!t&&!i)return;let a=t??i,n={id:a?.id,parent_id:a?.parent_id,pinned:a?.pinned,show_in_channel:a?.show_in_channel};return this._updateMessage(n,a=>{if(t){let i={...t};return t.own_reactions=this._addOwnReactionToMessage(a.own_reactions,e,s),i.own_reactions=this._channel.getClient().userID===e.user_id?t.own_reactions:a.own_reactions,this.formatMessage(i)}return i?this._addReactionToState(i,e,s):a}),t??i}
1_addReactionToState(e,t,s){if(e.reaction_groups||(e.reaction_groups={}),s)for(let t of e.own_reactions??[]){let s=e.reaction_groups[t.type];e.reaction_groups[t.type]={...s,count:s.count-1,sum_scores:s.sum_scores-(t.score??1)},e.reaction_groups[t.type].count<1&&delete e.reaction_groups[t.type]}let i=e.reaction_groups[t.type],a=t.score??1;e.reaction_groups[t.type]=i?{...i,count:i.count+1,sum_scores:i.sum_scores+a,last_reaction_at:t.created_at}:{count:1,first_reaction_at:t.created_at,last_reaction_at:t.created_at,sum_scores:a},e.own_reactions=this._addOwnReactionToMessage(e.own_reactions,t,s);let n=this._channel.getClient().userID;return e.latest_reactions=s?[...(e.latest_reactions||[]).filter(e=>e.user_id!==n),t]:[...e.latest_reactions||[],t],e}_addOwnReactionToMessage(e,t,s){return e=(e=s?[]:this._removeOwnReactionFromMessage(e,t))||[],this._channel.getClient().userID===t.user_id&&e.push(t),e}_removeOwnReactionFromMessage(e,t){return e?e.filter(e=>e.user_id!==t.user_id||e.type!==t.type):e}removeReaction(e,t){let s;if(t||(s=this.findMessage(e.message_id)),!t&&!s)return;let i=t??s,a={id:i?.id,parent_id:i?.parent_id,pinned:i?.pinned,show_in_channel:i?.show_in_channel};return this._updateMessage(a,i=>t?(t.own_reactions=this._removeOwnReactionFromMessage(i.own_reactions,e),this.formatMessage(t)):s?this._removeReactionFromState(s,e):i),t}_removeReactionFromState(e,t){let s=e.own_reactions?.find(e=>e.type===t.type);if(s&&e.reaction_groups?.[s.type]){let t=e.reaction_groups[s.type];e.reaction_groups[s.type]={...t,count:t.count-1,sum_scores:t.sum_scores-(s.score??1)},e.reaction_groups[s.type].count<1&&delete e.reaction_groups[s.type]}e.own_reactions=e.own_reactions?.filter(e=>e.type!==t.type);let i=this._channel.getClient().userID;return e.latest_reactions=e.latest_reactions?.filter(e=>e.user_id!==i||e.type!==t.type),e}_updateQuotedMessageReferences({message:e,remove:t}){let s=s=>{let i=s.reduce((s,i)=>(i.quoted_message_id===e.id&&s.push({...{...i,created_at:i.created_at.toISOString(),pinned_at:i.pinned_at?.toISOString(),updated_at:i.updated_at?.toISOString()},quoted_message:t?{...e,attachments:[]}:e}),s),[]);this.addMessagesSorted(i,!0)};e.parent_id?e.parent_id&&this.threads[e.parent_id]&&s(this.threads[e.parent_id]):this.messageSets.forEach(e=>s(e.messages))}removeQuotedMessageReferences(e){this._updateQuotedMessageReferences({message:e,remove:!0})}_updateMessage(e,t){let{parent_id:s,show_in_channel:i,pinned:a}=e;if(s&&this.threads[s]){let i=this.threads[s],a=i.findIndex(t=>t.id===e.id);-1!==a&&(i[a]=t(i[a]),this.threads[s]=i)}if(!i&&!s||i){let s=this.findMessageSetIndex(e);if(-1!==s){let i=this.messageSets[s].messages.findIndex(t=>t.id===e.id);if(-1!==i){let e=t(this.messageSets[s].messages[i]);this.messageSets[s].messages[i]=e}}}if(a){let s=this.pinnedMessages.findIndex(t=>t.id===e.id);-1!==s&&(this.pinnedMessages[s]=t(this.pinnedMessages[s]))}}_addToMessageList(e,t,s=!1,i="created_at",a=!0){return i2(e,t,s,i,a)}removeMessage(e){let t=!1;if(e.parent_id&&this.threads[e.parent_id]){let{removed:s,result:i}=this.removeMessageFromArray(this.threads[e.parent_id],e);this.threads[e.parent_id]=i,t=s}else{let s=e.messageSetIndex??this.findMessageSetIndex(e);if(-1!==s){let{removed:i,result:a}=this.removeMessageFromArray(this.messageSets[s].messages,e);this.messageSets[s].messages=a,t=i}}return t}filterErrorMessages(){let e=this.latestMessages.filter(e=>"error"!==e.type);for(let e of this.latestMessages.filter(ao))this._channel.getClient().offlineDb?.hardDeleteMessage({id:e.id});this.latestMessages=e}clean(){let e=new Date;for(let[t,s]of Object.entries(this.typing)){let i="string"==typeof s.received_at?new Date(s.received_at):s.received_at||new Date;e.getTime()-i.getTime()>7e3&&(delete this.typing[t],this._channel.getClient().dispatchEvent({cid:this._channel.cid,type:"typing.stop",user:{id:t}}))}}clearMessages(){this.initMessages(),this.pinnedMessages=[]}initMessages(){this.messageSets=[{messages:[],isLatest:!0,isCurrent:!0,pagination:{...iN}}]}async loadMessageIntoState(e,t,s=25){let i,a=!1,n=!1,r=t||e;if("latest"===e){if(this.messages===this.latestMessages)return;i=this.messageSets.findIndex(e=>e.isLatest)}else i=this.findMessageSetIndex({id:r});-1!==i&&(this.switchToMessageSet(i),a=!0),n=!t||!!this.threads[t]?.find(t=>
1t.id===e),a&&n||(a||await this._channel.query({messages:{id_around:r,limit:s}},"new"),!n&&t&&await this._channel.getReplies(t,{id_around:e,limit:s}),-1!==(i=this.findMessageSetIndex({id:r}))&&this.switchToMessageSet(i))}findMessage(e,t){if(t){let s=this.threads[t];if(!s)return;return s.find(t=>t.id===e)}let s=this.findMessageSetIndex({id:e});if(-1!==s)return this.messageSets[s].messages.find(t=>t.id===e)}findMessageByTimestamp(e,t,s=!1){if(t&&!this.threads[t]||0===this.messageSets.length)return null;let i=this.findMessageSetByOldestTimestamp(e),a=this.messageSets[i]?.messages;if(!a?.length)return null;let n=a[0].created_at.getTime(),r=a.slice(-1)[0].created_at.getTime();if((e<n||r<e)&&s)return null;let o=0,l=a.length-1;for(;o<l;){let t=o+l>>>1;e<=a[t].created_at.getTime()?l=t:o=t+1}let d=a[o];return s?d.created_at.getTime()===e?d:null:d}switchToMessageSet(e){let t=this.messageSets.find(e=>e.isCurrent);t&&(t.isCurrent=!1,this.messageSets[e].isCurrent=!0)}areMessageSetsOverlap(e,t){return e.some(e=>t.find(t=>e.id===t.id))}findMessageSetIndex(e){return this.messageSets.findIndex(t=>!!t.messages.find(t=>t.id===e.id))}findTargetMessageSet(e,t=!0,s="current"){let i,a=e;if(0===e.length)return{targetMessageSetIndex:0,messagesToAdd:e};if(t){let t=this.messageSets.map((e,t)=>t).filter(t=>this.areMessageSetsOverlap(this.messageSets[t].messages,e)),n=this.messageSets.map((e,t)=>t).filter(t=>{let s,i;return ad(s=this.messageSets[t].messages,i=e.map(iY))||ad(i,s)||ac(s,i)||ac(i,s)});switch(s){case"new":if(t.length>0)i=t[0];else if(n.length>0)i=n[0];else if(e.some(e=>!e.parent_id)){let t=this.findMessageSetByOldestTimestamp(new Date(e[0].created_at).getTime());if(-1===t)this.messageSets.push({messages:[],isCurrent:!1,isLatest:!1,pagination:{...iN}}),i=this.messageSets.length-1;else{let e=0===t;this.messageSets.splice(t,0,{messages:[],isCurrent:!1,isLatest:e,pagination:{...iN}}),e&&this.messageSets.slice(1).forEach(e=>{e.isLatest=!1}),i=t}}break;case"current":i=n.length>0?n[0]:this.messageSets.findIndex(e=>e.isCurrent);break;case"latest":i=n.length>0?n[0]:this.messageSets.findIndex(e=>e.isLatest);break;default:i=-1}let r=t.splice(0,1)[0],o=[...t];if(void 0!==r&&r!==i&&o.push(i),o.length>0){let t=this.messageSets[r],s=this.messageSets.filter((e,t)=>-1!==o.indexOf(t));s.forEach(e=>{t.isLatest=t.isLatest||e.isLatest,t.isCurrent=t.isCurrent||e.isCurrent,t.pagination.hasPrev=e.messages[0].created_at<t.messages[0].created_at?e.pagination.hasPrev:t.pagination.hasPrev,t.pagination.hasNext=t.messages.slice(-1)[0].created_at<e.messages.slice(-1)[0].created_at?e.pagination.hasNext:t.pagination.hasNext,a=[...a,...e.messages]}),s.forEach(e=>this.messageSets.splice(this.messageSets.indexOf(e),1)),i=this.messageSets.findIndex(t=>this.areMessageSetsOverlap(t.messages,e))}}else i=this.findMessageSetIndex(e[0]);return{targetMessageSetIndex:i,messagesToAdd:a}}},au=()=>{},ag=class{constructor(e){this.value=e,this.handlers=new Set,this.preprocessors=new Set,this.partialNext=e=>this.next(t=>({...t,...e})),this.subscribeWithSelector=(e,t)=>{let s;return this.subscribe(i=>{let a=e(i),n=void 0===s;for(let e in s)if(s[e]!==a[e]){n=!0;break}if(!n)return;let r=s;s=a,t(a,r)})}}merge(e){return new ap({original:this,merged:e})}next(e){let t="function"==typeof e?e(this.value):e;if(t===this.value)return;this.preprocessors.forEach(e=>e(t,this.value));let s=this.value;this.value=t,this.handlers.forEach(e=>e(this.value,s))}getLatestValue(){return this.value}subscribe(e){return e(this.value,void 0),this.handlers.add(e),()=>{this.handlers.delete(e)}}addPreprocessor(e){return this.preprocessors.add(e),()=>{this.preprocessors.delete(e)}}},ap=class e extends ag{constructor({original:t,merged:s}){const i=t.getLatestValue(),a=s.getLatestValue();super({...i,...a}),this.next=()=>{console.warn(`${e.name}.next is disabled, call original.next or merged.next instead`)},this.partialNext=()=>{console.warn(`${e.name}.partialNext is disabled, call original.partialNext or merged.partialNext instead`)},this.cachedOriginalValue=i,this.cachedMergedValue=a,this.original=t,this.merged=s}subscribe(e){let t=[];if(!this.handlers.size){let e=e=>{super.next(t=>({...t,...e}))};t.push(this.original.subscribe(t=>{t!==this.cachedOriginalValue&&(this.cachedOriginalValue=t,e(t))}),this.merged.subscribe(t=>{t!==this.cachedMergedValue&&(this.cachedMergedValue=t,e(t))}))}return t.push(super.subscribe(e)),()=>
1{t.forEach(e=>e())}}getLatestValue(){if(!this.handlers.size){let e=this.original.getLatestValue(),t=this.merged.getLatestValue();(e!==this.cachedOriginalValue||t!==this.cachedMergedValue)&&(this.value={...e,...t},this.cachedMergedValue=t,this.cachedOriginalValue=e)}return super.getLatestValue()}addPreprocessor(){return console.warn(`${e.name}.addPreprocessor is disabled, call original.addPreprocessor or merged.addPreprocessor instead`),au}},am=class e{constructor(){this.unsubscribeFunctions=new Set,this.refCount=0}get hasSubscriptions(){return this.unsubscribeFunctions.size>0}addUnsubscribeFunction(e){this.unsubscribeFunctions.add(e)}incrementRefCount(){return++this.refCount}unregisterSubscriptions(){return this.refCount>1?this.refCount--:(this.unsubscribeFunctions.forEach(e=>e()),this.unsubscribeFunctions.clear(),this.refCount=0),e.symbol}};am.symbol=Symbol(am.name);var af=am,ay=e=>{if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}},ab=class extends af{constructor({channel:e}){super(),this.timeout=null,this.registerSubscriptions=()=>{this.incrementRefCount(),this.hasSubscriptions||(this.addUnsubscribeFunction(this.channel.on("message.new",e=>{e.message?.user?.id&&e.message.user.id===this.getOwnUserId()&&this.setOwnLatestMessageDate(ay(e.message?.created_at))}).unsubscribe),this.addUnsubscribeFunction(this.channel.on("channel.updated",e=>{e.channel?.cooldown!==this.cooldownConfigSeconds&&this.refresh()}).unsubscribe))},this.setCooldownRemaining=e=>{this.state.partialNext({cooldownRemaining:e})},this.clearTimeout=()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},this.refresh=()=>{let{cooldown:e=0,own_capabilities:t}=this.channel.data??{},s=(t??[]).includes("skip-slow-mode"),i=this.findOwnLatestMessageDate({messages:this.channel.state.latestMessages});if((e!==this.cooldownConfigSeconds||i?.getTime()!==this.ownLatestMessageDate?.getTime()||s!==this.canSkipCooldown)&&this.state.partialNext({cooldownConfigSeconds:e,ownLatestMessageDate:i,canSkipCooldown:s}),this.canSkipCooldown||0===this.cooldownConfigSeconds){this.clearTimeout(),0!==this.cooldownRemaining&&this.setCooldownRemaining(0);return}this.recalculate()},this.setOwnLatestMessageDate=e=>{this.state.partialNext({ownLatestMessageDate:e}),this.recalculate()},this.recalculate=()=>{this.clearTimeout();let{cooldownConfigSeconds:e,ownLatestMessageDate:t,canSkipCooldown:s}=this.state.getLatestValue(),i=null!=t?Math.max(0,(Date.now()-t.getTime())/1e3):void 0,a=!s&&void 0!==i&&e>i?Math.round(e-i):0;a!==this.cooldownRemaining&&this.setCooldownRemaining(a),a<=0||(this.timeout=setTimeout(()=>{this.recalculate()},1e3))},this.channel=e,this.state=new ag({cooldownConfigSeconds:0,cooldownRemaining:0,ownLatestMessageDate:void 0,canSkipCooldown:!1}),this.refresh()}get cooldownConfigSeconds(){return this.state.getLatestValue().cooldownConfigSeconds}get cooldownRemaining(){return this.state.getLatestValue().cooldownRemaining}get canSkipCooldown(){return this.state.getLatestValue().canSkipCooldown}get ownLatestMessageDate(){return this.state.getLatestValue().ownLatestMessageDate}getOwnUserId(){let e=this.channel.getClient();return e.userID??e.user?.id}findOwnLatestMessageDate({messages:e}){let t,s=this.getOwnUserId();if(s){for(let i=e.length-1;i>=0;i-=1){let a=e[i];if(a.user?.id!==s)continue;let n=ay(a.created_at);if(n&&((!t||n.getTime()>t.getTime())&&(t=n),t.getTime()>n.getTime()))break}return t}}},a_=e=>!!e?.og_scrape_url||!!e?.title_link,aw=e=>!!e?.localMetadata?.id,av=(e,t=[])=>"file"===e.type||!!(e.mime_type&&-1===t.indexOf(e.mime_type)&&"video"!==e.type),aC=e=>"image"===e.type&&!a_(e),aS=e=>aC(e)&&aw(e),aR=e=>"audio"===e.type,aU=e=>"voiceRecording"===e.type,aI=(e,t=[])=>"video"===e.type||!!(e.mime_type&&-1!==t.indexOf(e.mime_type)),ax=e=>!!e.lastModified&&!("uri"in e),aL=e=>null!==e&&"object"==typeof e&&!ax(e)&&!(e instanceof Blob&&!(e instanceof File))&&"string"==typeof e.name&&"string"==typeof e.uri&&"number"==typeof e.size&&"string"==typeof e.type,aM=({blobsArray:e,fileName:t,mimeType:s})=>{let i=new Blob(e,{type:s});return new File([i],t,{type:i.type})},aE=e=>{let t,s=(t=e.match(/\/([^/;]+)/),t?.[1]);return`file_${new Date().toISOString()}${s?"."+s:""}`},aA=e=>{let t=e.type;return t.startsWith("image/")&&!t.endsWith(".photoshop")},ak=e=>{if(!e)return null;if(aw(e))return e;let{localMetadata:t,...s}=e;return{localMetadata:{...t??{},id:t?.id||iz()},...s}};aP(function(e,t){let s=!1;return{cb:()=>t().finally(()=>{s||aT.delete(e)}),onContinued:()=>s=!0}
1});var aD=aP(function(e,t){let s=new AbortController;return{cb:()=>s.signal.aborted?Promise.resolve("canceled"):t(s.signal).finally(()=>{s.signal.aborted||aT.delete(e)}),onContinued:()=>s.abort()}}),aT=new Map;function aP(e){return function(t,s){let{cb:i,onContinued:a}=e(t,s),n=aT.get(t);n?.onContinued();let r=n?n.promise.then(i,i):i();return aT.set(t,{promise:r,onContinued:a}),r}}var aO=class{constructor(){this.middleware=[],this.id=iz()}use(e){return this.middleware=this.middleware.concat(e),this}replace(e){let t=[...this.middleware];return e.forEach(e=>{let s=this.middleware.findIndex(t=>t.id===e.id);s>=0?t.splice(s,1,e):t.push(e)}),this.middleware=t,this}insert({middleware:e,position:t,unique:s}){s&&e.forEach(e=>{let t=this.middleware.findIndex(t=>t.id===e.id);t>=0&&this.middleware.splice(t,1)});let i=t.after||t.before,a=this.middleware.findIndex(e=>e.id===i),n=t.after?a+1:a;return this.middleware.splice(n,0,...e),this}setOrder(e){this.middleware=e.map(e=>this.middleware.find(t=>t.id===e)).filter(Boolean)}remove(e){(e||e.length)&&(this.middleware=this.middleware.filter(t=>"string"==typeof e?e!==t.id:!e.includes(t.id)))}async executeMiddlewareChain({eventName:e,initialValue:t,mode:s="cancelable"}){let i=-1,a=async(t,s,n)=>{if(t<=i)throw Error("next() called multiple times");if(i=t,t===this.middleware.length||n&&["complete","discard"].includes(n))return{state:s,status:n};let r=this.middleware[t].handlers[e];return r?await r({state:s,next:e=>a(t+1,e),complete:e=>a(t+1,e,"complete"),discard:()=>a(t+1,s,"discard"),forward:()=>a(t+1,s)}):a(t+1,s,n)},n="cancelable"===s?await aD(`middleware-execution-${this.id}-${e}`,async e=>{let s=await a(0,t);return e.aborted?"canceled":s}):await a(0,t);return"canceled"===n?{state:t,status:"discard"}:n}async execute({eventName:e,initialValue:t,mode:s}){return await this.executeMiddlewareChain({eventName:e,initialValue:t,mode:s})}},aN=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/attachment-manager-middleware/upload-error",handlers:{postProcess:({state:t,discard:s,forward:i})=>{let{attachment:a,error:n}=t;if(!n)return i();if(!a)return s();let r=n instanceof Error?n.message:"unknown error";return e.client.notifications.addError({message:"Error uploading attachment",origin:{emitter:"AttachmentManager",context:{attachment:a}},options:{type:"api:attachment:upload:failed",metadata:{reason:r},originalError:n}}),i()}}}))(e),{id:"stream-io/attachment-manager-middleware/post-upload-enrichment",handlers:{postProcess:({state:e,discard:t,forward:s,next:i})=>{let{attachment:a,error:n,response:r}=e;if(n)return s();if(!a||!r)return t();let o={...a},l=a.localMetadata.previewUri;return l&&(l.startsWith("blob:")&&URL.revokeObjectURL(l),delete o.localMetadata.previewUri),aS(a)?o.image_url=r.file:o.asset_url=r.file,r.thumb_url&&(o.thumb_url=r.thumb_url),i({...e,attachment:o})}}}])}},aF=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/attachment-manager-middleware/file-upload-config-check",handlers:{prepare:async({state:t,next:s,discard:i})=>{let{attachmentManager:a}=e;if(!a||!t.attachment)return i();let n=await a.getUploadConfigCheck(t.attachment.localMetadata.file),r={...t.attachment,localMetadata:{...t.attachment.localMetadata,uploadPermissionCheck:n,uploadState:n.uploadBlocked?"blocked":"pending"}};return s({...t,attachment:r})}}}))(e),(e=>({id:"stream-io/attachment-manager-middleware/blocked-upload-notification",handlers:{prepare:({state:{attachment:t},forward:s})=>(t&&t.localMetadata.uploadPermissionCheck?.uploadBlocked&&e.client.notifications.addError({message:"The attachment upload was blocked",origin:{emitter:"AttachmentManager",context:{blockedAttachment:t}},options:{type:"validation:attachment:upload:blocked",metadata:{reason:t.localMetadata.uploadPermissionCheck?.reason}}}),s())}}))(e)])}},aq=e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return null!==t&&t!==Object.prototype&&e.constructor&&e.constructor!==Object},aj=(e,t,s=new Set,i=new WeakSet,a=new WeakSet)=>{if(e===t)return!0;if(null==e||null==t)return!1;let n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e!=e&&t!=t||e===t;if(i.has(e)||a.has(t))return i.has(e)&&a.has(t);if(i.add(e),a.add(t),e instanceof Date&&t instanceof Date)return i.delete(e),a.delete(t),e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return i.delete(e),a.delete(t),e.toString()===t.toString();if(aq(e)||aq(t))return i.delete(e),a.delete(t),!1;let r=Array.isArray(e),o=Array.isArray(t);if(r!==o)return i.delete(e),a.delete(t),!1;if(r&&o){if(e.length!==t.length)return i.delete(e),a.delete(t),!1;let n=[e,t];if(s.has(n))return i.delete(e),a.delete(t),!0;
1s.add(n);for(let r=0;r<e.length;r++)if(!aj(e[r],t[r],s,i,a))return s.delete(n),i.delete(e),a.delete(t),!1;return s.delete(n),i.delete(e),a.delete(t),!0}let l=Object.keys(e),d=Object.keys(t);if(l.length!==d.length)return i.delete(e),a.delete(t),!1;for(let s of d)if(!Object.prototype.hasOwnProperty.call(e,s))return i.delete(e),a.delete(t),!1;let c=[e,t];if(s.has(c))return i.delete(e),a.delete(t),!0;for(let n of(s.add(c),l))if(!aj(e[n],t[n],s,i,a))return s.delete(c),i.delete(e),a.delete(t),!1;return s.delete(c),i.delete(e),a.delete(t),!0};function aB(e={}){let{trackDiff:t=!1}=e;return function({target:e,source:s,customizer:i}){let a,n=Array.isArray(s)?s:[s],r=t?structuredClone(e):void 0;function o(e,t,s,a){for(let n of[...Object.keys(t),...Object.getOwnPropertySymbols(t)])!function(e,t,s,a,n){let r,o=t[s],l=e[s];if(void 0===(r=i?.(l,o,s,e,t,a))||(Object.defineProperty(e,s,{value:r,enumerable:!0,writable:!0,configurable:!0}),0))if(o&&"object"==typeof o){if(!a.has(o)){let t=function(e,t){if(null==e||!Array.isArray(e)&&"object"!=typeof e)return t;if(e&&"object"==typeof e){let s=aq(e),i=aq(t);return s||i?i?t:e:Array.isArray(e)?[...e]:{...e}}return Array.isArray(t)?[]:{}}(l,o);if(Object.defineProperty(e,s,{value:t,enumerable:!0,writable:!0,configurable:!0}),aq(t))return;n.push({target:t,source:o,sourceKey:s,parentTarget:e})}}else void 0!==o&&(e[s]=o)}(e,t,n,s,a)}let l=n.reduce((e,s)=>(function(e,s,i=new Set){if(i.has(e)||i.has(s))return{...e};let a={...e},n=[];for(i.add(a),i.add(s),o(a,s,i,n);n.length;)!function({target:e,source:s,sourceKey:i,parentTarget:a},n,r){if(n.has(s)){t&&i&&a&&Object.defineProperty(a,i,{value:e,enumerable:!0,writable:!0,configurable:!0});return}n.has(e)||n.has(s)||(n.add(e),n.add(s),o(e,s,n,r),n.delete(s),n.delete(e))}(n.pop(),i,n);return i.delete(s),i.delete(a),a})(e,s),{...e}),d=t&&r?(function e(t,s,i,a,n=new Set,r=new Set){if(aj(t,s,new Set(n)))return;if(null==t){void 0!==a&&(i.children[String(a)]={type:"added",value:s,children:{}});return}if("object"==typeof t&&null!==t){if(r.has(t)){void 0!==a&&(i.children[String(a)]={type:"circular",value:s,oldValue:t,children:{}});return}r.add(t)}if("object"!=typeof t||"object"!=typeof s||null===t||null===s||Array.isArray(t)!==Array.isArray(s)||aq(t)||aq(s)){void 0!==a&&(i.children[String(a)]={type:"updated",value:s,oldValue:t,children:{}}),"object"==typeof t&&null!==t&&r.delete(t);return}let o=void 0!==a?{type:"updated",children:{},oldValue:t,value:s}:i;void 0!==a&&(i.children[String(a)]=o);let l=[t,s];if(n.has(l)){"object"==typeof t&&null!==t&&r.delete(t);return}for(let i of(n.add(l),new Set([...Object.keys(t),...Object.getOwnPropertySymbols(t),...Object.keys(s),...Object.getOwnPropertySymbols(s)]))){let a=t[i],l=s[i];if(i in s){if(!(i in t)){o.children[String(i)]={type:"added",value:l,children:{}};continue}e(a,l,o,i,n,r)}}n.delete(l),"object"==typeof t&&null!==t&&r.delete(t)}(r,l,a={children:{}}),a$(a)):null;return{result:l,diff:d}}}function a$(e){let t={},s=!1;for(let i in e.children){let a=a$(e.children[i]);a&&(t[i]=a,s=!0)}return e.type||s?{...e,children:t}:null}function aV(e,t,s){return aB()({target:e,source:t,customizer:s}).result}function aW(e,t,s){let{result:i,diff:a}=aB({trackDiff:!0})({target:e,source:t,customizer:s});return{result:i,diff:a$(a??{children:{}})||{children:{}}}}var aH=({message:e})=>({attachments:(e?.attachments??[])?.filter(({og_scrape_url:e})=>!e).map(e=>{let t=aR(e)||av(e)||aC(e)||aI(e)||aU(e)?{id:iz(),uploadState:"finished"}:{id:iz()};return{...e,localMetadata:t}})}),az=class e{constructor({composer:t,message:s}){this.setCustomUploadFn=e=>{this.composer.updateConfig({attachments:{doUploadRequest:e}})},this.initState=({message:e}={})=>{this.state.next(aH({message:e}))},this.getAttachmentIndex=e=>{let t=this.attachmentsById;return this.attachments.indexOf(t[e])},this.prepareAttachmentUpdate=e=>{let t=this.attachments,s=[...this.attachments],i=this.getAttachmentIndex(e.localMetadata.id);if(-1===i)return null;let a=aW(t[i],e);if(a.diff&&Object.keys(a.diff.children).length){let e=ak(a.result);if(e)return s.splice(i,1,e),s}return null},this.updateAttachment=e=>{let t=this.prepareAttachmentUpdate(e);t&&this.state.partialNext({attachments:t})},this.upsertAttachments=e=>{if(!e.length)return;let t=[...this.attachments],s=!1;
1e.forEach(e=>{let i=this.prepareAttachmentUpdate(e);if(i)t=i,s=!0;else{let i=ak(e);i&&(t.push(i),s=!0)}}),s&&this.state.partialNext({attachments:t})},this.removeAttachments=e=>{this.state.partialNext({attachments:this.attachments.filter(t=>!e.includes(t.localMetadata?.id))})},this.getUploadConfigCheck=async e=>{let t,s=this.channel.getClient();t=s.appSettingsPromise?await s.appSettingsPromise:await s.getAppSettings();let i=aA(e)?t?.app?.image_upload_config:t?.app?.file_upload_config;if(!i)return{uploadBlocked:!1};let{allowed_file_extensions:a,allowed_mime_types:n,blocked_file_extensions:r,blocked_mime_types:o,size_limit:l}=i,d=e.type;if(ax(e)||aL(e)){if(a?.length&&!a.some(t=>e.name.toLowerCase().endsWith(t.toLowerCase())))return{uploadBlocked:!0,reason:"allowed_file_extensions"};if(r?.length&&r.some(t=>e.name.toLowerCase().endsWith(t.toLowerCase())))return{uploadBlocked:!0,reason:"blocked_file_extensions"}}return n?.length&&!n.some(e=>e.toLowerCase()===d?.toLowerCase())?{uploadBlocked:!0,reason:"allowed_mime_types"}:o?.length&&o.some(e=>e.toLowerCase()===d?.toLowerCase())?{uploadBlocked:!0,reason:"blocked_mime_types"}:e.size&&e.size>(l||0x6400000)?{uploadBlocked:!0,reason:"size_limit"}:{uploadBlocked:!1}},this.fileToLocalUploadAttachment=async t=>{let s=e.toLocalUploadAttachment(t),i=await this.getUploadConfigCheck(s.localMetadata.file);return s.localMetadata.uploadPermissionCheck=i,s.localMetadata.uploadState=i.uploadBlocked?"blocked":"pending",s},this.ensureLocalUploadAttachment=async e=>{if(!e.localMetadata?.file)return void this.client.notifications.addError({message:"File is required for upload attachment",origin:{emitter:"AttachmentManager",context:{attachment:e}},options:{type:"validation:attachment:file:missing"}});if(!e.localMetadata.id)return void this.client.notifications.addError({message:"Local upload attachment missing local id",origin:{emitter:"AttachmentManager",context:{attachment:e}},options:{type:"validation:attachment:id:missing"}});if(!this.fileUploadFilter(e))return;let t=await this.fileToLocalUploadAttachment(e.localMetadata.file);return e.localMetadata.id&&(t.localMetadata.id=e.localMetadata.id),t},this.doDefaultUploadRequest=async e=>{if(aL(e))return this.channel[aA(e)?"sendImage":"sendFile"](e.uri,e.name,e.type);let t=ax(e)?e:aM({blobsArray:[e],fileName:aE(e.type),mimeType:e.type}),{duration:s,...i}=await this.channel[aA(e)?"sendImage":"sendFile"](t);return i},this.doUploadRequest=async e=>{let t=this.config.doUploadRequest;return t?await t(e):this.doDefaultUploadRequest(e)},this.uploadAttachment=async e=>{let t;if(!this.isUploadEnabled)return;let s=await this.ensureLocalUploadAttachment(e);if(void 0===s)return;if("blocked"===s.localMetadata.uploadState)return this.upsertAttachments([s]),this.client.notifications.addError({message:"The attachment upload was blocked",origin:{emitter:"AttachmentManager",context:{attachment:e,blockedAttachment:s}},options:{type:"validation:attachment:upload:blocked",metadata:{reason:s.localMetadata.uploadPermissionCheck?.reason}}}),s;this.upsertAttachments([{...e,localMetadata:{...e.localMetadata,uploadState:"uploading"}}]);try{t=await this.doUploadRequest(s.localMetadata.file)}catch(i){let t=i instanceof Error?i.message:"unknown error",s={...e,localMetadata:{...e.localMetadata,uploadState:"failed"}};return this.client.notifications.addError({message:"Error uploading attachment",origin:{emitter:"AttachmentManager",context:{attachment:e,failedAttachment:s}},options:{type:"api:attachment:upload:failed",metadata:{reason:t},originalError:i instanceof Error?i:void 0}}),this.updateAttachment(s),s}if(!t)return void this.removeAttachments([e.localMetadata.id]);let i={...e,localMetadata:{...e.localMetadata,uploadState:"finished"}},a=i.localMetadata.previewUri;return a&&(a.startsWith("blob:")&&URL.revokeObjectURL(a),delete i.localMetadata.previewUri),aS(i)?i.image_url=t.file:i.asset_url=t.file,t.thumb_url&&(i.thumb_url=t.thumb_url),this.updateAttachment(i),i},this.uploadFile=async t=>{let s,i,a=await this.preUploadMiddlewareExecutor.execute({eventName:"prepare",initialValue:{attachment:e.toLocalUploadAttachment(t)},mode:"concurrent"}),n=a.state.attachment;if("discard"===a.status||!this.fileUploadFilter(n))return n;if("blocked"===n.localMetadata.uploadState)return this.upsertAttachments([n]),a.state.attachment;n={...n,localMetadata:{...n.localMetadata,uploadState:"uploading"}},this.upsertAttachments([n]);try{s=await this.doUploadRequest(t)}catch(e){i=e instanceof Error?e:void 0}let r=await this.postUploadMiddlewareExecutor.execute({eventName:"postProcess",initialValue:{attachment:{...n,localMetadata:{...n.localMetadata,uploadState:i?"failed":"finished"}},error:i,response:s},mode:"concurrent"});
1return(n=r.state.attachment,"discard"===r.status)?this.removeAttachments([n.localMetadata.id]):this.updateAttachment(n),n},this.uploadFiles=async e=>{if(!this.isUploadEnabled)return;let t=null!=e&&"object"==typeof e&&("u">typeof FileList&&e instanceof FileList||"item"in e&&"length"in e&&!Array.isArray(e))?Array.from(e):e;return await Promise.all(t.slice(0,this.availableUploadSlots).map(this.uploadFile))},this.composer=t,this.state=new ag(aH({message:s})),this.attachmentsByIdGetterCache={attachmentsById:{},attachments:[]},this.preUploadMiddlewareExecutor=new aF({composer:t}),this.postUploadMiddlewareExecutor=new aN({composer:t})}get attachmentsById(){let{attachments:e}=this.state.getLatestValue();return e!==this.attachmentsByIdGetterCache.attachments&&(this.attachmentsByIdGetterCache.attachments=e,this.attachmentsByIdGetterCache.attachmentsById=e.reduce((e,t)=>{var s;return t.localMetadata.id&&(e[s=t.localMetadata.id]??(e[s]=t)),e},{})),this.attachmentsByIdGetterCache.attachmentsById}get client(){return this.composer.client}get channel(){return this.composer.channel}get config(){return this.composer.config.attachments}get acceptedFiles(){return this.config.acceptedFiles}set acceptedFiles(e){this.composer.updateConfig({attachments:{acceptedFiles:e}})}get fileUploadFilter(){return this.config.fileUploadFilter}set fileUploadFilter(e){this.composer.updateConfig({attachments:{fileUploadFilter:e}})}get maxNumberOfFilesPerMessage(){return this.config.maxNumberOfFilesPerMessage}set maxNumberOfFilesPerMessage(e){e!==this.maxNumberOfFilesPerMessage&&this.composer.updateConfig({attachments:{maxNumberOfFilesPerMessage:e}})}get attachments(){return this.state.getLatestValue().attachments}get hasUploadPermission(){return!!this.channel.data?.own_capabilities?.includes("upload-file")}get isUploadEnabled(){return this.hasUploadPermission&&this.availableUploadSlots>0}get successfulUploads(){return this.getUploadsByState("finished")}get successfulUploadsCount(){return this.successfulUploads.length}get uploadsInProgressCount(){return this.getUploadsByState("uploading").length}get failedUploadsCount(){return this.getUploadsByState("failed").length}get blockedUploadsCount(){return this.getUploadsByState("blocked").length}get pendingUploadsCount(){return this.getUploadsByState("pending").length}get availableUploadSlots(){return this.config.maxNumberOfFilesPerMessage-this.successfulUploadsCount-this.uploadsInProgressCount}getUploadsByState(e){return Object.values(this.attachments).filter(({localMetadata:t})=>t.uploadState===e)}};az.toLocalUploadAttachment=e=>{var t;let s=aL(e)||ax(e)?e:aM({blobsArray:[e],fileName:aE(e.type),mimeType:e.type}),i={file_size:s.size,mime_type:s.type,localMetadata:{file:s,id:iz(),uploadState:"pending"},type:(t=s.type).startsWith("image/")&&!t.endsWith(".photoshop")?"image":t.includes("video/")?"video":t.includes("audio/")?"audio":"file"};return i[aA(s)?"fallback":"title"]=s.name,i.localMetadata.previewUri=aL(e)?e.uri:URL.createObjectURL?.(e),aL(e)&&e.height&&e.width&&aA(s)&&(i.original_height=e.height,i.original_width=e.width),aL(e)&&e.thumb_url&&(i.thumb_url=e.thumb_url),aL(e)&&e.duration&&(i.duration=e.duration),i};var aQ={attachments:{acceptedFiles:[],fileUploadFilter:()=>!0,maxNumberOfFilesPerMessage:10},drafts:{enabled:!1},linkPreviews:{debounceURLEnrichmentMs:1500,enabled:!1,findURLFn:e=>it(e,"url",{defaultProtocol:"https"}).reduce((e,t)=>{try{let s=new URL(t.href);t.isLink&&/^[a-zA-Z0-9-.]+\.[a-zA-Z]{2,}$/.test(s.hostname)&&e.push(t.href)}catch{}return e},[])},location:{enabled:!0,getDeviceId:()=>iz()},text:{enabled:!0,publishTypingEvents:!0}},aK=e=>({message:{},custom:{}}),aJ=class{constructor({composer:e,message:t}){this.isMessageDataEqual=(e,t)=>JSON.stringify(e.message)===JSON.stringify(t?.message),this.initState=({message:e}={})=>{this.state.next(aK({composer:this.composer,message:e}))},this.composer=e,this.state=new ag(aK({composer:e,message:t}))}get customMessageData(){return this.state.getLatestValue().message}get customComposerData(){return this.state.getLatestValue().custom}setMessageData(e){this.state.partialNext({message:{...this.state.getLatestValue().message,...e}})}setCustomData(e){this.state.partialNext({custom:{...this.state.getLatestValue().custom,...e}})}},aG=((d=aG||{}).DISMISSED="dismissed",d.FAILED="failed",d.LOADED="loaded",d.LOADING="loading",d.PENDING="pending",d),aY=({message:e})=>e?{previews:e.attachments?.reduce((e,t)=>
1(t.og_scrape_url&&e.set(t.og_scrape_url,{...t,status:"loaded"}),e),new Map)??new Map}:{previews:new Map},aX=class e{constructor({composer:t,message:s}){this.shouldDiscardEnrichQueries=!1,this.initState=({message:e}={})=>{this.state.next(aY({message:this.enabled?e:void 0}))},this._findAndEnrichUrls=async e=>{if(!this.enabled)return;let t=this.config.findURLFn(e);if(this.shouldDiscardEnrichQueries=!t.length,this.shouldDiscardEnrichQueries)return void this.state.next({previews:new Map});let s=new Map(Array.from(this.previews).filter(([e])=>t.includes(e)||t.includes(e+"/"))),i=t.filter(e=>{let t=this.previews;return!(t.get(e)||t.get(e+"/"))}).map(e=>({og_scrape_url:e.trim(),status:"loading"}));i.length&&(this.state.partialNext({previews:new Map([...s,...new Map(i.map(e=>[e.og_scrape_url,e]))])}),await Promise.all(i.map(async e=>{try{let{duration:t,...s}=await this.client.enrichURL(e.og_scrape_url);if(this.shouldDiscardEnrichQueries)return;this.previews.has(e.og_scrape_url)&&this.updatePreview(e.og_scrape_url,{status:"loaded",...s})}catch(t){this.previews.has(e.og_scrape_url)&&this.updatePreview(e.og_scrape_url,{status:"failed"})}return e})))},this.cancelURLEnrichment=()=>{this.findAndEnrichUrls.cancel(),this.findAndEnrichUrls.flush()},this.clearPreviews=()=>{let t=this.previews,s=new Map;t.forEach((t,i)=>{e.previewIsDismissed(t)&&s.set(i,t)}),this.state.partialNext({previews:s})},this.updatePreview=(e,t)=>{if(!e)return;let s=this.previews.get(e),i=t.status??this.previews.get(e)?.status??"pending",a=t;if(s){let e=aW(s,t);if(!e.diff||0===Object.keys(e.diff).length)return;a=e.result}this.state.partialNext({previews:new Map(this.previews).set(e,{...a,og_scrape_url:e,status:i})})},this.dismissPreview=e=>{let t=this.previews.get(e);t&&(this.onLinkPreviewDismissed?.(t),this.updatePreview(e,{status:"dismissed"}))},this.composer=t,this.state=new ag(aY({message:this.enabled?s:void 0})),this.findAndEnrichUrls=i3(this._findAndEnrichUrls.bind(this),this.config.debounceURLEnrichmentMs)}get client(){return this.composer.client}get channel(){return this.composer.channel}get previews(){return this.state.getLatestValue().previews}get loadingPreviews(){return Array.from(this.previews.values()).filter(t=>e.previewIsLoading(t))}get loadedPreviews(){return Array.from(this.previews.values()).filter(t=>e.previewIsLoaded(t))}get dismissedPreviews(){return Array.from(this.previews.values()).filter(t=>e.previewIsDismissed(t))}get failedPreviews(){return Array.from(this.previews.values()).filter(t=>e.previewIsFailed(t))}get pendingPreviews(){return Array.from(this.previews.values()).filter(t=>e.previewIsPending(t))}get config(){return this.composer.config.linkPreviews}get debounceURLEnrichmentMs(){return this.config.debounceURLEnrichmentMs}set debounceURLEnrichmentMs(e){this.cancelURLEnrichment(),this.findAndEnrichUrls=i3(this._findAndEnrichUrls.bind(this),this.config.debounceURLEnrichmentMs),this.composer.updateConfig({linkPreviews:{debounceURLEnrichmentMs:e}})}get enabled(){return!!this.channel.getConfig()?.url_enrichment&&this.composer.config.linkPreviews.enabled}set enabled(e){e!==this.enabled&&this.composer.updateConfig({linkPreviews:{enabled:e}})}get findURLFn(){return this.config.findURLFn}set findURLFn(e){this.composer.updateConfig({linkPreviews:{findURLFn:e}})}get onLinkPreviewDismissed(){return this.config.onLinkPreviewDismissed}set onLinkPreviewDismissed(e){this.composer.updateConfig({linkPreviews:{onLinkPreviewDismissed:e}})}};aX.previewIsLoading=e=>"loading"===e.status,aX.previewIsLoaded=e=>"loaded"===e.status,aX.previewIsDismissed=e=>"dismissed"===e.status,aX.previewIsFailed=e=>"failed"===e.status,aX.previewIsPending=e=>"pending"===e.status,aX.getPreviewData=e=>{let{status:t,...s}=e;return s};var aZ=({message:e})=>({location:e?.shared_location??null}),a0=class{constructor({composer:e,message:t}){this.initState=({message:e}={})=>{this.state.next(aZ({message:e}))},this.setData=e=>{!this.config.enabled||e.latitude&&e.longitude&&this.state.partialNext({location:{...e,message_id:this.composer.id,created_by_device_id:this.deviceId}})},this.composer=e,this.state=new ag(aZ({message:t})),this._deviceId=this.config.getDeviceId()}get config(){return this.composer.config.location}get deviceId(){return this._deviceId}get location(){return this.state.getLatestValue().location}get validLocation(){let{durationMs:e,...t}=this.location??{};return t?.created_by_device_id&&t.message_id&&t.latitude&&t.longitude&&(void 0===e||e>=6e4)?{...t,end_at:e&&new Date(Date.now()+e).toISOString()}:null}},a1=/^([2-9]|10)$/,a2={enforce_unique_vote:()=>({max_votes_allowed:void 0}),max_votes_allowed:({data:e,value:t})=>e.enforce_unique_vote&&t?{max_votes_allowed:"Enforce unique vote is enabled"}:!t.match(/^[0-9]+$/)&&t?{max_votes_allowed:"Only numbers are allowed"}:t?.length>1&&!t.match(a1)?{max_votes_allowed:"Type a number from 2 to 10"}:{max_votes_allowed:void 0},options:({value:e})=>{let t={},s=new Set;
1return e.forEach(e=>{s.has(e.text)&&e.text.length?t[e.id]="Option already exists":s.add(e.text)}),Object.keys(t).length>0?{options:t}:{options:void 0}}},a3={name:({currentError:e,value:t})=>t&&e?{name:void 0}:{name:"string"==typeof e?e:void 0}},a4={max_votes_allowed:({value:e})=>e&&!e.match(a1)?{max_votes_allowed:"Type a number from 2 to 10"}:{max_votes_allowed:void 0},name:({value:e})=>e.trim()?{name:void 0}:{name:"Question is required"},options:e=>{let t=a2.options?.(e),s=t?.options??{};return e.value.forEach((t,i)=>{let a=i===e.value.length-1;t.text.trim()||a||(s[t.id]="Option is empty")}),Object.keys(s).length>0?{options:s}:{options:void 0}}},a5={enforce_unique_vote:({value:e})=>({enforce_unique_vote:e,max_votes_allowed:""}),max_votes_allowed:({value:e})=>({max_votes_allowed:(e=>{if(""===e||null==e)return"";let t="string"==typeof e?parseInt(e,10):Number(e);return!Number.isInteger(t)||Number.isNaN(t)?"":String(Math.min(10,Math.max(2,t)))})(e)}),options:({value:e,data:t})=>{if(Array.isArray(e))return{options:e.map(e=>({id:e.id,text:e.text.trim()}))};let{index:s,text:i}=e,a=t.options||[],n=a&&a.slice(s+1).length>0&&!i,r=a.slice(0,s),o=a.slice(s+1),l=[...r,...n?[]:[{...a[s],text:i}],...o];return a.length<100&&!l.some(e=>!e.text.trim())&&l.push({id:iz(),text:""}),{options:l}}},a6=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/poll-composer-composition",handlers:{compose:({discard:t,forward:s})=>e.pollComposer.canCreatePoll?s():t()}}))(e)])}},a8=class extends aO{constructor(){super(),this.use([(({processors:e,validators:t}={})=>{let s=({state:e,validators:t,processors:s})=>{let i,a,{previousState:n,targetFields:r}=e;if(s||Array.isArray(a=r.options)||"number"!=typeof a?.index||"string"!=typeof a?.text)i=s?Object.entries(r).reduce((e,[t,i])=>{let a=s[t];return{...e,...a?a({data:n.data,value:i}):{[t]:i}}},{}):r;else{let e=[...n.data.options],t=n.data.options[r.options.index];t&&(t.text=r.options.text,e.splice(r.options.index,1,t)),i={...r,options:e}}let o=Object.keys(r).reduce((e,s)=>{let a=t[s];if(a){let t=a({currentError:n.errors[s],data:n.data,value:i[s]});e={...e,...t}}return e},{});return{newData:i,newErrors:o}};return{id:"stream-io/poll-composer-state-processing",handlers:{handleFieldChange:({state:i,next:a,forward:n})=>{if(!i.targetFields)return n();let{previousState:r,injectedFieldErrors:o}=i,{newData:l,newErrors:d}=s({processors:{...a5,...e?.handleFieldChange},state:i,validators:{...a2,...a3,...t?.handleFieldChange}});return a({...i,nextState:{...r,data:{...r.data,...l},errors:{...r.errors,...d,...o}}})},handleFieldBlur:({state:i,next:a,forward:n})=>{if(!i.targetFields)return n();let{previousState:r}=i,{newData:o,newErrors:l}=s({processors:e?.handleFieldBlur,state:i,validators:{...a2,...a4,...t?.handleFieldBlur}});return a({...i,nextState:{...r,data:{...r.data,...o},errors:{...r.errors,...l,...i.injectedFieldErrors}}})}}}})()])}},a7=((c=a7||{}).Chat="chat",c.Video="video",c.Moderation="moderation",c.Feeds="feeds",c),a9=class extends Error{constructor(e,{code:t,status:s,response:i}){super(e),this.name="ErrorFromResponse",this.code=t,this.response=i,this.status=s}toJSON(){let e=[["status",this.status],["code",this.code]],t=[];for(let[s,i]of e)null!=i&&t.push(`${s}: ${i}`);return{message:`(${t.join(", ")}) - ${this.message}`,stack:this.stack,name:this.name,code:this.code,status:this.status}}},ne=((h=ne||{}).anonymous="anonymous",h.public="public",h),nt=class{constructor({composer:e}){this.initState=()=>{this.state.next(this.initialState)},this.updateFields=async(e,t)=>{let{state:s,status:i}=await this.stateMiddlewareExecutor.execute({eventName:"handleFieldChange",initialValue:{nextState:{...this.state.getLatestValue()},previousState:{...this.state.getLatestValue()},targetFields:e,injectedFieldErrors:t}});"discard"!==i&&this.state.next(s.nextState)},this.handleFieldBlur=async e=>{let t=await this.stateMiddlewareExecutor.execute({eventName:"handleFieldBlur",initialValue:{nextState:{...this.state.getLatestValue()},previousState:{...this.state.getLatestValue()},targetFields:{[e]:this.state.getLatestValue().data[e]}}});"discard"!==t.status&&this.state.next(t.state.nextState)},this.compose=async()=>{let{data:e,errors:t}=this.state.getLatestValue(),s=await this.compositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{data:{...e,max_votes_allowed:e.max_votes_allowed?parseInt(e.max_votes_allowed):void 0,options:e.options?.filter(e=>e.text.trim()).map(e=>({text:e.text}))},errors:t}});if("discard"!==s.status)return s.state},this.composer=e,this.state=new ag(this.initialState),this.compositionMiddlewareExecutor=new a6({composer:e}),this.stateMiddlewareExecutor=new a8}get initialState(){return{data:{allow_answers:!1,allow_user_suggested_options:!1,description:"",enforce_unique_vote:!0,id:iz(),max_votes_allowed:"",name:"",options:[{id:iz(),text:""}],user_id:this.composer.client.user?.id,voting_visibility:"public"},errors:{}}}get allow_answers(){return this.state.getLatestValue().data.allow_answers}get allow_user_suggested_options(){return this.state.getLatestValue().data.allow_user_suggested_options}get description(){return this.state.getLatestValue().data.description}get enforce_unique_vote(){return this.state.getLatestValue().data.enforce_unique_vote}get id(){return this.state.getLatestValue().data.id}get max_votes_allowed(){return this.state.getLatestValue().data.max_votes_allowed}get name(){return this.state.getLatestValue().data.name}get options(){return this.state.getLatestValue().data.options}get user_id(){return this.state.getLatestValue().data.user_id}get voting_visibility(){return this.state.getLatestValue().data.voting_visibility}
1get canCreatePoll(){let{data:e,errors:t}=this.state.getLatestValue(),s=e.options.filter(e=>!!e.text.trim()).length>0,i=!!e.name,a=parseInt(e.max_votes_allowed?.match(a1)?.[0]||""),n=""===e.max_votes_allowed||!!a&&(2<=a||a<=10);return s&&i&&n&&0===Object.values(t).filter(e=>!!e).length}},ns=e=>{let{localMetadata:t,...s}=e;return s},ni={attachments:[],mentioned_users:[],parent_id:void 0,quoted_message:void 0,text:""},na=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/message-composer-middleware/user-data-injection",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.client.user)return i();let{channel_mutes:a,devices:n,mutes:r,...o}=e.client.user;return s({...t,localMessage:{...t.localMessage,user:o,user_id:o.id}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/poll-only",handlers:{compose:({state:t,complete:s,forward:i})=>{let a=e.pollId,n=!!e.editedMessage,r=!!e.threadId;return!a||r||n?i():s({...t,localMessage:{...t.localMessage,...ni,poll_id:a},message:{id:t.localMessage.id,poll_id:a}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/text-composition",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.textComposer)return i();let{mentionedUsers:a,text:n}=e.textComposer,r=Array.from(new Set(a.filter(({id:e,name:t})=>n.includes(`@${e}`)||n.includes(`@${t}`))));return n||0!==r.length?s({...t,localMessage:{...t.localMessage,mentioned_users:r,text:n},message:{...t.message,mentioned_users:r.map(e=>e.id),text:n}}):i()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/attachments",handlers:{compose:({state:t,next:s,discard:i,forward:a})=>{let{attachmentManager:n}=e;if(!n)return a();if(n.uploadsInProgressCount>0)return e.client.notifications.addWarning({message:"Wait until all attachments have uploaded",origin:{emitter:"MessageComposer",context:{composer:e}},options:{type:"validation:attachment:upload:in-progress"}}),i();let r=(t.message.attachments??[]).concat(n.successfulUploads.map(ns));return r.length?s({...t,localMessage:{...t.localMessage,attachments:r},message:{...t.message,attachments:r}}):a()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/link-previews",handlers:{compose:({state:t,next:s,forward:i})=>{let{linkPreviewsManager:a}=e;if(!a)return i();a.cancelURLEnrichment();let n=a.loadingPreviews.length>0,r=a.dismissedPreviews.length>0,o=a.loadingPreviews.length>0?[]:a.loadedPreviews.map(e=>aX.getPreviewData(e)),l=(t.message.attachments??[]).concat(o);if(!l.length)return i();let d={...t.sendOptions};return(!n&&o.length>0||r)&&(d.skip_enrich_url=!0),s({...t,message:{...t.message,attachments:l},localMessage:{...t.localMessage,attachments:l},sendOptions:d})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/shared-location",handlers:{compose:({state:t,next:s,forward:i})=>{let{locationComposer:a}=e,n=a.validLocation;if(!a||!n||!e.client.user)return i();let r=new Date().toISOString();return s({...t,localMessage:{...t.localMessage,shared_location:{...n,channel_cid:e.channel.cid,created_at:r,updated_at:r,user_id:e.client.user.id}},message:{...t.message,shared_location:n}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/own-state",handlers:{compose:({state:t,next:s})=>{let i={};return e.quotedMessage&&(i.quoted_message_id=e.quotedMessage.id),e.pollId&&(i.poll_id=e.pollId),e.showReplyInChannel&&(i.show_in_channel=!0),s({...t,localMessage:{...t.localMessage,...i,quoted_message:e.quotedMessage??void 0},message:{...t.message,...i}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/custom-data",handlers:{compose:({state:t,next:s,forward:i})=>{let a=e.customDataManager.customMessageData;return a?s({...t,localMessage:{...t.localMessage,...a},message:{...t.message,...a}}):i()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/data-validation",handlers:{compose:async({state:t,discard:s,forward:i})=>{let{maxLengthOnSend:a}=e.config.text??{},n=t.message.text??"",r="number"==typeof a&&n.length>a;return e.compositionIsEmpty||r?await s():await i()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/data-cleanup",handlers:{compose:({state:t,next:s})=>{let i={type:e.editedMessage?.type&&"error"!==e.editedMessage.type?e.editedMessage.type:"regular"},a=e.editedMessage?iX(e.editedMessage):void 0;
1return s({...t,localMessage:iY({...e.editedMessage,...t.localMessage,...i}),message:{...a,...t.message,...i},sendOptions:e.editedMessage&&t.sendOptions?.skip_enrich_url?{skip_enrich_url:t.sendOptions?.skip_enrich_url}:t.sendOptions})}}}))(e)])}},nn=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/message-composer-middleware/draft-text-composition",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.textComposer)return i();let{maxLengthOnSend:a}=e.config.text??{},{mentionedUsers:n,text:r}=e.textComposer,o=n.length?Array.from(new Set(n.filter(({id:e,name:t})=>r.includes(`@${e}`)||r.includes(`@${t}`)))):void 0,l="number"==typeof a&&r.length>a?r.slice(0,a):r;return s({...t,draft:{...t.draft,mentioned_users:o?.map(e=>e.id),text:l}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/draft-attachments",handlers:{compose:({state:t,next:s,forward:i})=>{let{attachmentManager:a}=e;if(!a)return i();let n=a.successfulUploads,r=n.length?(t.draft.attachments??[]).concat(n.map(ns)):void 0;return s({...t,draft:{...t.draft,attachments:r}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/draft-link-previews",handlers:{compose:({state:t,next:s,forward:i})=>{let{linkPreviewsManager:a}=e;if(!a)return i();a.cancelURLEnrichment();let n=a.loadedPreviews.map(e=>aX.getPreviewData(e));return n.length?s({...t,draft:{...t.draft,attachments:(t.draft.attachments??[]).concat(n)}}):i()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/draft-own-state",handlers:{compose:({state:t,next:s})=>{let i={};return e.quotedMessage&&(i.quoted_message_id=e.quotedMessage.id),e.pollId&&(i.poll_id=e.pollId),e.showReplyInChannel&&(i.show_in_channel=!0),s({...t,draft:{...t.draft,...i}})}}}))(e),(e=>({id:"stream-io/message-composer-middleware/draft-custom-data",handlers:{compose:({state:t,next:s,forward:i})=>{let a=e.customDataManager.customMessageData;return a?s({...t,draft:{...t.draft,...a}}):i()}}}))(e),(e=>({id:"stream-io/message-composer-middleware/draft-data-validation",handlers:{compose:async({state:t,discard:s,forward:i})=>{let a=!nk(t.draft.text??"")||t.draft.attachments?.length||t.draft.poll_id||t.draft.quoted_message_id;return e.lastChangeOriginIsLocal&&a?await i():await s()}}}))(e)])}},nr={"-1":{name:"InternalSystemError",retryable:!0},2:{name:"AccessKeyError",retryable:!1},3:{name:"AuthenticationFailedError",retryable:!0},4:{name:"InputError",retryable:!1},6:{name:"DuplicateUsernameError",retryable:!1},9:{name:"RateLimitError",retryable:!0},16:{name:"DoesNotExistError",retryable:!1},17:{name:"NotAllowedError",retryable:!1},18:{name:"EventNotSupportedError",retryable:!1},19:{name:"ChannelFeatureNotSupportedError",retryable:!1},20:{name:"MessageTooLongError",retryable:!1},21:{name:"MultipleNestingLevelError",retryable:!1},22:{name:"PayloadTooBigError",retryable:!1},23:{name:"RequestTimeoutError",retryable:!0},24:{name:"MaxHeaderSizeExceededError",retryable:!1},40:{name:"AuthErrorTokenExpired",retryable:!1},41:{name:"AuthErrorTokenNotValidYet",retryable:!1},42:{name:"AuthErrorTokenUsedBeforeIssuedAt",retryable:!1},43:{name:"AuthErrorTokenSignatureInvalid",retryable:!1},44:{name:"CustomCommandEndpointMissingError",retryable:!1},45:{name:"CustomCommandEndpointCallError",retryable:!0},46:{name:"ConnectionIDNotFoundError",retryable:!1},60:{name:"CoolDownError",retryable:!0},69:{name:"ErrWrongRegion",retryable:!1},70:{name:"ErrQueryChannelPermissions",retryable:!1},71:{name:"ErrTooManyConnections",retryable:!0},99:{name:"AppSuspendedError",retryable:!1}};function no(e){return void 0!==e.code}function nl(e){if(!e.code)return!1;let t=nr[`${e.code}`];return!!t&&t.retryable}var nd={debounceMs:300,pageSize:10},nc=class{constructor(e){this.activate=()=>{this.isActive||this.state.partialNext({isActive:!0})},this.deactivate=()=>{this.isActive&&this.state.partialNext({isActive:!1})},this.canExecuteQuery=e=>{let t=e??this.searchQuery;return!!(this.isActive&&!this.isLoading&&(this.hasNext||void 0!==e)&&t)};const{pageSize:t}={...nd,...e};this.pageSize=t,this.state=new ag(this.initialState)}get lastQueryError(){return this.state.getLatestValue().lastQueryError}get hasNext(){return this.state.getLatestValue().hasNext}get hasResults(){return Array.isArray(this.state.getLatestValue().items)}get isActive(){return this.state.getLatestValue().isActive}get isLoading(){return this.state.getLatestValue().isLoading}get initialState(){return{hasNext:!0,isActive:!1,isLoading:!1,items:void 0,lastQueryError:void 0,next:void 0,offset:0,searchQuery:""}}get items(){return this.state.getLatestValue().items}get next(){return this.state.getLatestValue().next}get offset(){return this.state.getLatestValue().offset}get searchQuery(){return this.state.getLatestValue().searchQuery}getStateBeforeFirstQuery(e){return{...this.initialState,isActive:this.isActive,isLoading:!0,searchQuery:e}}getStateAfterQuery(e,t){return{...this.state.getLatestValue(),lastQueryError:void 0,...e,isLoading:!1,items:t?e.items:[...this.items??[],...e.items||[]]}}prepareStateForQuery(e){let t=void 0!==e,s=e??this.searchQuery;return t?this.state.next(this.getStateBeforeFirstQuery(e??"")):this.state.partialNext({isLoading:!0}),{searchString:s,hasNewSearchQuery:t}}updatePaginationStateFromQuery(e){let{items:t,next:s}=e,i={};return Object.prototype.hasOwnProperty.call(e,"next")?(i.next=s,i.hasNext=!!s):(i.offset=(this.offset??0)+t.length,i.hasNext=t.length===this.pageSize),i}resetState(){this.state.next(this.initialState)}resetStateAndActivate(){this.resetState(),this.activate()}},nh=class extends nc{constructor(e){const{debounceMs:t}={...nd,...e};super(e),this.setDebounceOptions=({debounceMs:e})=>{this.searchDebounced=i3(this.executeQuery.bind(this),e)},this.search=e=>this.searchDebounced(e),this.setDebounceOptions({debounceMs:t})}async executeQuery(e){if(!this.canExecuteQuery(e))return;let{hasNewSearchQuery:t,searchString:s}=this.prepareStateForQuery(e),i={};try{let e=await this.query(s);if(!e)return;let{items:t}=e;(i=this.updatePaginationStateFromQuery(e)).items=await this.filterQueryResults(t)}catch(e){i.lastQueryError=e,no(e)&&!nl(e)&&(i.hasNext=!1)}finally{this.state.next(this.getStateAfterQuery(i,t))}}cancelScheduledQuery(){this.searchDebounced.cancel()}},nu=class extends nc{constructor(e){const{debounceMs:t}={...nd,...e};super(e),this.setDebounceOptions=({debounceMs:e})=>{this.searchDebounced=i3(this.executeQuery.bind(this),e)},this.search=e=>this.searchDebounced(e),this.setDebounceOptions({debounceMs:t})}executeQuery(e){if(!this.canExecuteQuery(e))return;let{hasNewSearchQuery:t,searchString:s}=this.prepareStateForQuery(e),i={};try{let e=this.query(s);if(!e)return;let{items:t}=e;(i=this.updatePaginationStateFromQuery(e)).items=this.filterQueryResults(t)}catch(e){i.lastQueryError=e,no(e)&&!nl(e)&&(i.hasNext=!1)}finally{this.state.next(this.getStateAfterQuery(i,t))}}cancelScheduledQuery(){this.searchDebounced.cancel()}},ng=class{constructor({config:e,sources:t}={}){this.addSource=e=>{this.state.partialNext({sources:[...this.sources,e]})}
1,this.getSource=e=>this.sources.find(t=>t.type===e),this.removeSource=e=>{let t=this.sources.filter(t=>t.type!==e);t.length!==this.sources.length&&this.state.partialNext({sources:t})},this.activateSource=e=>{let t=this.getSource(e);t&&!t.isActive&&(this.config.keepSingleActiveSource&&this.sources.forEach(t=>{t.type!==e&&t.deactivate()}),t.activate(),this.state.partialNext({sources:[...this.sources]}))},this.deactivateSource=e=>{let t=this.getSource(e);t?.isActive&&1!==this.activeSources.length&&(t.deactivate(),this.state.partialNext({sources:[...this.sources]}))},this.activate=()=>{this.activeSources.length||(this.config.keepSingleActiveSource?this.sources.slice(0,1):this.sources).forEach(e=>e.activate()),this.isActive||this.state.partialNext({isActive:!0})},this.search=async e=>{let t=this.activeSources;this.state.partialNext({searchQuery:e}),await Promise.all(t.map(t=>t.search(e)))},this.cancelSearchQueries=()=>{this.activeSources.forEach(e=>e.cancelScheduledQuery())},this.clear=()=>{this.cancelSearchQueries(),this.sources.forEach(e=>e.state.next({...e.initialState,isActive:e.isActive})),this.state.next(e=>({...e,isActive:!0,queriesInProgress:[],searchQuery:""}))},this.exit=()=>{this.cancelSearchQueries(),this.sources.forEach(e=>e.state.next({...e.initialState,isActive:e.isActive})),this.state.next(e=>({...e,isActive:!1,queriesInProgress:[],searchQuery:""}))},this.state=new ag({isActive:!1,searchQuery:"",sources:t??[]}),this._internalState=new ag({}),this.config={keepSingleActiveSource:!0,...e}}get hasNext(){return this.sources.some(e=>e.hasNext)}get sources(){return this.state.getLatestValue().sources}get activeSources(){return this.state.getLatestValue().sources.filter(e=>e.isActive)}get isActive(){return this.state.getLatestValue().isActive}get searchQuery(){return this.state.getLatestValue().searchQuery}get searchSourceTypes(){return this.sources.map(e=>e.type)}},np={debounceMs:300,pageSize:10},nm=class{constructor(e){this._isCursorPagination=!1,this.setDebounceOptions=({debounceMs:e})=>{this._executeQueryDebounced=i3(this.executeQuery.bind(this),e)},this.canExecuteQuery=e=>!this.isLoading&&"next"===e&&this.hasNext||"prev"===e&&this.hasPrev,this.next=()=>this.executeQuery({direction:"next"}),this.prev=()=>this.executeQuery({direction:"prev"}),this.nextDebounced=()=>{this._executeQueryDebounced({direction:"next"})},this.prevDebounced=()=>{this._executeQueryDebounced({direction:"prev"})};const{debounceMs:t,pageSize:s}={...np,...e};this.pageSize=s,this.state=new ag(this.initialState),this.setDebounceOptions({debounceMs:t})}get lastQueryError(){return this.state.getLatestValue().lastQueryError}get hasNext(){return this.state.getLatestValue().hasNext}get hasPrev(){return this.state.getLatestValue().hasPrev}get hasResults(){return Array.isArray(this.state.getLatestValue().items)}get isLoading(){return this.state.getLatestValue().isLoading}get initialState(){return{hasNext:!0,hasPrev:!0,isLoading:!1,items:void 0,lastQueryError:void 0,cursor:void 0,offset:0}}get items(){return this.state.getLatestValue().items}get cursor(){return this.state.getLatestValue().cursor}get offset(){return this.state.getLatestValue().offset}getStateBeforeFirstQuery(){return{...this.initialState,isLoading:!0}}getStateAfterQuery(e,t){return{...this.state.getLatestValue(),lastQueryError:void 0,...e,isLoading:!1,items:t?e.items:[...this.items??[],...e.items||[]]}}async executeQuery({direction:e}){if(!this.canExecuteQuery(e))return;let t=void 0===this.items;t?this.state.next(this.getStateBeforeFirstQuery()):this.state.partialNext({isLoading:!0});let s={};try{let i=await this.query({direction:e});if(!i)return;let{items:a,next:n,prev:r}=i;t&&(n||r)&&(this._isCursorPagination=!0),this._isCursorPagination?(s.cursor={next:n||null,prev:r||null},s.hasNext=!!n,s.hasPrev=!!r):(s.offset=(this.offset??0)+a.length,s.hasNext=a.length===this.pageSize),s.items=await this.filterQueryResults(a)}catch(e){s.lastQueryError=e}finally{this.state.next(this.getStateAfterQuery(s,t))}}cancelScheduledQuery(){this._executeQueryDebounced.cancel()}resetState(){this.state.next(this.initialState)}},nf=class{constructor(e){this.context=new ag(e?.initialContext??{}),this.filterConfig=new ag(e?.initialFilterConfig??{})}updateFilterConfig(e){this.filterConfig.partialNext(e)}enableFilter(e){let t=this.filterConfig.getLatestValue();t[e]&&this.filterConfig.partialNext({[e]:{...t[e],enabled:!0}})}disableFilter(e){let t=this.filterConfig.getLatestValue();t[e]&&this.filterConfig.partialNext({[e]:{...t[e],enabled:!1}})}updateContext(e){this.context.partialNext(e)}buildFilters(e){let t={...e?.baseFilters??{}},s=this.filterConfig.getLatestValue();for(let i in s){let a=s[i];if(!a?.enabled)continue;let n=a.generate({...this.context.getLatestValue(),...e?.context??{}});n&&Object.assign(t,n)}return t}},ny=class extends nm{constructor(e,t){super(t),this.query=async({direction:e})=>{let t=this.cursor?.[e],{reminders:s,next:i,prev:a}=await this.client.queryReminders({filter:this.filters,sort:this.sort,limit:this.pageSize,[e]:t});return{items:s,next:i,prev:a}},this.filterQueryResults=e=>e,this.client=e}get filters(){return this._filters}get sort(){return this._sort}set filters(e){this._filters=e,this.resetState()}set sort(e){this._sort=e,this.resetState()}},nb=class extends nh{constructor(e,t,s={}){super(t),this.type="users",this.client=e,this.filterBuilder=new nf({initialFilterConfig:{$or:{enabled:!0,generate:({searchQuery:e})=>e?{$or:[{id:{$autocomplete:e}},{name:{$autocomplete:e}}]}:null}},...s})}async query(e){let t=this.filterBuilder.buildFilters({baseFilters:this.filters,context:{searchQuery:e}}),s={id:1,...this.sort},i={...this.searchOptions,limit:this.pageSize,offset:this.offset},{users:a}=await this.client.queryUsers(t,s,i);return{items:a}}filterQueryResults(e){return e.filter(e=>e.id!==this.client.user?.id)}},n_=class extends nh{constructor(e,t,s={}){super(t),this.type="channels",this.client=e,this.filterBuilder=new nf({...s,initialFilterConfig:{name:{enabled:!0,generate:({searchQuery:e})=>e?{name:{$autocomplete:e}}:null},...s.initialFilterConfig}})}async query(e){let t=this.filterBuilder.buildFilters({baseFilters:{...this.client.userID?{members:{$in:[this.client.userID]}}:{},...this.filters},context:{searchQuery:e}}),s=this.sort??{},i={...this.searchOptions,limit:this.pageSize,offset:this.offset};return{items:await this.client.queryChannels(t,s,i)}}filterQueryResults(e){return e}},nw=class extends nh{constructor(e,t,s){super(t),this.type="messages",this.client=e,this.messageSearchChannelFilterBuilder=new nf(s?.messageSearchChannel),this.messageSearchFilterBuilder=new nf({...s?.messageSearch,initialFilterConfig:{text:{enabled:!0,generate:({searchQuery:e})=>e?{text:e}:null},...s?.messageSearch?.initialFilterConfig}}),this.channelQueryFilterBuilder=new nf({...s?.channelQuery,initialFilterConfig:{cid:{enabled:!0,generate:({cids:e})=>e?{cid:{$in:e}}:null},...s?.channelQuery?.initialFilterConfig}})}async query(e){if(!this.client.userID||!e||null===this.next)return{items:[]};let t=this.messageSearchChannelFilterBuilder.buildFilters({baseFilters:{...this.client.userID?{members:{$in:[this.client.userID]}}:{},...this.messageSearchChannelFilters},context:{searchQuery:e}}),s=this.messageSearchFilterBuilder.buildFilters({baseFilters:{type:"regular",...this.messageSearchFilters},context:{searchQuery:e}}),i={created_at:-1,...this.messageSearchSort},a={limit:this.pageSize,next:this.next,sort:i},{next:n,results:r}=await this.client.search(t,s,a),o=r.map(({message:e})=>e),l=Array.from(o.reduce((e,t)=>
1(t.cid&&!this.client.activeChannels[t.cid]&&e.add(t.cid),e),new Set));if(l.length>0){let e=this.channelQueryFilterBuilder.buildFilters({baseFilters:this.channelQueryFilters,context:{cids:l}});await this.client.queryChannels(e,{last_message_at:-1,...this.channelQuerySort},this.channelQueryOptions)}return{items:o,next:n}}filterQueryResults(e){return e}},nv=({trigger:e,text:t,isCommand:s=!1,acceptTrailingSpaces:i=!0})=>{let a=nS(e),n=`[^\\s${a}]*`,r=t.match(RegExp(s?`^[${a}]${n}$`:i?`(?!^|\\W)?[${a}]${n}\\s?${n}$`:`(?!^|\\W)?[${a}]${n}$`,"g"));return r&&r[r.length-1].trim()},nC=({insertText:e,selection:t,text:s,trigger:i})=>{let a=s.slice(0,t.end),n=s.slice(t.end),r=a.lastIndexOf(i);return{text:a.slice(0,r)+e+n,selection:{start:r+e.length,end:r+e.length}}};function nS(e){return e.replace(/[-[\]{}()*+?.,/\\^$|#]/g,"\\$&")}var nR=class extends nu{constructor(e,t){super(t),this.type="commands",this.canExecuteQuery=e=>this.isActive&&!this.isLoading&&(this.hasNext||void 0!==e),this.channel=e}getStateBeforeFirstQuery(e){let t=super.getStateBeforeFirstQuery(e),{items:s}=this.state.getLatestValue();return{...t,items:s}}query(e){let t=this.channel.getConfig(),s=(t?.commands||[]).filter(t=>!!(t.name&&-1!==t.name.toLowerCase().indexOf(e.toLowerCase())));return s.sort((t,s)=>{let i=t.name?.toLowerCase(),a=s.name?.toLowerCase();if(i?.indexOf(e)===0&&(i=`0${i}`),a?.indexOf(e)===0&&(a=`0${a}`),null!=i&&null!=a){if(i<a)return -1;if(i>a)return 1}return 0}),{items:s.map(e=>({...e,id:e.name})),next:null}}filterQueryResults(e){return e}},nU={minChars:1,trigger:"/"},nI={a:"á|à|ã|â|À|Á|Ã|Â",c:"ç|Ç",e:"é|è|ê|É|È|Ê",i:"í|ì|î|Í|Ì|Î",n:"ñ|Ñ",o:"ó|ò|ô|ő|õ|Ó|Ò|Ô|Õ",u:"ú|ù|û|ü|Ú|Ù|Û|Ü"},nx=e=>e?Object.keys(nI).reduce((e,t)=>e.replace(RegExp(nI[t],"g"),t),e):"",nL=(e,t)=>{let s,i;if(0===e.length)return t.length;if(0===t.length)return e.length;let a=[];for(s=0;s<=t.length;s++)a[s]=[s];for(i=0;i<=e.length;i++)a[0][i]=i;for(s=1;s<=t.length;s++)for(i=1;i<=e.length;i++)t.charAt(s-1)===e.charAt(i-1)?a[s][i]=a[s-1][i-1]:a[s][i]=Math.min(a[s-1][i-1]+1,Math.min(a[s][i-1]+1,a[s-1][i]+1));return a[t.length][e.length]},nM=class extends nh{constructor(e,t){const{mentionAllAppUsers:s,textComposerText:i,transliterate:a,...n}=t||{};super(n),this.type="mentions",this.toUserSuggestion=e=>({...e,...(({displayName:e,searchToken:t})=>({tokenizedDisplayName:{token:t,parts:t?e.split(RegExp(`(${nS(t)})`,"gi")).filter(Boolean):[e]}}))({displayName:e.name||e.id,searchToken:this.searchQuery})}),this.canExecuteQuery=e=>this.isActive&&!this.isLoading&&(void 0!==e||this.hasNext),this.transliterate=e=>e,this.getMembersAndWatchers=()=>{let e=[...Object.values(this.channel.state.members??{}).map(({user:e})=>e),...Object.values(this.channel.state.watchers??{})],t={};return e.forEach(e=>{e&&!t[e.id]&&(t[e.id]=e)}),Object.values(t)},this.searchMembersLocally=e=>{let{textComposerText:t}=this.config;return t?this.getMembersAndWatchers().filter(s=>{if(s.id===this.client.userID)return!1;if(!e)return!0;let i=this.transliterate(nx(s.id)).toLowerCase(),a=this.transliterate(nx(s.name)).toLowerCase(),n=this.transliterate(nx(e)).toLowerCase(),r=t.slice(-4).includes("@");if(a){let e=nL(n,a);if(a.includes(n)||e<=3&&r)return!0}let o=nL(n,i);return i.includes(n)||o<=3&&r}).sort((e,t)=>{if(!this.memberSort)return(e.name||"").localeCompare(t.name||"");for(let[s,i]of Object.entries(this.memberSort)){let a=e[s],n=t[s];if(a!==n)return 1===i?String(a||"").localeCompare(String(n||"")):String(n||"").localeCompare(String(a||""))}return 0}):[]},this.prepareQueryUsersParams=e=>({filters:{$or:[{id:{$autocomplete:e}},{name:{$autocomplete:e}}],...this.userFilters},sort:this.userSort??[{name:1},{id:1}],options:{...this.searchOptions,limit:this.pageSize,offset:this.offset}}),this.prepareQueryMembersParams=e=>{let t=[{user_id:1}];return this.memberSort?Array.isArray(this.memberSort)?t=this.memberSort[0]:1===Object.keys(this.memberSort).length&&(t=this.memberSort):t=[{user_id:1}],{filters:this.memberFilters??{name:{$autocomplete:e}},sort:t,options:{...this.searchOptions,limit:this.pageSize,offset:this.offset}}},this.queryUsers=async e=>{let{filters:t,sort:s,options:i}=this.prepareQueryUsersParams(e),{users:a}=await this.client.queryUsers(t,s,i);return a},this.queryMembers=async e=>{let{filters:t,sort:s,options:i}=this.prepareQueryMembersParams(e);
1return(await this.channel.queryMembers(t,s,i)).members.map(e=>e.user)},this.filterMutes=e=>{let{textComposerText:t}=this.config;if(!t)return[];let{mutedUsers:s}=this.client;return t.includes("/unmute")&&!s.length?[]:s.length?t.includes("/unmute")?e.filter(e=>s.some(t=>t.target.id===e.id)):e.filter(e=>s.every(t=>t.target.id!==e.id)):e},this.client=e.getClient(),this.channel=e,this.config={mentionAllAppUsers:s,textComposerText:i},a&&(this.transliterate=a)}get allMembersLoadedWithInitialChannelQuery(){return Object.keys(this.channel.state.members||{}).length<100}getStateBeforeFirstQuery(e){let t=super.getStateBeforeFirstQuery(e),{items:s}=this.state.getLatestValue();return{...t,items:s}}async query(e){let t=this.allMembersLoadedWithInitialChannelQuery||!e;return{items:(this.config.mentionAllAppUsers?await this.queryUsers(e):t?this.searchMembersLocally(e):await this.queryMembers(e)).map(this.toUserSuggestion)}}filterQueryResults(e){return this.filterMutes(e)}},nE={minChars:1,trigger:"@"},nA=class extends aO{constructor({composer:e}){super(),this.use([(e=>({id:"stream-io/text-composer/pre-validation-middleware",handlers:{onChange:({state:t,next:s,forward:i})=>{let{maxLengthOnEdit:a}=e.config.text??{};return"number"==typeof a&&t.text.length>a?(t.text=t.text.slice(0,a),s({...t,text:t.text})):i()},onSuggestionItemSelect:({forward:e})=>e()}}))(e),((e,t)=>{let s,i=aV(nE,t??{});return t?.searchSource?(s=t.searchSource).resetState():s=new nM(e),s.activate(),{id:"stream-io/text-composer/mentions-middleware",handlers:{onChange:({state:e,next:t,complete:a,forward:n})=>{if(!e.selection)return n();let r=nv({trigger:i.trigger,text:e.text.slice(0,e.selection.end)});if(r&&r.length===i.minChars&&s.resetStateAndActivate(),!r||r.length<i.minChars){let s=e.suggestions?.trigger===i.trigger,a={...e};return s&&delete a.suggestions,t(a)}return s.config.textComposerText=e.text,a({...e,suggestions:{query:r.slice(1),searchSource:s,trigger:i.trigger}})},onSuggestionItemSelect:({state:e,complete:t,forward:a})=>{let{selectedSuggestion:n}=e.change??{};return n&&e.suggestions?.trigger===i.trigger?(s.resetStateAndActivate(),t({...e,...nC({insertText:`@${n.name||n.id} `,selection:e.selection,text:e.text,trigger:i.trigger}),mentionedUsers:e.mentionedUsers.concat((e=>{let{tokenizedDisplayName:t,...s}=e;return s})(n)),suggestions:void 0})):a()}}}})(e.channel),((e,t)=>{let s=aV(nU,t??{}),i=new nR(e);return t?.searchSource&&(i=t.searchSource).resetState(),i.activate(),{id:"stream-io/text-composer/commands-middleware",handlers:{onChange:({state:e,next:t,complete:a,forward:n})=>{let r;if(!e.selection)return n();let o=e.text.slice(0,e.selection.end),l=(r=o.match(/^\/(\S+)\s+.*/))&&r[1];if(l){let s=i?.query(l).items[0];if(s)return t({...e,command:s,suggestions:void 0})}let d=nv({trigger:s.trigger,text:o,acceptTrailingSpaces:!1,isCommand:!0});if(d&&d.length===s.minChars&&i.resetStateAndActivate(),!d||d.length<s.minChars){let i=e.suggestions?.trigger===s.trigger,a={...e};return i&&delete a.suggestions,t(a)}return a({...e,command:null,suggestions:{query:d.slice(1),searchSource:i,trigger:s.trigger}})},onSuggestionItemSelect:({state:e,next:t,forward:a})=>{let{selectedSuggestion:n}=e.change??{};return n&&e.suggestions?.trigger===s.trigger?(i.resetStateAndActivate(),t({...e,...nC({insertText:`/${n.name} `,selection:e.selection,text:e.text,trigger:s.trigger}),command:n,suggestions:void 0})):a()}}}})(e.channel)])}async execute({eventName:e,initialValue:t}){let s=await this.executeMiddlewareChain({eventName:e,initialValue:t}),{query:i,searchSource:a}=s.state.suggestions??{};return a?.search(i)?.catch(console.error),s}},nk=e=>{let t=e.trim();return""===t||">"===t||"``````"===t||"``"===t||"**"===t||"____"===t||"__"===t||"****"===t},nD=({composer:e,message:t})=>{if(!t){let t=e.config.text.defaultValue??"";return{command:null,mentionedUsers:[],text:t,selection:{start:t.length,end:t.length}}}let s=t.text??"";return{mentionedUsers:(t.mentioned_users??[]).map(e=>"string"==typeof e?{id:e}:e),text:s,selection:{start:s.length,end:s.length}}},nT=class{constructor({composer:e,message:t}){this.initState=({message:e}={})=>{this.state.next(nD({composer:this.composer,message:e}))},this.upsertMentionedUser=e=>{let t=[...this.mentionedUsers],s=t.findIndex(t=>t.id===e.id);s>=0?t.splice(s,1,e):t.push(e),this.state.partialNext({mentionedUsers:t})},this.getMentionedUser=e=>this.state.getLatestValue().mentionedUsers.find(t=>
1t.id===e),this.removeMentionedUser=e=>{let t=this.mentionedUsers.findIndex(t=>t.id===e);if(-1===t)return;let s=[...this.mentionedUsers];s.splice(t,1),this.state.partialNext({mentionedUsers:s})},this.setCommand=e=>{e?.name!==this.command?.name&&this.state.partialNext({command:e})},this.setText=e=>{this.enabled&&e!==this.text&&this.state.partialNext({text:e})},this.setSelection=e=>{let t=e.start!==this.selection.start||e.end!==this.selection.end;this.enabled&&t&&this.state.partialNext({selection:e})},this.insertText=async({text:e,selection:t})=>{if(!this.enabled)return;let s=e.replace(/\r\n/g,"\n"),i=t??this.selection,{maxLengthOnEdit:a}=this.composer.config.text??{},n=this.text,r=[n.slice(0,i.start),s,n.slice(i.end)].join(""),o=r.slice(0,"number"==typeof a?a:r.length),l=Math.min(i.start+s.length,o.length);await this.handleChange({text:o,selection:{start:l,end:l}})},this.wrapSelection=({head:e="",selection:t,tail:s=""})=>{if(!this.enabled)return;let i=t??this.selection,a=this.text.slice(0,i.start),n=this.text.slice(i.start,i.end),r=this.text.slice(i.end),o={start:a.length+e.length,end:a.length+e.length+n.length};this.state.partialNext({text:[a,e,n,s,r].join(""),selection:o})},this.setSuggestions=e=>{this.state.partialNext({suggestions:e})},this.closeSuggestions=()=>{let{suggestions:e}=this.state.getLatestValue();e&&this.state.partialNext({suggestions:void 0})},this.handleChange=async({text:e,selection:t})=>{if(!this.enabled)return;let s=await this.middlewareExecutor.execute({eventName:"onChange",initialValue:{...this.state.getLatestValue(),text:e,selection:t}});"discard"!==s.status&&(this.state.next(s.state),this.config.publishTypingEvents&&e&&ij(this.channel.keystroke(this.composer.threadId??void 0),"start typing event"))},this.handleSelect=async e=>{if(!this.enabled)return;let t=await this.middlewareExecutor.execute({eventName:"onSuggestionItemSelect",initialValue:{...this.state.getLatestValue(),change:{selectedSuggestion:e}}});t?.status!=="discard"&&this.state.next(t.state)},this.composer=e,this.state=new ag(nD({composer:e,message:t})),this.middlewareExecutor=new nA({composer:e})}get channel(){return this.composer.channel}get config(){return this.composer.config.text}get enabled(){return this.composer.config.text.enabled}set enabled(e){e!==this.enabled&&this.composer.updateConfig({text:{enabled:e}})}get defaultValue(){return this.composer.config.text.defaultValue}set defaultValue(e){e!==this.defaultValue&&this.composer.updateConfig({text:{defaultValue:e}})}get maxLengthOnEdit(){return this.composer.config.text.maxLengthOnEdit}set maxLengthOnEdit(e){e!==this.maxLengthOnEdit&&this.composer.updateConfig({text:{maxLengthOnEdit:e}})}get maxLengthOnSend(){return this.composer.config.text.maxLengthOnSend}set maxLengthOnSend(e){e!==this.maxLengthOnSend&&this.composer.updateConfig({text:{maxLengthOnSend:e}})}get publishTypingEvents(){return this.composer.config.text.publishTypingEvents}set publishTypingEvents(e){e!==this.publishTypingEvents&&this.composer.updateConfig({text:{publishTypingEvents:e}})}get command(){return this.state.getLatestValue().command}get mentionedUsers(){return this.state.getLatestValue().mentionedUsers}get selection(){return this.state.getLatestValue().selection}get suggestions(){return this.state.getLatestValue().suggestions}get text(){return this.state.getLatestValue().text}get textIsEmpty(){return nk(this.text)}setMentionedUsers(e){this.state.partialNext({mentionedUsers:e})}clearCommand(){this.state.partialNext({command:null})}},nP=50,nO=[{created_at:-1}],nN={active_participant_count:!0,channel:!0,channel_cid:!0,created_at:!0,created_by:!0,created_by_user_id:!0,deleted_at:!0,draft:!0,last_message_at:!0,latest_replies:!0,parent_message:!0,parent_message_id:!0,participant_count:!0,read:!0,reply_count:!0,thread_participants:!0,title:!0,updated_at:!0},nF=e=>{let t={};for(let s in e)nN[s]||(t[s]=e[s]);return t},nq=class extends af{constructor({client:e,threadData:t}){super(),this.failedRepliesMap=new Map,this.activate=()=>{this.state.partialNext({active:!0})},this.deactivate=()=>{this.state.partialNext({active:!1})},this.reload=async()=>
1{if(!this.state.getLatestValue().isLoading){this.state.partialNext({isLoading:!0});try{let e=await this.client.getThread(this.id,{watch:!0});this.hydrateState(e)}finally{this.state.partialNext({isLoading:!1})}}},this.hydrateState=e=>{if(e===this)return;if(e.id!==this.id)throw Error("Cannot hydrate thread's state using thread with different threadId");let{createdAt:t,custom:s,title:i,deletedAt:a,parentMessage:n,participants:r,read:o,replyCount:l,replies:d,updatedAt:c}=e.state.getLatestValue(),h=Array.from(this.failedRepliesMap.values());this.state.partialNext({title:i,createdAt:t,custom:s,deletedAt:a,parentMessage:n,participants:r,read:o,replyCount:l,replies:h.length?d.concat(h):d,updatedAt:c,isStateStale:!1})},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeThreadUpdated()),this.addUnsubscribeFunction(this.subscribeMarkActiveThreadRead()),this.addUnsubscribeFunction(this.subscribeReloadActiveStaleThread()),this.addUnsubscribeFunction(this.subscribeMarkThreadStale()),this.addUnsubscribeFunction(this.subscribeNewReplies()),this.addUnsubscribeFunction(this.subscribeRepliesRead()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeMessageUpdated()))},this.subscribeThreadUpdated=()=>this.client.on("thread.updated",e=>{if(!e.thread||e.thread.parent_message_id!==this.id)return;let t=e.thread;this.state.partialNext({title:t.title,updatedAt:new Date(t.updated_at),deletedAt:t.deleted_at?new Date(t.deleted_at):null,custom:nF(t)})}).unsubscribe,this.subscribeMarkActiveThreadRead=()=>this.state.subscribeWithSelector(e=>({active:e.active,unreadMessageCount:n$(this.client.userID)(e)}),({active:e,unreadMessageCount:t})=>{e&&t&&this.throttledMarkAsRead()}),this.subscribeReloadActiveStaleThread=()=>this.state.subscribeWithSelector(e=>({active:e.active,isStateStale:e.isStateStale}),({active:e,isStateStale:t})=>{e&&t&&this.reload()}),this.subscribeMarkThreadStale=()=>this.client.on("user.watching.stop",e=>{let{channel:t}=this.state.getLatestValue();this.client.userID&&this.client.userID===e.user?.id&&e.channel?.cid===t.cid&&this.state.partialNext({isStateStale:!0})}).unsubscribe,this.subscribeNewReplies=()=>this.client.on("message.new",e=>{if(!this.client.userID||e.message?.parent_id!==this.id)return;let t=e.message.user?.id===this.client.userID,{active:s,read:i}=this.state.getLatestValue();this.upsertReplyLocally({message:e.message,timestampChanged:t}),s&&this.throttledMarkAsRead();let a={};for(let t of Object.keys(i)){let n=i[t];if(n){let i=n;t===e.user?.id?i={...i,lastReadAt:e.created_at?new Date(e.created_at):new Date,user:e.user,unreadMessageCount:0}:s&&t===this.client.userID||(i={...i,unreadMessageCount:n.unreadMessageCount+1}),a[t]=i}}this.state.partialNext({read:a})}).unsubscribe,this.subscribeRepliesRead=()=>this.client.on("message.read",e=>{if(!e.user||!e.created_at||!e.thread||e.thread.parent_message_id!==this.id)return;let t=e.user.id,s=e.created_at,i=e.user;this.state.next(a=>({...a,read:{...a.read,[t]:{lastReadAt:new Date(s),user:i,lastReadMessageId:e.last_read_message_id,unreadMessageCount:0}}}))}).unsubscribe,this.subscribeMessageDeleted=()=>this.client.on("message.deleted",e=>{e.message&&(e.message.parent_id===this.id&&(e.hard_delete?this.deleteReplyLocally({message:e.message}):this.upsertReplyLocally({message:e.message})),e.message.id===this.id&&this.updateParentMessageLocally({message:e.message}))}).unsubscribe,this.subscribeMessageUpdated=()=>{let e=["message.updated","reaction.new","reaction.deleted","reaction.updated"].map(e=>this.client.on(e,e=>{e.message&&this.updateParentMessageOrReplyLocally(e.message)}).unsubscribe);return()=>e.forEach(e=>e())},this.unregisterSubscriptions=()=>{let e=super.unregisterSubscriptions();return this.state.partialNext({isStateStale:!0}),e},this.deleteReplyLocally=({message:e})=>{let{replies:t}=this.state.getLatestValue(),s=i1({needle:iY(e),sortedArray:t,sortDirection:"ascending",selectValueToCompare:e=>e.created_at.getTime(),selectKey:e=>e.id});if(t[s]?.id!==e.id)return;let i=[...t];i.splice(s,1),this.state.partialNext({replies:i})},this.upsertReplyLocally=({message:e,timestampChanged:t=!1})=>{if(e.parent_id!==this.id)throw Error("Reply does not belong to this thread");let s=iY(e);"failed"===e.status?this.failedRepliesMap.set(s.id,s):this.failedRepliesMap.has(e.id)&&this.failedRepliesMap.delete(e.id),this.state.next(e=>({...e,replies:i2(e.replies,s,t)}))},this.updateParentMessageLocally=({message:e})=>
1{if(e.id!==this.id)throw Error("Message does not belong to this thread");this.state.next(t=>{let s=iY(e);return{...t,deletedAt:s.deleted_at,parentMessage:s,replyCount:e.reply_count??t.replyCount}})},this.updateParentMessageOrReplyLocally=e=>{e.parent_id===this.id&&this.upsertReplyLocally({message:e}),e.parent_id||e.id!==this.id||this.updateParentMessageLocally({message:e})},this.markAsRead=async({force:e=!1}={})=>0!==this.ownUnreadCount||e?await this.client.messageDeliveryReporter.markRead(this):null,this.throttledMarkAsRead=i4(()=>this.markAsRead(),1e3,{trailing:!0}),this.queryReplies=({limit:e=nP,sort:t=nO,...s}={})=>this.channel.getReplies(this.id,{limit:e,...s},t),this.loadNextPage=({limit:e=nP}={})=>this.loadPage(e),this.loadPrevPage=({limit:e=nP}={})=>this.loadPage(-e),this.loadPage=async e=>{let{pagination:t}=this.state.getLatestValue(),[s,i,a]=e>0?["isLoadingNext","nextCursor","push"]:["isLoadingPrev","prevCursor","unshift"];if(t[s]||null===t[i])return;let n={[e>0?"id_gt":"id_lt"]:t[i]},r=Math.abs(e);this.state.partialNext({pagination:{...t,[s]:!0}});try{let t=await this.queryReplies({...n,limit:r}),o=t.messages.map(iY),l=o.at(e>0?-1:0)?.id??null;this.state.next(e=>{let n=e.replies;return o.length>0&&(n=[...e.replies])[a](...o),{...e,replies:n,pagination:{...e.pagination,[i]:t.messages.length<r?null:l,[s]:!1}}})}catch(e){this.client.logger("error",e.message),this.state.next(e=>({...e,pagination:{...e.pagination,[s]:!1}}))}};
1const s=e.channel(t.channel.type,t.channel.id,{name:t.channel.name});s._hydrateMembers({members:t.channel.members??[],overrideCurrentState:!1});const i=e.userID?[{user:{id:e.userID},unread_messages:0,last_read:new Date().toISOString()}]:[];this.state=new ag({active:!1,isLoading:!1,isStateStale:!1,channel:s,createdAt:new Date(t.created_at),deletedAt:t.deleted_at?new Date(t.deleted_at):null,pagination:nB(t),parentMessage:iY(t.parent_message),participants:t.thread_participants,read:nj(t.read&&0!==t.read.length?t.read:i),replies:t.latest_replies.map(iY),replyCount:t.reply_count??0,updatedAt:t.updated_at?new Date(t.updated_at):null,title:t.title,custom:nF(t)}),this.id=t.parent_message_id,this.client=e,this.messageComposer=new nz({client:e,composition:t.draft,compositionContext:this})}get channel(){return this.state.getLatestValue().channel}get hasStaleState(){return this.state.getLatestValue().isStateStale}get ownUnreadCount(){return n$(this.client.userID)(this.state.getLatestValue())}},nj=e=>e.reduce((e,t)=>(e[t.user.id]={user:t.user,lastReadMessageId:t.last_read_message_id,unreadMessageCount:t.unread_messages??0,lastReadAt:new Date(t.last_read)},e),{}),nB=e=>({nextCursor:null,prevCursor:e.latest_replies.length===e.reply_count?null:e.latest_replies.at(0)?.id??null,isLoadingNext:!1,isLoadingPrev:!1}),n$=e=>t=>e&&t.read[e]?.unreadMessageCount||0,nV=e=>!!e?.message,nW=e=>{let t;if(!e)return{draftId:null,id:nz.generateId(),pollId:null,quotedMessage:null,showReplyInChannel:!1,editedMessage:null};let s=e.quoted_message,i=nV(e)?null:iY(e),a=null,n=nz.generateId();return nV(e)?(t=e.message,a=e.message.id):(t=e,n=e.id),{draftId:a,id:n,pollId:t.poll_id??null,quotedMessage:s?iY(s):null,showReplyInChannel:!1,editedMessage:i}},nH=class e extends af{constructor({composition:t,config:s,compositionContext:i,client:a}){let n;if(super(),this.setEditedMessage=e=>{this.state.partialNext({editedMessage:e??null})},this.refreshId=()=>{this.state.partialNext({id:e.generateId()})},this.initState=({composition:e}={})=>{this.editingAuditState.partialNext(this.initEditingAuditState(e));let t=void 0===e?e:nV(e)?e.message:iY(e);this.attachmentManager.initState({message:t}),this.linkPreviewsManager.initState({message:t}),this.locationComposer.initState({message:t}),this.textComposer.initState({message:t}),this.pollComposer.initState(),this.customDataManager.initState({message:t}),this.state.next(nW(e))},this.initStateFromChannelResponse=e=>{this.channel.cid===e.channel.cid&&(e.draft?this.initState({composition:e.draft}):this.state.getLatestValue().draftId&&(this.clear(),this.client.offlineDb?.executeQuerySafely(e=>e.deleteDraft({cid:this.channel.cid,parent_id:void 0}),{method:"deleteDraft"})))},this.initEditingAuditState=e=>{let t,s;return t=null,s=new Date().getTime(),nV(e)?s=t=new Date(e.created_at).getTime():e&&e.created_at.getTime&&(s=new Date(e.updated_at).getTime()),{lastChange:{draftUpdate:t,stateUpdate:s}}},this.registerDraftEventSubscriptions=()=>{let e=this.subscribeDraftUpdated(),t=this.subscribeDraftDeleted();return()=>{e(),t()}},this.registerSubscriptions=()=>(this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeMessageComposerSetupStateChange()),this.addUnsubscribeFunction(this.subscribeMessageUpdated()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeTextComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeAttachmentManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeLinkPreviewsManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeLocationComposerStateChanged()),this.addUnsubscribeFunction(this.subscribePollComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeCustomDataManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeMessageComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeMessageComposerConfigStateChanged())),this.incrementRefCount(),()=>this.unregisterSubscriptions()),this.subscribeMessageUpdated=()=>{let e=["message.updated","reaction.new","reaction.deleted","reaction.updated"].map(e=>this.client.on(e,e=>{e.message&&(e.message.id===this.id&&this.initState({composition:e.message}),this.quotedMessage?.id&&e.message.id===this.quotedMessage.id&&this.setQuotedMessage(iY(e.message)))}).unsubscribe);return()=>
1e.forEach(e=>e())},this.subscribeMessageComposerSetupStateChange=()=>{let e=null,t=this.client._messageComposerSetupState.subscribeWithSelector(({setupFunction:e})=>({setup:e}),({setup:t})=>{e?.(),e=t?.({composer:this})??null});return()=>{e?.(),t()}},this.subscribeMessageDeleted=()=>this.client.on("message.deleted",e=>{e.message&&(e.message.id===this.id?this.clear():this.quotedMessage&&e.message.id===this.quotedMessage.id&&this.setQuotedMessage(null))}).unsubscribe,this.subscribeDraftUpdated=()=>this.client.on("draft.updated",e=>{let t=e.draft;t&&(t.parent_id??null)===(this.threadId??null)&&t.channel_cid===this.channel.cid&&this.initState({composition:t})}).unsubscribe,this.subscribeDraftDeleted=()=>this.client.on("draft.deleted",e=>{let t=e.draft;!t||(t.parent_id??null)!==(this.threadId??null)||t.channel_cid!==this.channel.cid||(this.logDraftUpdateTimestamp(),this.compositionIsEmpty||this.clear())}).unsubscribe,this.subscribeTextComposerStateChanged=()=>this.textComposer.state.subscribeWithSelector(({text:e})=>[e],([e],t)=>{void 0===t||((this.logStateUpdateTimestamp(),this.compositionIsEmpty)?this.deleteDraft():this.linkPreviewsManager.enabled&&(e?this.linkPreviewsManager.findAndEnrichUrls(e):this.linkPreviewsManager.clearPreviews()))}),this.subscribeAttachmentManagerStateChanged=()=>this.attachmentManager.state.subscribe((e,t)=>{if(void 0!==t&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty))return void this.deleteDraft()}),this.subscribeLocationComposerStateChanged=()=>this.locationComposer.state.subscribe((e,t)=>{if(void 0!==t&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty))return void this.deleteDraft()}),this.subscribeLinkPreviewsManagerStateChanged=()=>this.linkPreviewsManager.state.subscribe((e,t)=>{if(void 0!==t&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty))return void this.deleteDraft()}),this.subscribePollComposerStateChanged=()=>this.pollComposer.state.subscribe((e,t)=>{if(void 0!==t&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty))return void this.deleteDraft()}),this.subscribeCustomDataManagerStateChanged=()=>this.customDataManager.state.subscribe((e,t)=>{void 0===t||this.customDataManager.isMessageDataEqual(e,t)||this.logStateUpdateTimestamp()}),this.subscribeMessageComposerStateChanged=()=>this.state.subscribe((e,t)=>{void 0!==t&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty&&this.deleteDraft())}),this.subscribeMessageComposerConfigStateChanged=()=>{let e,t=this.configState.subscribeWithSelector(e=>({textDefaultValue:e.text.defaultValue,draftsEnabled:e.drafts.enabled}),({textDefaultValue:t,draftsEnabled:s})=>{""===this.textComposer.text&&t&&this.textComposer.insertText({text:t,selection:{start:0,end:0}}),s&&!e?e=this.registerDraftEventSubscriptions():!s&&e&&(e(),e=null)});return()=>{e?.(),t()}},this.setQuotedMessage=e=>{this.state.partialNext({quotedMessage:e})},this.toggleShowReplyInChannel=()=>{this.state.partialNext({showReplyInChannel:!this.showReplyInChannel})},this.clear=()=>{this.setQuotedMessage(null),this.initState()},this.restore=()=>{let{editedMessage:e}=this;e?this.initState({composition:e}):this.clear()},this.compose=async()=>{let e=this.editedMessage?.created_at??new Date,t=await this.compositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{message:{id:this.id,parent_id:this.threadId??void 0,type:"regular"},localMessage:{attachments:[],created_at:e,deleted_at:null,error:void 0,id:this.id,mentioned_users:[],parent_id:this.threadId??void 0,pinned_at:this.editedMessage?.pinned_at||null,reaction_groups:null,status:this.editedMessage?this.editedMessage.status:"sending",text:"",type:"regular",updated_at:e},sendOptions:{}}});if("discard"!==t.status)return t.state},this.composeDraft=async()=>{let{state:e,status:t}=await this.draftCompositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{draft:{id:this.id,parent_id:this.threadId??void 0,text:""}}});if("discard"!==t)return e},this.createDraft=async()=>{if(this.editedMessage||!this.config.drafts.enabled)return;let e=await this.composeDraft();if(!e)return;let{draft:t}=e;if(this.state.partialNext({draftId:t.id}),this.client.offlineDb)try{var s;let e,i={channel_cid:this.channel.cid,created_at:new Date().toISOString(),message:t,parent_id:t.parent_id,quoted_message:this.quotedMessage?(s=this.quotedMessage,{...(e=e=>{if(!e)return null;let t=new Date().toISOString();return{...e,created_at:s.created_at?s.created_at.toISOString():t,deleted_at:s.deleted_at?s.deleted_at.toISOString():void 0,pinned_at:s.pinned_at?s.pinned_at.toISOString():void 0,updated_at:s.updated_at?s.updated_at.toISOString():t}})(s),quoted_message:e(s.quoted_message)}):void 0};await this.client.offlineDb.upsertDraft({draft:i})}catch(e){this.client.logger("error","offlineDb:upsertDraft",{tags:["channel","offlineDb"],error:e})}this.logDraftUpdateTimestamp(),await this.channel.createDraft(t)},this.deleteDraft=async()=>
1{if(this.editedMessage||!this.config.drafts.enabled||!this.draftId)return;this.state.partialNext({draftId:null});let e=this.threadId??void 0;if(this.client.offlineDb)try{await this.client.offlineDb.deleteDraft({cid:this.channel.cid,parent_id:e})}catch(e){this.client.logger("error","offlineDb:deleteDraft",{tags:["channel","offlineDb"],error:e})}this.logDraftUpdateTimestamp(),await this.channel.deleteDraft({parent_id:e})},this.getDraft=async()=>{if(this.editedMessage||!this.config.drafts.enabled||!this.client.userID)return;let e=await this.client.offlineDb?.getDraft({cid:this.channel.cid,userId:this.client.userID,parent_id:this.threadId??void 0});e&&this.initState({composition:e});try{let{draft:e}=await this.channel.getDraft({parent_id:this.threadId??void 0});if(!e)return;this.client.offlineDb?.executeQuerySafely(t=>t.upsertDraft({draft:e}),{method:"upsertDraft"}),this.initState({composition:e})}catch(e){this.client.logger("error","messageComposer:getDraft",{tags:["channel","messageComposer"],error:e})}},this.createPoll=async()=>{let e=await this.pollComposer.compose();if(e&&e.data.id)try{let t=await this.client.polls.createPoll(e.data);this.state.partialNext({pollId:t?.id})}catch(e){throw this.client.notifications.addError({message:"Failed to create the poll",origin:{emitter:"MessageComposer",context:{composer:this}},options:{type:"api:poll:create:failed",metadata:{reason:e.message},originalError:e instanceof Error?e:void 0}}),e}},this.sendLocation=async()=>{let e=this.locationComposer.validLocation;if(!this.threadId&&e)try{await this.channel.sendSharedLocation(e),this.refreshId(),this.locationComposer.initState()}catch(e){throw this.client.notifications.addError({message:"Failed to share the location",origin:{emitter:"MessageComposer",context:{composer:this}},options:{type:"api:location:create:failed",metadata:{reason:e.message},originalError:e instanceof Error?e:void 0}}),e}},this.compositionContext=i,i instanceof n1)this.channel=i;else if(i instanceof nq)this.channel=i.channel;else if(i.cid){const[e,t]=i.cid.split(":");this.channel=a.channel(e,t)}else throw Error("MessageComposer requires composition context pointing to channel (channel or context.cid)");this.configState=new ag(aV(aV(aQ,s??{}),{location:{enabled:this.channel.getConfig()?.shared_locations}},(e,t,s)=>"object"==typeof e?void 0:(!1!==e||"enabled"!==s)&&(["string","number","bigint","boolean","symbol"].includes(typeof t)?t:e))),nV(t)?n=t.message:t&&(n=iY(t)),this.attachmentManager=new az({composer:this,message:n}),this.linkPreviewsManager=new aX({composer:this,message:n}),this.locationComposer=new a0({composer:this,message:n}),this.textComposer=new nT({composer:this,message:n}),this.pollComposer=new nt({composer:this}),this.customDataManager=new aJ({composer:this,message:n}),this.editingAuditState=new ag(this.initEditingAuditState(t)),this.state=new ag(nW(t)),this.compositionMiddlewareExecutor=new na({composer:this}),this.draftCompositionMiddlewareExecutor=new nn({composer:this})}static evaluateContextType(e){return e instanceof n1?"channel":e instanceof nq?"thread":"string"==typeof e.legacyThreadId?"legacy_thread":"message"}static constructTag(e){return`${this.evaluateContextType(e)}_${e.id}`}get config(){return this.configState.getLatestValue()}get editedMessage(){return this.state.getLatestValue().editedMessage??void 0}set editedMessage(e){this.state.partialNext({editedMessage:e??null})}get contextType(){return e.evaluateContextType(this.compositionContext)}get tag(){return e.constructTag(this.compositionContext)}get threadId(){return this.compositionContext instanceof n1?null:this.compositionContext instanceof nq?this.compositionContext.id:"string"==typeof this.compositionContext.legacyThreadId?this.compositionContext.legacyThreadId:"string"==typeof this.compositionContext.parent_id?this.compositionContext.parent_id:null}get client(){return this.channel.getClient()}get id(){return this.state.getLatestValue().id}get draftId(){return this.state.getLatestValue().draftId}get lastChange(){return this.editingAuditState.getLatestValue().lastChange}get quotedMessage(){return this.state.getLatestValue().quotedMessage}get pollId(){return this.state.getLatestValue().pollId}
1get showReplyInChannel(){return this.state.getLatestValue().showReplyInChannel}get hasSendableData(){return this.client.offlineDb?!this.textComposer.textIsEmpty||!!this.attachmentManager.attachments.length||!!this.pollId||!!this.locationComposer.validLocation:!!(!this.attachmentManager.uploadsInProgressCount&&(!this.textComposer.textIsEmpty||this.attachmentManager.successfulUploadsCount>0)||this.pollId||this.locationComposer.validLocation)}get compositionIsEmpty(){return!this.quotedMessage&&this.contentIsEmpty}get contentIsEmpty(){return this.textComposer.textIsEmpty&&!this.attachmentManager.attachments.length&&!this.pollId&&!this.locationComposer.validLocation}get lastChangeOriginIsLocal(){let e=null===this.lastChange.draftUpdate&&!this.editedMessage,t=!!this.editedMessage?.updated_at&&new Date(this.editedMessage.updated_at).getTime()<this.lastChange.stateUpdate,s=!!this.lastChange.draftUpdate&&this.lastChange.draftUpdate<this.lastChange.stateUpdate;return t||s||e}updateConfig(e){this.configState.partialNext(aV(this.config,e))}logStateUpdateTimestamp(){this.editingAuditState.partialNext({lastChange:{...this.lastChange,stateUpdate:new Date().getTime()}})}logDraftUpdateTimestamp(){if(!this.config.drafts.enabled)return;let e=new Date().getTime();this.editingAuditState.partialNext({lastChange:{draftUpdate:e,stateUpdate:e}})}};nH.generateId=iz;var nz=nH,nQ=class e{constructor({client:e}){this.deliveryReportCandidates=new Map,this.nextDeliveryReportCandidates=new Map,this.markDeliveredRequestPromise=null,this.markDeliveredTimeout=null,this.requestTimeoutMs=1e3,this.requestRetryCount=0,this.getNextDeliveryReportCandidate=e=>{let t,s,i,a=this.client.user?.id;if(!a)return;let n=[];if(e instanceof n1){n=e.state.latestMessages;let r=e.state.read[a]??{};s=r?.last_read,t=r?.last_delivered_at,i=e.cid}else{if(!(e instanceof nq))return;n=e.state.getLatestValue().replies;let r=e.state.getLatestValue().read[a]??{};s=r?.lastReadAt,t=r?.lastDeliveredAt,i=`${e.channel.cid}:${e.id}`;return}if(!i)return;let[r]=n.slice(-1);return!r||s>=r.created_at||!r||(t??0)>=r.created_at?{key:i,id:null}:{key:i,id:r.id||null}},this.announceDelivery=e=>{if(!this.canExecuteRequest)return;let{latest_delivered_messages:t,sendBuffer:s}=this.confirmationsFromDeliveryReportCandidates();if(!t.length)return;let i={...e,latest_delivered_messages:t},a=({preventSchedulingRetry:t}={})=>{for(let[e,t]of(this.markDeliveredRequestPromise=null,this.nextDeliveryReportCandidates.entries()))this.deliveryReportCandidates.set(e,t);this.nextDeliveryReportCandidates=new Map,t||this.announceDeliveryBuffered(e)},n=()=>{this.resetBackOff(),a()},r=e=>{let t=new Map(s);for(let[e,s]of this.deliveryReportCandidates.entries())t.set(e,s);this.deliveryReportCandidates=t,no(e)&&nl(e)||e.status>=500?(this.increaseBackOff(),a()):a({preventSchedulingRetry:!0})};this.markDeliveredRequestPromise=this.client.markChannelsDelivered(i).then(n,r)},this.announceDeliveryBuffered=e=>{!this.hasTimer&&this.canExecuteRequest&&(this.markDeliveredTimeout=setTimeout(()=>{this.markDeliveredTimeout=null,this.announceDelivery(e)},this.requestTimeoutMs))},this.markRead=async(e,t)=>{let s=null;return e instanceof n1?s=await e.markAsReadRequest(t):e instanceof nq&&(s=await e.channel.markAsReadRequest({...t,thread_id:e.id})),this.removeCandidateFor(e),s},this.throttledMarkRead=i4(this.markRead,1e3,{leading:!1,trailing:!0}),this.client=e}get markDeliveredRequestInFlight(){return null!==this.markDeliveredRequestPromise}get hasTimer(){return null!==this.markDeliveredTimeout}get hasDeliveryCandidates(){return this.deliveryReportCandidates.size>0}get canExecuteRequest(){return!this.markDeliveredRequestInFlight&&this.hasDeliveryCandidates}static hasPermissionToReportDeliveryFor(e){return e instanceof n1?!!e.getConfig()?.delivery_events:e instanceof nq?!!e.channel.getConfig()?.delivery_events:void 0}increaseBackOff(){this.requestRetryCount>=3||(this.requestRetryCount=this.requestRetryCount+1,this.requestTimeoutMs=2*this.requestTimeoutMs)}resetBackOff(){this.requestTimeoutMs=1e3,this.requestRetryCount=0}confirmationsFrom(e){return Array.from(e.entries()).map(([e,t])=>{let[s,i,a]=e.split(":");return a?{cid:`${s}:${i}`,id:t,parent_id:a}:{cid:e,id:t}})}confirmationsFromDeliveryReportCandidates(){let e=Array.from(this.deliveryReportCandidates),t=new Map(e.slice(0,100));return this.deliveryReportCandidates=new Map(e.slice(100)),{latest_delivered_messages:this.confirmationsFrom(t),sendBuffer:t}}candidateKeyFor(e){return e instanceof n1?e.cid:e instanceof nq?`${e.channel.cid}:${e.id}`:void 0}trackDeliveredCandidate(t){if(!e.hasPermissionToReportDeliveryFor(t))return;let s=this.getNextDeliveryReportCandidate(t);
1if(!s?.key)return;let i=this.markDeliveredRequestInFlight?this.nextDeliveryReportCandidates:this.deliveryReportCandidates;null===s.id?i.delete(s.key):i.set(s.key,s.id)}removeCandidateFor(e){let t=this.candidateKeyFor(e);t&&(this.deliveryReportCandidates.delete(t),this.nextDeliveryReportCandidates.delete(t))}syncDeliveredCandidates(e){if(this.client.user?.privacy_settings?.delivery_receipts?.enabled!==!1){for(let t of e)this.trackDeliveredCandidate(t);this.announceDeliveryBuffered()}}},nK={timestampMs:-1/0,msgId:""},nJ=(e,t)=>e.timestampMs!==t.timestampMs?e.timestampMs-t.timestampMs:0,nG=(e,t,s)=>{let i=0,a=e.length;for(;i<a;){let n=i+a>>>1;nJ(s(e[n]),t)>=0?a=n:i=n+1}return i},nY=(e,t,s)=>{let i=0,a=e.length;for(;i<a;){let n=i+a>>>1;nJ(s(e[n]),t)>0?a=n:i=n+1}return i},nX=(e,t,s)=>e.splice(nY(e,s(t),s),0,t),nZ=(e,t,s,i)=>{let a=nG(e,s,i);for(;a<e.length&&0===nJ(i(e[a]),s);){if(e[a].user.id===t.user.id)return void e.splice(a,1);a++}},n0=class{constructor({locateMessage:e}){this.byUser=new Map,this.readSorted=[],this.deliveredSorted=[],this.locateMessage=e}ingestInitial(e){for(let t of(this.byUser.clear(),this.readSorted=[],this.deliveredSorted=[],e)){let e=t.last_read?new Date(t.last_read).getTime():null,s=t.last_delivered_at?new Date(t.last_delivered_at).getTime():null,i=e?this.locateMessage(e)??nK:nK,a=s?this.locateMessage(s)??nK:nK;0>nJ(a,i)&&(a=i);let n={user:t.user,lastReadRef:i,lastDeliveredRef:a};this.byUser.set(t.user.id,n),this.readSorted.splice(nG(this.readSorted,i,e=>e.lastReadRef),0,n),this.deliveredSorted.splice(nG(this.deliveredSorted,a,e=>e.lastDeliveredRef),0,n)}}onMessageDelivered({user:e,deliveredAt:t,lastDeliveredMessageId:s}){let i=new Date(t).getTime(),a=s?{timestampMs:i,msgId:s}:this.locateMessage(new Date(t).getTime());if(!a)return;let n=this.ensureUser(e),r=0>nJ(a,n.lastReadRef)?n.lastReadRef:a;0>=nJ(r,n.lastDeliveredRef)||(nZ(this.deliveredSorted,n,n.lastDeliveredRef,e=>e.lastDeliveredRef),n.lastDeliveredRef=r,nX(this.deliveredSorted,n,e=>e.lastDeliveredRef))}onMessageRead({user:e,readAt:t,lastReadMessageId:s}){let i=new Date(t).getTime(),a=s?{timestampMs:i,msgId:s}:this.locateMessage(i);if(!a)return;let n=this.ensureUser(e);!(0>=nJ(a,n.lastReadRef))&&(nZ(this.readSorted,n,n.lastReadRef,e=>e.lastReadRef),n.lastReadRef=a,nX(this.readSorted,n,e=>e.lastReadRef),0>nJ(n.lastDeliveredRef,n.lastReadRef)&&(nZ(this.deliveredSorted,n,n.lastDeliveredRef,e=>e.lastDeliveredRef),n.lastDeliveredRef=n.lastReadRef,nX(this.deliveredSorted,n,e=>e.lastDeliveredRef)))}onNotificationMarkUnread({user:e,lastReadAt:t,lastReadMessageId:s}){let i=this.ensureUser(e),a=t?{timestampMs:new Date(t).getTime(),msgId:s??""}:{...nK};(0!==nJ(a,i.lastReadRef)||a.msgId!==i.lastReadRef.msgId)&&(nZ(this.readSorted,i,i.lastReadRef,e=>e.lastReadRef),i.lastReadRef=a,nX(this.readSorted,i,e=>e.lastReadRef),0>nJ(i.lastDeliveredRef,i.lastReadRef)&&(nZ(this.deliveredSorted,i,i.lastDeliveredRef,e=>e.lastDeliveredRef),i.lastDeliveredRef=i.lastReadRef,nX(this.deliveredSorted,i,e=>e.lastDeliveredRef)))}readersForMessage(e){let t=nG(this.readSorted,e,({lastReadRef:e})=>e);return this.readSorted.slice(t).map(e=>e.user)}deliveredForMessage(e){let t=nG(this.deliveredSorted,e,({lastDeliveredRef:e})=>e);return this.deliveredSorted.slice(t).map(e=>e.user)}deliveredNotReadForMessage(e){let t=nG(this.deliveredSorted,e,({lastDeliveredRef:e})=>e),s=[];for(let i=t;i<this.deliveredSorted.length;i++){let t=this.deliveredSorted[i];0>nJ(t.lastReadRef,e)&&s.push(t.user)}return s}usersWhoseLastReadIs(e){if(!e.msgId)return[];let t=nG(this.readSorted,e,e=>e.lastReadRef),s=nY(this.readSorted,e,e=>e.lastReadRef),i=[];for(let a=t;a<s;a++){let t=this.readSorted[a];t.lastReadRef.msgId===e.msgId&&i.push(t.user)}return i}usersWhoseLastDeliveredIs(e){if(!e.msgId)return[];let t=nG(this.deliveredSorted,e,e=>e.lastDeliveredRef),s=nY(this.deliveredSorted,e,e=>e.lastDeliveredRef),i=[];for(let a=t;a<s;a++){let t=this.deliveredSorted[a];t.lastDeliveredRef.msgId===e.msgId&&i.push(t.user)}return i}hasUserRead(e,t){let s=this.byUser.get(t);return!!s&&nJ(s.lastReadRef,e)>=0}hasUserDelivered(e,t){let s=this.byUser.get(t);return!!s&&nJ(s.lastDeliveredRef,e)>=0}getUserProgress(e){let t=this.byUser.get(e);return t||null}groupUsersByLastReadMessage(){return Array.from(this.byUser.values()).reduce((e,t)=>
1{let s=t.lastReadRef.msgId;return s&&(e[s]||(e[s]=[]),e[s].push(t.user)),e},{})}groupUsersByLastDeliveredMessage(){return Array.from(this.byUser.values()).reduce((e,t)=>{let s=t.lastDeliveredRef.msgId;return s&&(e[s]||(e[s]=[]),e[s].push(t.user)),e},{})}ensureUser(e){let t=this.byUser.get(e.id);return t||(t={user:e,lastReadRef:nK,lastDeliveredRef:nK},this.byUser.set(e.id,t),nX(this.readSorted,t,e=>e.lastReadRef),nX(this.deliveredSorted,t,e=>e.lastDeliveredRef)),t}},n1=class{constructor(e,t,s,i){if(this.create=async e=>{let t={...e,watch:!1,state:!1,presence:!1};return await this.query(t,"latest")},this._callChannelListeners=e=>{let t=[];for(let s of(this.listeners.all&&t.push(...this.listeners.all),this.listeners[e.type]&&t.push(...this.listeners[e.type]),t))"string"!=typeof s&&s(e)},this._channelURL=()=>{if(!this.id)throw Error("channel id is not defined");return`${this.getClient().baseURL}/channels/${encodeURIComponent(this.type)}/${encodeURIComponent(this.id)}`},!/^[\w_-]+$/.test(t))throw Error(`Invalid chat type ${t}, letters, numbers and "_-" are allowed`);if("string"==typeof s&&!/^[\w!_-]+$/.test(s))throw Error(`Invalid chat id ${s}, letters, numbers and "!-_" are allowed`);this._client=e,this.type=t,this.id=s,this.data=i,this._data={...i},this.cid=`${t}:${s}`,this.listeners={},this.state=new ah(this),this.initialized=!1,this.offlineMode=!1,this.lastTypingEvent=null,this.isTyping=!1,this.disconnected=!1,this.messageComposer=new nz({client:this._client,compositionContext:this}),this.messageReceiptsTracker=new n0({locateMessage:e=>{let t=this.state.findMessageByTimestamp(e);return t&&{timestampMs:e,msgId:t.id}}}),this.cooldownTimer=new ab({channel:this})}getClient(){if(!0===this.disconnected)throw Error("You can't use a channel after client.disconnect() was called");return this._client}getConfig(){return this.getClient().configs[this.cid]}async _sendMessage(e,t){return await this.getClient().post(this._channelURL()+"/message",{message:e,...t})}async sendMessage(e,t){try{let s=this.getClient().offlineDb;if(s){let i=e.id;if(i)return await s.queueTask({task:{channelId:this.id,channelType:this.type,messageId:i,payload:[e,t],type:"send-message"}})}}catch(e){this._client.logger("error","offlineDb:send-message",{tags:["channel","offlineDb"],error:e})}return await this._sendMessage(e,t)}sendFile(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/file`,e,t,s,i)}sendImage(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/image`,e,t,s,i)}deleteFile(e){return this.getClient().delete(`${this._channelURL()}/file`,{url:e})}deleteImage(e){return this.getClient().delete(`${this._channelURL()}/image`,{url:e})}async sendEvent(e){return this._checkInitialized(),await this.getClient().post(this._channelURL()+"/event",{event:e})}async search(e,t={}){if(t.offset&&t.next)throw Error("Cannot specify offset with next");let s={filter_conditions:{cid:this.cid},...t,sort:t.sort?iV(t.sort):void 0};if("string"==typeof e)s.query=e;else if("object"==typeof e)s.message_filter_conditions=e;else throw Error(`Invalid type ${typeof e} for query parameter`);return await this.getClient().wsPromise,await this.getClient().get(this.getClient().baseURL+"/search",{payload:s})}async queryMembers(e,t=[],s={}){let i,a,n=this.type;return this.id?i=this.id:this.data?.members&&Array.isArray(this.data.members)&&(a=this.data.members),await this.getClient().get(this.getClient().baseURL+"/members",{payload:{type:n,id:i,members:a,sort:iV(t),filter_conditions:e,...s}})}async updateMemberPartial(e,t){let s=new URL(`${this._channelURL()}/member`);return t?.userId&&s.searchParams.append("user_id",t.userId),await this.getClient().patch(s.toString(),e)}async partialUpdateMember(e,t){if(!e)throw Error("Please specify the user id");return await this.getClient().patch(this._channelURL()+`/member/${encodeURIComponent(e)}`,t)}async sendReaction(e,t,s){if(!e)throw Error("Message id is missing");if(!t||0===Object.keys(t).length)throw Error("Reaction object is missing");try{let i=this.getClient().offlineDb;if(i)return await i.queueTask({task:{channelId:this.id,channelType:this.t
1ype,messageId:e,payload:[e,t,s],type:"send-reaction"}})}catch(e){this._client.logger("error","offlineDb:send-reaction",{tags:["channel","offlineDb"],error:e})}return this._sendReaction(e,t,s)}async _sendReaction(e,t,s){if(!e)throw Error("Message id is missing");if(!t||0===Object.keys(t).length)throw Error("Reaction object is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reaction`,{reaction:t,...s})}async deleteReaction(e,t,s){if(this._checkInitialized(),!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");try{let i=this.getClient().offlineDb;if(i){let a=this.state.messages.find(({id:t})=>t===e),n={created_at:"",updated_at:"",message_id:e,type:t,user_id:this.getClient().userID??s};return a&&await i.deleteReaction({message:a,reaction:n}),await i.queueTask({task:{channelId:this.id,channelType:this.type,messageId:e,payload:[e,t],type:"delete-reaction"}})}}catch(e){this._client.logger("error","offlineDb:delete-reaction",{tags:["channel","offlineDb"],error:e})}return await this._deleteReaction(e,t,s)}async _deleteReaction(e,t,s){if(this._checkInitialized(),!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");let i=this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reaction/${encodeURIComponent(t)}`;return s?await this.getClient().delete(i,{user_id:s}):await this.getClient().delete(i,{})}async update(e={},t,s){return["config","cid","created_by","id","member_count","type","created_at","updated_at","last_message_at","own_capabilities"].forEach(t=>{delete e[t]}),await this._update({message:t,data:e,...s})}async updatePartial(e){let t=await this.getClient().patch(this._channelURL(),e),s=[...t.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=t.channel,s&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:t.channel.own_capabilities}),t}async enableSlowMode(e){let t=await this.getClient().post(this._channelURL(),{cooldown:e});return this.data=t.channel,t}async disableSlowMode(){let e=await this.getClient().post(this._channelURL(),{cooldown:0});return this.data=e.channel,e}async sendSharedLocation(e,t){let s=await this.sendMessage({id:e.message_id,shared_location:e,user:t?{id:t}:void 0});return e.end_at&&this.getClient().dispatchEvent({message:s.message,type:"live_location_sharing.started"}),s}async stopLiveLocationSharing(e){let t=await this.getClient().updateLocation({...e,end_at:new Date().toISOString()});this.getClient().dispatchEvent({live_location:t,type:"live_location_sharing.stopped"})}async delete(e={}){return await this.getClient().delete(this._channelURL(),{...e})}async truncate(e={}){return await this.getClient().post(this._channelURL()+"/truncate",e)}async acceptInvite(e={}){return await this._update({accept_invite:!0,...e})}async rejectInvite(e={}){return await this._update({reject_invite:!0,...e})}async addMembers(e,t,s={}){return await this._update({add_members:e,message:t,...s})}async addFilterTags(e,t,s={}){return await this._update({add_filter_tags:e,message:t,...s})}async removeFilterTags(e,t,s={}){return await this._update({remove_filter_tags:e,message:t,...s})}async addModerators(e,t,s={}){return await this._update({add_moderators:e,message:t,...s})}async assignRoles(e,t,s={}){return await this._update({assign_roles:e,message:t,...s})}async inviteMembers(e,t,s={}){return await this._update({invites:e,message:t,...s})}async removeMembers(e,t,s={}){return await this._update({remove_members:e,message:t,...s})}async demoteModerators(e,t,s={}){return await this._update({demote_moderators:e,message:t,...s})}async _update(e){let t=await this.getClient().post(this._channelURL(),e);return this.data=t.channel,t}async mute(e={}){return await this.getClient().post(this.getClient().baseURL+"/moderation/mute/channel",{channel_cid:this.cid,...e})}async unmute(e={}){return await this.getClient().post(this.getClient().baseURL+"/moderation/unmute/channel",{channel_cid:this.cid,...e})}async archive(e={}){let t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for archiving a channel");return(await this.partialUpdateMember(s,{set:{archived:!0}})).channel_member}async unarchive(e={}){let t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for unarchiving a channel");return(await this.partialUpdateMember(s,{set:{archived:!1}})).channel_member}async pin(e={}){let t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for pinning a channel");return(await this.partialUpdateMember(s,{set:{pinned:!0}})).channel_member}async unpin(e={}){let t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for unpinning a channel");return(await this.partialUpdateMember(s,{set:{pinned:!1}
1})).channel_member}muteStatus(){return this._checkInitialized(),this.getClient()._muteStatus(this.cid)}sendAction(e,t){if(this._checkInitialized(),!e)throw Error("Message id is missing");return this.getClient().post(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/action`,{message_id:e,form_data:t,id:this.id,type:this.type})}async keystroke(e,t){if(!this._isTypingIndicatorsEnabled())return;let s=new Date,i=this.lastTypingEvent&&s.getTime()-this.lastTypingEvent.getTime();this.lastKeyStroke=s,this.isTyping=!0,(null===i||i>2e3)&&(this.lastTypingEvent=new Date,await this.sendEvent({type:"typing.start",parent_id:e,...t||{}}))}async updateAIState(e,t,s={}){await this.sendEvent({...s,type:"ai_indicator.update",message_id:e,ai_state:t})}async clearAIIndicator(){await this.sendEvent({type:"ai_indicator.clear"})}async stopAIResponse(){await this.sendEvent({type:"ai_indicator.stop"})}async stopTyping(e,t){this._isTypingIndicatorsEnabled()&&(this.lastTypingEvent=null,this.isTyping=!1,await this.sendEvent({type:"typing.stop",parent_id:e,...t||{}}))}_isTypingIndicatorsEnabled(){return!!this.getConfig()?.typing_events&&!!this.getClient().wsConnection?.isHealthy&&(this.getClient().user?.privacy_settings?.typing_indicators?.enabled??!0)}lastMessage(){let e=this.state.latestMessages.length-5;e<0&&(e=0);let t=this.state.latestMessages.length+1,s=this.state.latestMessages.slice(e,t);return s.sort((e,t)=>t.created_at.getTime()-e.created_at.getTime()),s[0]}async markRead(e={}){return await this.getClient().messageDeliveryReporter.markRead(this,e)}async markAsReadRequest(e={}){return(this._checkInitialized(),this.getConfig()?.read_events||this.getClient()._isUsingServerAuth())?await this.getClient().post(this._channelURL()+"/read",{...e}):null}async markUnread(e){return(this._checkInitialized(),this.getConfig()?.read_events||this.getClient()._isUsingServerAuth())?await this.getClient().post(this._channelURL()+"/unread",{...e}):Promise.resolve(null)}clean(){this.lastKeyStroke&&new Date().getTime()-this.lastKeyStroke.getTime()>1e3&&this.isTyping&&ij(this.stopTyping(),"stop typing event"),this.state.clean()}async watch(e){let t={state:!0,watch:!0,presence:!1};await this.getClient().wsPromise,this.getClient()._hasConnectionID()||(t.watch=!1);let s={...t,...e},i=await this.query(s,"latest");return this.initialized=!0,this.data=i.channel,this._client.logger("info",`channel:watch() - started watching channel ${this.cid}`,{tags:["channel"],channel:this}),i}async stopWatching(){let e=await this.getClient().post(this._channelURL()+"/stop-watching",{});return this._client.logger("info",`channel:watch() - stopped watching channel ${this.cid}`,{tags:["channel"],channel:this}),e}async getReplies(e,t,s){let i=s?iV(s):void 0,a=await this.getClient().get(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/replies`,{sort:i,...t});return a.messages&&this.state.addMessagesSorted(a.messages),a}async getPinnedMessages(e,t=[]){return await this.getClient().get(this._channelURL()+"/pinned_messages",{payload:{...e,sort:iV(t)}})}getReactions(e,t){return this.getClient().get(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reactions`,{...t})}getMessagesById(e){return this.getClient().get(this._channelURL()+"/messages",{ids:e.join(",")})}lastRead(){let{userID:e}=this.getClient();if(e)return this.state.read[e]?this.state.read[e].last_read:null}_countMessageAsUnread(e){return!(e.shadowed||e.silent||e.parent_id&&!e.show_in_channel||e.user?.id===this.getClient().userID||e.user?.id&&this.getClient().userMuteStatus(e.user.id)||Array.isArray(this.data?.own_capabilities)&&!this.data?.own_capabilities.includes("read-events"))&&!this.muteStatus().muted}countUnread(e){if(!e)return this.state.unreadCount;let t=0;for(let s=0;s<this.state.latestMessages.length;s+=1){let i=this.state.latestMessages[s];i.created_at>e&&this._countMessageAsUnread(i)&&t++}return t}countUnreadMentions(){let e=this.lastRead(),t=this.getClient().userID,s=0;for(let i=0;i<this.state.latestMessages.length;i+=1){let a=this.state.latestMessages[i];this._countMessageAsUnread(a)&&(!e||a.created_at>e)&&a.mentioned_users?.some(e=>e.id===t)&&s++}return s}async query(e={},t="current"){await this.getClient().wsPromise;let s=e.created_by?.id??e.created_by_id??this._data?.created_by?.id??this._data?.created_by_id;this.getClient()._isUsingServerAuth()&&"string"!=typeof s&&this.getClient().logger("warn","Either `created_by` (with `id` property) or `created_by_id` are missing from both `Channel._data` and `options` parameter");let i=`${this.getClient().baseURL}
1/channels/${encodeURIComponent(this.type)}`;this.id&&(i+=`/${encodeURIComponent(this.id)}`);let a=await this.getClient().post(i+"/query",{data:this._data,state:!0,...e});if(!this.id){this.id=a.channel.id,this.cid=a.channel.cid;let e=i7(this.type,a.members.map(e=>e.user_id||e.user?.id||""));e&&e in this.getClient().activeChannels&&delete this.getClient().activeChannels[e],!(this.cid in this.getClient().activeChannels)&&this.getClient()._cacheEnabled()&&(this.getClient().activeChannels[this.cid]=this)}this.getClient()._addChannelConfig(a.channel),void 0!==a.channel.config?.shared_locations&&this.messageComposer.updateConfig({location:{enabled:a.channel.config.shared_locations}});let{messageSet:n}=this._initializeState(a,t);n.pagination={...n.pagination,...i5({parentSet:n,messagePaginationOptions:e?.messages,requestedPageSize:e?.messages?.limit??100,returnedPage:a.messages,logger:this.getClient().logger})},this.getClient().polls.hydratePollCache(a.messages,!0),this.getClient().reminders.hydrateState(a.messages),this.messageComposer.initStateFromChannelResponse(a);let r=[...a.channel.own_capabilities||[]].sort().join()!==[...this.data&&Array.isArray(this.data?.own_capabilities)?this.data.own_capabilities:[]].sort().join();return this.data=a.channel,this.offlineMode=!1,this.cooldownTimer.refresh(),r&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:a.channel.own_capabilities}),this.getClient().dispatchEvent({type:"channels.queried",queriedChannels:{channels:[a],isLatestMessageSet:n.isLatest}}),this.getClient().offlineDb?.executeQuerySafely(e=>e.upsertChannels?.({channels:[a],isLatestMessagesSet:n.isLatest}),{method:"upsertChannels"}),this.getClient().syncDeliveredCandidates([this]),a}async banUser(e,t){return this._checkInitialized(),await this.getClient().banUser(e,{...t,type:this.type,id:this.id})}async hide(e=null,t=!1){return this._checkInitialized(),await this.getClient().post(`${this._channelURL()}/hide`,{user_id:e,clear_history:t})}async show(e=null){return this._checkInitialized(),await this.getClient().post(`${this._channelURL()}/show`,{user_id:e})}async unbanUser(e,t){return this._checkInitialized(),await this.getClient().unbanUser(e,{...t,type:this.type,id:this.id})}async shadowBan(e,t){return this._checkInitialized(),await this.getClient().shadowBan(e,{...t,type:this.type,id:this.id})}async removeShadowBan(e){return this._checkInitialized(),await this.getClient().removeShadowBan(e,{type:this.t
1ype,id:this.id})}async vote(e,t,s){return await this.getClient().castPollVote(e,t,s)}async removeVote(e,t,s){return await this.getClient().removePollVote(e,t,s)}async _createDraft(e){return await this.getClient().post(this._channelURL()+"/draft",{message:e})}async createDraft(e){try{let t=this.getClient().offlineDb;if(t)return await t.queueTask({task:{channelId:this.id,channelType:this.type,threadId:e.parent_id,payload:[e],type:"create-draft"}})}catch(e){this._client.logger("error","offlineDb:create-draft",{tags:["channel","offlineDb"],error:e})}return this._createDraft(e)}async _deleteDraft({parent_id:e}={}){return await this.getClient().delete(this._channelURL()+"/draft",{parent_id:e})}async deleteDraft(e={}){let{parent_id:t}=e;try{let s=this.getClient().offlineDb;if(s)return await s.queueTask({task:{channelId:this.id,channelType:this.type,threadId:t,payload:[e],type:"delete-draft"}})}catch(e){this._client.logger("error","offlineDb:delete-draft",{tags:["channel","offlineDb"],error:e})}return this._deleteDraft(e)}async getDraft({parent_id:e}={}){return await this.getClient().get(this._channelURL()+"/draft",{parent_id:e})}on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Attaching listener for ${s} event on channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s].push(i),{unsubscribe:()=>{this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(e=>e!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(e=>e!==i)}_handleChannelEvent(e){this._client.logger("info",`channel:_handleChannelEvent - Received event of type { ${e.type} } on ${this.cid}`,{tags:["event","channel"],channel:this});let t=this.state;switch(e.type){case"typing.start":e.user?.id&&(t.typing[e.user.id]=e);break;case"typing.stop":e.user?.id&&delete t.typing[e.user.id];break;case"message.read":if(e.user?.id&&e.created_at){let s=t.read[e.user.id];t.read[e.user.id]={...s,last_read:new Date(e.created_at),last_read_message_id:e.last_read_message_id,user:e.user,unread_messages:0},this.messageReceiptsTracker.onMessageRead({user:e.user,readAt:e.created_at,lastReadMessageId:e.last_read_message_id});let i=this.getClient();e.user?.id===i.user?.id&&(t.unreadCount=0,i.syncDeliveredCandidates([this]))}break;case"message.delivered":if(e.user?.id&&e.created_at){let s=t.read[e.user.id];t.read[e.user.id]={...s,last_delivered_at:e.last_delivered_at?new Date(e.last_delivered_at):void 0,last_delivered_message_id:e.last_delivered_message_id,user:e.user},this.messageReceiptsTracker.onMessageDelivered({user:e.user,deliveredAt:e.created_at,lastDeliveredMessageId:e.last_delivered_message_id});let i=this.getClient();e.user?.id===i.user?.id&&i.syncDeliveredCandidates([this])}break;case"user.watching.start":case"user.updated":e.user?.id&&(t.watchers[e.user.id]=e.user);break;case"user.watching.stop":e.user?.id&&delete t.watchers[e.user.id];break;case"message.deleted":e.message&&(this._extendEventWithOwnReactions(e),e.hard_delete?t.removeMessage(e.message):t.addMessageSorted(e.message,!1,!1),t.removeQuotedMessageReferences(e.message),e.message.pinned&&t.removePinnedMessage(e.message));break;case"user.messages.deleted":e.user&&this.state.deleteUserMessages(e.user,!!e.hard_delete,new Date(e.created_at??Date.now()));break;case"message.new":if(e.message){let s=this.getClient(),i=e.user?.id===s.user?.id,a=e.message.parent_id&&!e.message.show_in_channel;(this.state.isUpToDate||a)&&t.addMessageSorted(e.message,i),e.message.pinned&&t.addPinnedMessage(e.message);let n=i||a;if(i&&this.cooldownTimer.refresh(),n)break;if(e.user?.id)for(let s in t.read)s===e.user.id?t.read[e.user.id]={last_read:new Date(e.created_at),user:e.user,unread_messages:0,last_delivered_at:new Date(e.created_at),last_delivered_message_id:e.message.id}:t.read[s].unread_messages+=1;this._countMessageAsUnread(e.message)&&(t.unreadCount=t.unreadCount+1),s.syncDeliveredCandidates([this])}break;case"message.updated":case"message.undeleted":e.message&&(this._extendEventWithOwnReactions(e),t.addMessageSorted(e.message,!1,!1),t._updateQuotedMessageReferences({message:e.message}),e.message.pinned?t.addPinnedMessage(e.message):t.removePinnedMessage(e.message));break;case"channel.truncated":if(e.channel?.truncated_at){let s=+new Date(e.channel.truncated_at);
1t.messageSets.forEach((e,i)=>{e.messages.forEach(({created_at:e,id:a})=>{s>+e&&t.removeMessage({id:a,messageSetIndex:i})})}),t.pinnedMessages.forEach(({id:e,created_at:i})=>{s>+i&&t.removePinnedMessage({id:e})}),t.unreadCount=this.countUnread(new Date(e.channel.truncated_at))}else t.clearMessages(),t.unreadCount=0;e.message&&(t.addMessageSorted(e.message),e.message.pinned&&t.addPinnedMessage(e.message));break;case"member.added":case"member.updated":{let s={...e.member};null===s.pinned_at&&delete s.pinned_at,null===s.archived_at&&delete s.archived_at,s?.user&&(t.members={...t.members,[s.user.id]:s},this.data?.member_count&&"member.added"===e.type&&(this.data.member_count+=1));let i=this.getClient().userID;"string"==typeof i&&"string"==typeof s?.user?.id&&s.user.id===i&&(t.membership=s);break}case"member.removed":if(e.user?.id){let s={...t.members};delete s[e.user.id],t.members=s,this.data?.member_count&&(this.data.member_count=Math.max(this.data.member_count-1,0))}break;case"notification.mark_unread":{if(e.user?.id!==this.getClient().user?.id||!e.user)break;let s=e.unread_messages??0,i=t.read[e.user.id];t.read[e.user.id]={...i,first_unread_message_id:e.first_unread_message_id,last_read:new Date(e.last_read_at),last_read_message_id:e.last_read_message_id,user:e.user,unread_messages:s},t.unreadCount=s,this.messageReceiptsTracker.onNotificationMarkUnread({user:e.user,lastReadAt:e.last_read_at,lastReadMessageId:e.last_read_message_id});break}case"channel.updated":if(e.channel){e.channel?.frozen!==void 0&&e.channel.frozen!==this.data?.frozen&&this.query({state:!1,messages:{limit:0},watchers:{limit:0}});let t={...e.channel,hidden:e.channel?.hidden??this.data?.hidden,own_capabilities:e.channel?.own_capabilities??this.data?.own_capabilities};this.data=t,this.cooldownTimer.refresh()}break;case"reaction.new":if(e.message&&e.reaction){let{message:s,reaction:i}=e;e.message=t.addReaction(i,s)}break;case"reaction.deleted":if(e.message&&e.reaction){let{message:s,reaction:i}=e;e.message=t.removeReaction(i,s)}break;case"reaction.updated":if(e.message&&e.reaction){let{message:s,reaction:i}=e;e.message=t.addReaction(i,s,!0)}break;case"channel.hidden":this.data={...this.data,blocked:!!e.channel?.blocked,hidden:!0},e.clear_history&&t.clearMessages();break;case"channel.visible":this.data={...this.data,blocked:!!e.channel?.blocked,hidden:!1},this.getClient().offlineDb?.handleChannelVisibilityEvent({event:e});break;case"user.banned":if(!e.user?.id)break;t.members[e.user.id]={...t.members[e.user.id]||{},shadow_banned:!!e.shadow,banned:!e.shadow,user:{...t.members[e.user.id]?.user||{},...e.user}};break;case"user.unbanned":if(!e.user?.id)break;t.members[e.user.id]={...t.members[e.user.id]||{},shadow_banned:!1,banned:!1,user:{...t.members[e.user.id]?.user||{},...e.user}}}void 0!==e.watcher_count&&(this.state.watcher_count=e.watcher_count)}_checkInitialized(){if(!this.initialized&&!this.offlineMode&&!this.getClient()._isUsingServerAuth())throw Error(`Channel ${this.cid} hasn't been initialized yet. Make sure to call .watch() and wait for it to resolve`)}_initializeState(e,t="latest"){let{state:s,user:i,userID:a}=this.getClient();if(e.members)for(let t of(this._hydrateMembers({members:e.members}),e.members))t.user&&s.updateUserReference(t.user,this.cid);this.state.membership=e.membership||{};let n=e.messages||[];this.state.messages||this.state.initMessages();let{messageSet:r}=this.state.addMessagesSorted(n,!1,!0,!0,t);if(this.state.pinnedMessages||(this.state.pinnedMessages=[]),this.state.addPinnedMessages(e.pinned_messages||[]),e.pending_messages&&(this.state.pending_messages=e.pending_messages),void 0!==e.watcher_count&&(this.state.watcher_count=e.watcher_count),e.watchers)for(let t of e.watchers)t&&(s.updateUserReference(t,this.cid),this.state.watchers[t.id]=t);if(null!=a){let e=this.state.last_message_at||new Date;i&&(this.state.read[i.id]={user:i,last_read:e,unread_messages:0})}if(e.read){for(let t of e.read)this.state.read[t.user.id]={last_delivered_at:t.last_delivered_at?new Date(t.last_delivered_at):void 0,last_delivered_message_id:t.last_delivered_message_id,last_read:new Date(t.last_read),last_read_message_id:t.last_read_message_id,unread_messages:t.unread_messages??0,user:t.user},t.user.id===i?.id&&(this.state.unreadCount=this.state.read[t.user.id].unread_messages);this.messageReceiptsTracker.ingestInitial(e.read)}return{messageSet:r}}_extendEventWithOwnReactions(e){if(!e.message)return;let t=this.state.findMessage(e.message.id,e.message.parent_id);t&&(e.message.own_reactions=t.own_reactions)}_hydrateMembers({members:e,overrideCurrentState:t=!0}){let s=e.reduce((e,t)=>
1(t.user&&(e[t.user.id]=t),e),{});t?this.state.members=s:!t&&e.length&&(this.state.members={...this.state.members,...s})}_disconnect(){this._client.logger("info",`channel:disconnect() - Disconnecting the channel ${this.cid}`,{tags:["connection","channel"],channel:this}),this.disconnected=!0,this.cooldownTimer.clearTimeout(),this.state.setIsUpToDate(!1)}},n2=class{constructor({client:e}){this.client=e,this.users={},this.userChannelReferences={}}updateUsers(e){for(let t of e)this.updateUser(t)}updateUser(e){null!=e&&this.client._cacheEnabled()&&(this.users[e.id]=e)}updateUserReference(e,t){null!=e&&this.client._cacheEnabled()&&(this.updateUser(e),this.userChannelReferences[e.id]||(this.userChannelReferences[e.id]={}),this.userChannelReferences[e.id][t]=!0)}deleteAllChannelReference(e){for(let t in this.userChannelReferences)delete this.userChannelReferences[t][e]}},n3=class{constructor(){this.connectionStartTimestamp=null,this.wsTotalFailures=0,this.wsConsecutiveFailures=0,this.instanceClientId=iz()}},n4=async(e,t)=>{for(let s=0;s<3;s++){try{await tB.post(`https://chat-insights.getstream.io/insights/${e}`,t)}catch(e){await iB((s+1)*3e3);continue}break}};function n5(e){let{client:t}=e;return{ready_state:e.ws?.readyState,url:e._buildUrl(),api_key:t.key,start_ts:t.insightMetrics.connectionStartTimestamp,end_ts:new Date().getTime(),auth_type:t.getAuthType(),token:t.tokenManager.token,user_id:t.userID,user_details:t._user,device:t.options.device,client_id:e.connectionID,ws_details:e.ws,ws_consecutive_failures:t.insightMetrics.wsConsecutiveFailures,ws_total_failures:t.insightMetrics.wsTotalFailures,request_id:e.requestID,online:"u">typeof navigator?navigator?.onLine:null,user_agent:"u">typeof navigator?navigator?.userAgent:null,instance_client_id:t.insightMetrics.instanceClientId}}var n6=class{constructor({client:e}){this._buildUrl=()=>{let e=this.client._buildWSPayload(this.requestID),t=this.client.tokenManager.getToken(),s=new URLSearchParams(this.client.options.wsUrlParams);return s.set("json",e),s.set("api_key",this.client.key),s.set("authorization",`${t}`),s.set("stream-auth-type",this.client.getAuthType()),s.set("X-Stream-Client",this.client.getUserAgent()),`${this.client.wsBaseURL}/connect?${s.toString()}`},this.onlineStatusChanged=e=>{"offline"===e.type?(this._log("onlineStatusChanged() - Status changing to offline"),this._setHealth(!1)):"online"===e.type&&(this._log(`onlineStatusChanged() - Status changing to online. isHealthy: ${this.isHealthy}`),this.isHealthy||this._reconnect({interval:10}))},this.onopen=e=>{this.wsID===e&&this._log("onopen() - onopen callback",{wsID:e})},this.onmessage=(e,t)=>{if(this.wsID!==e)return;this._log("onmessage() - onmessage callback",{event:t,wsID:e});let s="string"==typeof t.data?JSON.parse(t.data):null;if(!this.isResolved&&s){if(this.isResolved=!0,s.error)return void this.rejectPromise?.(this._errorFromWSEvent(s,!1));this.resolvePromise?.(s),this._setHealth(!0)}this.lastEvent=new Date,s&&"health.check"===s.type&&this.scheduleNextPing(),this.client.handleEvent(t),this.scheduleConnectionCheck()},this.onclose=(e,t)=>{if(this.wsID===e)if(this._log("onclose() - onclose callback - "+t.code,{event:t,wsID:e}),1e3===t.code){let e=Error(`WS connection reject with error ${t.reason}`);e.reason=t.reason,e.code=t.code,e.wasClean=t.wasClean,e.target=t.target,this.rejectPromise?.(e),this._log(`onclose() - WS connection reject with error ${t.reason}`,{event:t})}else this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onclose() - WS connection closed. Calling reconnect ...",{event:t}),this._reconnect()},this.onerror=(e,t)=>{this.wsID===e&&(this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onerror() - WS connection resulted into error",{event:t}),this._reconnect())},this._setHealth=e=>{if(e!==this.isHealthy){if(this.isHealthy=e,this.isHealthy)return void this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy});setTimeout(()=>{this.isHealthy||this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy})},5e3)}},this._errorFromWSEvent=(e,t=!0)=>{let s,i,a;void 0!==e.code&&(s=e.code,i="unknown",a=e.reason),void 0!==e.error&&(s=e.error.code,i=e.error.StatusCode,a=e.error.message),this._log(`_errorFromWSEvent() - WS failed with code ${s}`,{event:e},"warn");let n=Error(`WS failed with code ${s} and reason - ${a}`);return n.code=s,n.StatusCode=i,n.isWSFailure=t,n},this._setupConnectionPromise=()=>{this.isResolved=!1,this.connectionOpen=new Promise((e,t)=>
1{this.resolvePromise=e,this.rejectPromise=t})},this.scheduleNextPing=()=>{this.healthCheckTimeoutRef&&clearTimeout(this.healthCheckTimeoutRef),this.healthCheckTimeoutRef=setTimeout(()=>{let e=[{type:"health.check",client_id:this.client.clientID}];try{this.ws?.send(JSON.stringify(e))}catch(e){}},this.pingInterval)},this.scheduleConnectionCheck=()=>{this.connectionCheckTimeoutRef&&clearTimeout(this.connectionCheckTimeoutRef),this.connectionCheckTimeoutRef=setTimeout(()=>{let e=new Date;this.lastEvent&&e.getTime()-this.lastEvent.getTime()>this.connectionCheckTimeout&&(this._log("scheduleConnectionCheck - going to reconnect"),this._setHealth(!1),this._reconnect())},this.connectionCheckTimeout)},this.client=e,this.consecutiveFailures=0,this.totalFailures=0,this.isConnecting=!1,this.isDisconnected=!1,this.isResolved=!1,this.isHealthy=!1,this.wsID=1,this.lastEvent=null,this.pingInterval=25e3,this.connectionCheckTimeout=this.pingInterval+1e4,iK(this.onlineStatusChanged)}_log(e,t={},s="info"){this.client.logger(s,"connection:"+e,{tags:["connection"],...t})}setClient(e){this.client=e}async connect(e=15e3){if(this.isConnecting)throw Error("You've called connect twice, can only attempt 1 connection at the time");this.isDisconnected=!1;try{let e=await this._connect();this.consecutiveFailures=0,this._log(`connect() - Established ws connection with healthcheck: ${e}`)}catch(e){if(this.isHealthy=!1,this.consecutiveFailures+=1,40!==e.code||this.client.tokenManager.isStatic()){if(!e.isWSFailure)throw Error(JSON.stringify({code:e.code,StatusCode:e.StatusCode,message:e.message,isWSFailure:e.isWSFailure}))}else this._log("connect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0})}return await this._waitForHealthy(e)}_waitForHealthy(e=15e3){return Promise.race([(async()=>{for(let t=0;t<=e;t+=50)try{return await this.connectionOpen}catch(s){if(t===e)throw Error(JSON.stringify({code:s.code,StatusCode:s.StatusCode,message:s.message,isWSFailure:s.isWSFailure}));await iB(50)}})(),(async()=>{throw await iB(e),this.isConnecting=!1,Error(JSON.stringify({code:"",StatusCode:"",message:"initial WS connection could not be established",isWSFailure:!0}))})()])}disconnect(e){let t;this._log(`disconnect() - Closing the websocket connection for wsID ${this.wsID}`),this.wsID+=1,this.isConnecting=!1,this.isDisconnected=!0,this.healthCheckTimeoutRef&&clearInterval(this.healthCheckTimeoutRef),this.connectionCheckTimeoutRef&&clearInterval(this.connectionCheckTimeoutRef),iJ(this.onlineStatusChanged),this.isHealthy=!1,this.ws&&this.ws.removeAllListeners&&this.ws.removeAllListeners();let{ws:s}=this;return s&&s.close&&s.readyState===s.OPEN?(t=new Promise(t=>{let i=e=>{this._log(`disconnect() - resolving isClosedPromise ${e?"with":"without"} close frame`,{event:e}),t()};s.onclose=i,setTimeout(i,null!=e?e:1e3)}),this._log("disconnect() - Manually closed connection by calling client.disconnect()"),s.close(1e3,"Manually closed connection by calling client.disconnect()")):(this._log("disconnect() - ws connection doesn't exist or it is already closed."),t=Promise.resolve()),delete this.ws,t}async _connect(){if(this.isConnecting||this.isDisconnected&&this.client.options.enableWSFallback)return;this.isConnecting=!0,this.requestID=iz(),this.client.insightMetrics.connectionStartTimestamp=new Date().getTime();let e=!1;try{this._log("_connect() - waiting for token"),await this.client.tokenManager.tokenReady(),e=!0}catch(e){}try{e||(this._log("_connect() - tokenProvider failed before, so going to retry"),await this.client.tokenManager.loadToken()),this._setupConnectionPromise();let t=this._buildUrl();this._log(`_connect() - Connecting to ${t}`,{wsURL:t,requestID:this.requestID}),this.ws=new ii(t),this.ws.onopen=this.onopen.bind(this,this.wsID),this.ws.onclose=this.onclose.bind(this,this.wsID),this.ws.onerror=this.onerror.bind(this,this.wsID),this.ws.onmessage=this.onmessage.bind(this,this.wsID);let s=await this.connectionOpen;if(this.isConnecting=!1,s)return this.connectionID=s.connection_id,this.client.insightMetrics.wsConsecutiveFailures>0&&this.client.options.enableInsights&&(n4("ws_success_after_failure",n5(this)),this.client.insightMetrics.wsConsecutiveFailures=0),s}catch(e){if(this.isConnecting=!1,this._log("_connect() - Error - ",e),this.client.options.enableInsights){this.client.insightMetrics.wsConsecutiveFailures++,this.client.insightMetrics.wsTotalFailures++;let t={...function(e){let t={};if(!e)return t;try{Object.getOwnPropertyNames(e).forEach(s=>{t[s]=Object.getOwnPropertyDescriptor(e,s)})}catch(e){return{error:"failed to serialize the error"}}return t}(e),...n5(this)};n4?.("ws_fatal",t)}throw e}}async _reconnect(e={}){if(this._log("_reconnect() - Initiating the reconnect"),this.isConnecting||this.isHealthy)return void this._log("_reconnect() - Abort (1) since already connecting or healthy");let t=e.interval;if(t||(t=iW(this.consecutiveFailures)),await iB(t),this.isConnecting||this.isHealthy)return void this._log("_reconnect() - Abort (2) since already connecting or healthy");if(this.isDisconnected&&this.client.options.enableWSFallback)return void this._log("_reconnect() - Abort (3) since disconnect() is called");this._log("_reconnect() - Destroying current WS connection"),this._destroyCurrentWSConnection(),e.refreshToken&&await this.client.tokenManager.loadToken();try{await this._connect(),this._log("_reconnect() - Waiting for recoverCallBack"),await this.client.re
1coverState(),this._log("_reconnect() - Finished recoverCallBack"),this.consecutiveFailures=0}catch(e){if(this.isHealthy=!1,this.consecutiveFailures+=1,40===e.code&&!this.client.tokenManager.isStatic())return this._log("_reconnect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0});e.isWSFailure&&(this._log("_reconnect() - WS failure, so going to try to reconnect"),this._reconnect())}this._log("_reconnect() - == END ==")}_destroyCurrentWSConnection(){this.wsID+=1;try{this?.ws?.removeAllListeners(),this?.ws?.close()}catch(e){}}},n8=iM(iA()),n7=iM(ik());function n9(e,t,s={},i={}){if("string"!=typeof t)throw TypeError("userId should be a string");let a={user_id:t,...s};if(null==n8.default||null==n8.default.sign)throw Error("Unable to find jwt crypto, if you are getting this error is probably because you are trying to generate tokens on browser or React Native (or other environment where crypto functions are not available). Please Note: token should only be generated server-side.");let n=Object.assign({algorithm:"HS256",noTimestamp:!0},i);return a.iat&&(n.noTimestamp=!1),n8.default.sign(a,e,n)}function re(e,t={}){let s=Object.assign({algorithm:"HS256",noTimestamp:!0},t);return n8.default.sign({server:!0},e,s)}var rt=class{constructor(e){this.setTokenOrProvider=async(e,t)=>{this.validateToken(e,t),this.user=t,i$(e)&&(this.tokenProvider=e,this.type="provider"),"string"==typeof e&&(this.token=e,this.type="static"),!e&&this.user&&this.secret&&(this.token=n9(this.secret,t.id,{},{}),this.type="static"),await this.loadToken()},this.reset=()=>{this.token=void 0,this.tokenProvider=void 0,this.type="static",this.user=void 0,this.loadTokenPromise=null},this.validateToken=(e,t)=>{if(!t||!t.anon||e){if(!this.secret&&!e)throw Error("User token can not be empty");if(e&&"string"!=typeof e&&!i$(e))throw Error("user token should either be a string or a function");if("string"==typeof e){let s;if(t.anon&&""===e)return;let i=3!==(s=e.split(".")).length?"":JSON.parse((e=>{let t={},s=String.fromCharCode,i=e.length,a,n=0,r,o=0,l,d="";for(a=0;a<64;a++)t["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(a)]=a;for(r=0;r<i;r++)for(n=(n<<6)+t[e.charAt(r)],o+=6;o>=8;)((l=n>>>(o-=8)&255)||r<i-2)&&(d+=s(l));return d})(s[1])).user_id;if(null!=e&&(null==i||""===i||i!==t.id))throw Error("userToken does not have a user_id or is not matching with user.id")}}},this.tokenReady=()=>this.loadTokenPromise,this.loadToken=()=>(this.loadTokenPromise=new Promise(async(e,t)=>{if("static"===this.type)return e(this.token);if(this.tokenProvider&&"string"!=typeof this.tokenProvider){try{this.token=await this.tokenProvider()}catch(e){return t(Error(`Call to tokenProvider failed with message: ${e}`,{cause:e}))}e(this.token)}}),this.loadTokenPromise),this.getToken=()=>{if(this.token||this.user&&this.user.anon&&!this.token)return this.token;if(this.secret)return re(this.secret);throw Error("Both secret and user tokens are not set. Either client.connectUser wasn't called or client.disconnect was called")},this.isStatic=()=>"static"===this.type,this.loadTokenPromise=null,e&&(this.secret=e),this.type="static",this.secret&&(this.token=re(this.secret))}},rs=class{constructor({client:e}){this._onlineStatusChanged=e=>{if(this._log(`_onlineStatusChanged() - ${e.type}`),"offline"===e.type){this._setState("CLOSED"),this.cancelToken?.cancel("disconnect() is called"),this.cancelToken=void 0;return}"online"===e.type&&"CLOSED"===this.state&&this.connect(!0)},this._req=async(e,t,s)=>{this.cancelToken||e.close||(this.cancelToken=tB.CancelToken.source());try{let s=await this.client.doAxiosRequest("get",this.client.baseURL.replace(":3030",":8900")+"/longpoll",void 0,{config:{...t,cancelToken:this.cancelToken?.token},params:e});return this.consecutiveFailures=0,s}catch(i){if(this.consecutiveFailures+=1,s&&nl(i))return this._log("_req() - Retryable error, retrying request"),await iB(iW(this.consecutiveFailures)),this._req(e,t,s);throw i}},this._poll=async()=>{for(;"CONNECTED"===this.state;)try{let e=await this._req({},{timeout:3e4},!0);if(e.events?.length)for(let t=0;t<e.events.length;t++)this.client.dispatchEvent(e.events[t])}catch(e){if(tB.isCancel(e))return void this._log("_poll() - axios canceled request");
1if(46===e.code){this._log("_poll() - ConnectionID error, connecting without ID..."),this._setState("DISCONNECTED"),this.connect(!0);return}if(no(e)&&!nl(e))return void this._setState("CLOSED");await iB(iW(this.consecutiveFailures))}},this.connect=async(e=!1)=>{if("CONNECTING"===this.state)return void this._log("connect() - connecting already in progress",{reconnect:e},"warn");if("CONNECTED"===this.state)return void this._log("connect() - already connected and polling",{reconnect:e},"warn");this._setState("CONNECTING"),this.connectionID=void 0;try{let{event:t}=await this._req({json:this.client._buildWSPayload()},{timeout:8e3},e);return this._setState("CONNECTED"),this.connectionID=t.connection_id,this.client.dispatchEvent(t),this._poll(),e&&this.client.recoverState(),t}catch(e){throw this._setState("CLOSED"),e}},this.isHealthy=()=>!!this.connectionID&&"CONNECTED"===this.state,this.disconnect=async(e=2e3)=>{iJ(this._onlineStatusChanged),this._setState("DISCONNECTED"),this.cancelToken?.cancel("disconnect() is called"),this.cancelToken=void 0;let t=this.connectionID;this.connectionID=void 0;try{await this._req({close:!0,connection_id:t},{timeout:e},!1),this._log("disconnect() - Closed connectionID")}catch(e){this._log("disconnect() - Failed",{err:e},"error")}},this.client=e,this.state="INIT",this.consecutiveFailures=0,iK(this._onlineStatusChanged)}_log(e,t={},s="info"){this.client.logger(s,"WSConnectionFallback:"+e,{tags:["connection_fallback","connection"],...t})}_setState(e){this._log(`_setState() - ${e}`),"CONNECTING"===this.state&&"CONNECTED"===e&&this.client.dispatchEvent({type:"connection.changed",online:!0}),("CLOSED"===e||"DISCONNECTED"===e)&&this.client.dispatchEvent({type:"connection.changed",online:!1}),this.state=e}},ri=class{constructor(e,t,s,i){this.client=e,this.type=t,this.id=s,this.data=i}create(){let e={name:this.data?.name,filter:this.data?.filter,description:this.data?.description,all_sender_channels:this.data?.all_sender_channels,all_users:this.data?.all_users};return this.client.createSegment(this.type,this.id,e)}verifySegmentId(){if(!this.id)throw Error("Segment id is missing. Either create the segment using segment.create() or set the id during instantiation - const segment = client.segment(id)")}get(){return this.verifySegmentId(),this.client.getSegment(this.id)}update(e){return this.verifySegmentId(),this.client.updateSegment(this.id,e)}addTargets(e){return this.verifySegmentId(),this.client.addSegmentTargets(this.id,e)}removeTargets(e){return this.verifySegmentId(),this.client.removeSegmentTargets(this.id,e)}delete(){return this.verifySegmentId(),this.client.deleteSegment(this.id)}targetExists(e){return this.verifySegmentId(),this.client.segmentTargetExists(this.id,e)}queryTargets(e={},t=[],s={}){return this.verifySegmentId(),this.client.querySegmentTargets(this.id,e,t,s)}},ra="stream:chat:v1:message",rn=class{constructor(e){this.client=e}flagUser(e,t,s={}){return this.flag("stream:user",e,"",t,s)}flagMessage(e,t,s={}){return this.flag(ra,e,"",t,s)}async flag(e,t,s,i,a={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/flag",{entity_type:e,entity_id:t,entity_creator_id:s,reason:i,...a})}async muteUser(e,t={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/mute",{target_ids:[e],...t})}async unmuteUser(e,t){return await this.client.post(this.client.baseURL+"/api/v2/moderation/unmute",{target_ids:[e],...t})}async getUserModerationReport(e,t={}){return await this.client.get(this.client.baseURL+"/api/v2/moderation/user_report",{user_id:e,...t})}async queryReviewQueue(e={},t=[],s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/review_queue",{filter:e,sort:iV(t),...s})}async upsertConfig(e){return await this.client.post(this.client.baseURL+"/api/v2/moderation/config",e)}async getConfig(e,t){return await this.client.get(this.client.baseURL+"/api/v2/moderation/config/"+e,t)}async deleteConfig(e,t){return await this.client.delete(this.client.baseURL+"/api/v2/moderation/config/"+e,t)}async queryConfigs(e,t,s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/configs",{filter:e,sort:t,...s})}async submitAction(e,t,s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/submit_action",{action_type:e,item_id:t,...s})}async check(e,t,s,i,a,n){return await this.client.post(this.client.baseURL+"/api/v2/moderation/check",{entity_type:e,entity_id:t,entity_creator_id:s,moderation_payload:i,config_key:a,options:n})}async checkUserProfile(e,t){if(!t.username&&!t.image)throw Error("Either username or image must be provided");let s={};return t.username&&(s.texts=[t.username]),t.image&&(s.images=[t.image]),await this.check("stream:v1:u
1ser_profile",e,e,s,"user_profile:default",{force_sync:!0,test_mode:!0})}async addCustomFlags(e,t,s,i,a){return await this.client.post(this.client.baseURL+"/api/v2/moderation/custom_check",{entity_type:e,entity_id:t,entity_creator_id:s,moderation_payload:i,flags:a})}async addCustomMessageFlags(e,t){return await this.addCustomFlags(ra,e,"",{},t)}async upsertModerationRule(e){return await this.client.post(this.client.baseURL+"/api/v2/moderation/moderation_rule",e)}async queryModerationRules(e={},t=[],s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/moderation_rules",{filter:e,sort:t,...s})}async getModerationRule(e){return await this.client.get(this.client.baseURL+"/api/v2/moderation/moderation_rule/"+e)}async deleteModerationRule(e){return await this.client.delete(this.client.baseURL+"/api/v2/moderation/moderation_rule/"+e)}},rr={active:!1,isThreadOrderStale:!1,threads:[],unreadThreadCount:0,unseenThreadIds:[],lastConnectionDropAt:null,pagination:{isLoading:!1,isLoadingNext:!1,nextCursor:null},ready:!1},ro=class extends af{constructor({client:e}){super(),this.resetState=()=>{this.state.next(rr)},this.activate=()=>{this.state.partialNext({active:!0})},this.deactivate=()=>{this.state.partialNext({active:!1})},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeUnreadThreadsCountChange()),this.addUnsubscribeFunction(this.subscribeManageThreadSubscriptions()),this.addUnsubscribeFunction(this.subscribeReloadOnActivation()),this.addUnsubscribeFunction(this.subscribeNewReplies()),this.addUnsubscribeFunction(this.subscribeRecoverAfterConnectionDrop()),this.addUnsubscribeFunction(this.subscribeChannelDeleted()))},this.subscribeUnreadThreadsCountChange=()=>{let{unread_threads:e=0}=this.client.user??{};this.state.partialNext({unreadThreadCount:e});let t=["health.check","notification.mark_read","notification.thread_message_new","notification.channel_deleted"].map(e=>this.client.on(e,e=>{let{unread_threads:t}=e.me??e;"number"==typeof t&&this.state.partialNext({unreadThreadCount:t})}).unsubscribe);return()=>t.forEach(e=>e())},this.subscribeChannelDeleted=()=>this.client.on("notification.channel_deleted",e=>{let{cid:t}=e,{threads:s}=this.state.getLatestValue(),i=s.filter(e=>e.channel.cid!==t);this.state.partialNext({threads:i})}).unsubscribe,this.subscribeManageThreadSubscriptions=()=>this.state.subscribeWithSelector(e=>({threads:e.threads}),({threads:e},t)=>{let{threads:s=[]}=t??{},i=s.filter(e=>e!==this.threadsById[e.id]);e.forEach(e=>
1e.registerSubscriptions()),i.forEach(e=>e.unregisterSubscriptions())}),this.subscribeReloadOnActivation=()=>this.state.subscribeWithSelector(e=>({active:e.active}),({active:e})=>{e&&this.reload()}),this.subscribeNewReplies=()=>this.client.on("notification.thread_message_new",e=>{let t=e.message?.parent_id;if(!t)return;let{unseenThreadIds:s,ready:i}=this.state.getLatestValue();i&&(this.threadsById[t]?this.state.partialNext({isThreadOrderStale:!0}):s.includes(t)||this.state.partialNext({unseenThreadIds:s.concat(t)}))}).unsubscribe,this.subscribeRecoverAfterConnectionDrop=()=>{let e=this.client.on("connection.changed",e=>{!1===e.online&&this.state.next(e=>e.lastConnectionDropAt?e:{...e,lastConnectionDropAt:new Date})}).unsubscribe,t=i4(()=>{let{lastConnectionDropAt:e}=this.state.getLatestValue();e&&this.reload({force:!0})},1e3,{trailing:!0}),s=this.client.on("connection.recovered",t).unsubscribe;return()=>{e(),s()}},this.unregisterSubscriptions=()=>(this.state.getLatestValue().threads.forEach(e=>e.unregisterSubscriptions()),super.unregisterSubscriptions()),this.reload=async({force:e=!1}={})=>{let{threads:t,unseenThreadIds:s,isThreadOrderStale:i,pagination:a,ready:n}=this.state.getLatestValue();if(a.isLoading||!e&&n&&!s.length&&!i)return;let r=t.length+s.length;try{this.state.next(e=>({...e,pagination:{...e.pagination,isLoading:!0}}));let e=await this.queryThreads({limit:Math.min(r,25)||25}),t=[];for(let s of e.threads){let e=this.threadsById[s.id];e?(t.push(e),e.hasStaleState&&e.hydrateState(s)):t.push(s)}this.state.next(s=>({...s,threads:t,unseenThreadIds:[],isThreadOrderStale:!1,pagination:{...s.pagination,isLoading:!1,nextCursor:e.next??null},ready:!0}))}catch(e){this.client.logger("error",e.message),this.state.next(e=>({...e,pagination:{...e.pagination,isLoading:!1}}))}},this.queryThreads=(e={})=>this.client.queryThreads({limit:25,participant_limit:10,reply_limit:10,watch:!0,...e}),this.loadNextPage=async(e={})=>{let{pagination:t}=this.state.getLatestValue();if(!t.isLoadingNext&&t.nextCursor)try{this.state.partialNext({pagination:{...t,isLoadingNext:!0}});let s=await this.queryThreads({...e,next:t.nextCursor});this.state.next(e=>({...e,threads:s.threads.length?e.threads.concat(s.threads):e.threads,pagination:{...e.pagination,nextCursor:s.next??null,isLoadingNext:!1}}))}catch(e){this.client.logger("error",e.message),this.state.next(e=>({...e,pagination:{...e.pagination,isLoadingNext:!1}}))}},this.client=e,this.state=new ag(rr),this.threadsByIdGetterCache={threads:[],threadsById:{}}}get threadsById(){let{threads:e}=this.state.getLatestValue();if(e===this.threadsByIdGetterCache.threads)return this.threadsByIdGetterCache.threadsById;let t=e.reduce((e,t)=>(e[t.id]=t,e),{});return this.threadsByIdGetterCache.threads=e,this.threadsByIdGetterCache.threadsById=t,t}},rl=e=>!!e?.answer_text,rd=class{constructor({client:e,poll:t}){this.getInitialStateFromPollResponse=e=>{var t;let{own_votes:s,id:i,...a}=e,{ownAnswer:n,ownVotes:r}=s?.reduce((e,t)=>(rl(t)?e.ownAnswer=t:e.ownVotes.push(t),e),{ownVotes:[]})??{ownVotes:[]};return{...a,lastActivityAt:new Date,maxVotedOptionIds:rc(a.vote_counts_by_option),ownAnswer:n,ownVotesByOptionId:(t=r)?t.reduce((e,t)=>(rl(t)||!t.option_id||(e[t.option_id]=t),e),{}):{}}},this.upsertOfflineDb=()=>{this.client.offlineDb?.executeQuerySafely(e=>e.upsertPoll({poll:function(e){let{lastActivityAt:t,maxVotedOptionIds:s,ownVotesByOptionId:i,ownAnswer:a,...n}=e.data,r=[...Object.values(i),...a?[a]:[]].sort((e,t)=>Date.parse(e.created_at)-Date.parse(t.created_at));return{...n,own_votes:r,id:e.id}}(this)}),{method:"upsertPoll"})},this.reinitializeState=e=>{this.state.partialNext(this.getInitialStateFromPollResponse(e))},this.handlePollUpdated=e=>{var t;if(e.poll?.id&&e.poll.id!==this.id||"poll.updated"!==e.type)return;let{id:s,...i}={allow_answers:(t=e.poll).allow_answers,allow_user_suggested_options:t.allow_user_suggested_options,description:t.description,enforce_unique_vote:t.enforce_unique_vote,id:t.id,is_closed:t.is_closed,max_votes_allowed:t.max_votes_allowed,name:t.name,options:t.options,voting_visibility:t.voting_visibility};this.state.partialNext({...i,lastActivityAt:new Date(e.created_at)}),this.upsertOfflineDb()},this.handlePollClosed=e=>{e.poll?.id&&e.poll.id!==this.id||"poll.closed"===e.type&&(this.state.partialNext({is_closed:!0,lastActivityAt:new Date(e.created_at)}),this.upsertOfflineDb())},this.handleVoteCasted=e=>{if(e.poll?.id&&e.poll.id!==this.id||"poll.vote_casted"!==e.type)return;let t=this.data,s=e.poll_vote.user_id===this.client.userID,i=[...t.latest_answers],a=t.ownAnswer,n=t.ownVotesByOptionId,r=t.maxVotedOptionIds;s&&(rl(e.poll_vote)?a=e.poll_vote:e.poll_vote.option_id&&(n[e.poll_vote.option_id]=e.poll_vote)),rl(e.poll_vote)?i=[e.poll_vote,...i]:r=rc(e.poll.vote_counts_by_option);let o=rh(e.poll);this.state.partialNext({...o,latest_answers:i,lastActivityAt:new Date(e.created_at),ownAnswer:a,ownVotesByOptionId:n,maxVotedOptionIds:r}),this.upsertOfflineDb()},this.handleVoteChanged=e=>{if(e.poll?.id&&e.poll.id!==this.id||"poll.vote_changed"!==e.type)return;let t=this.data,s=e.poll_vote.user_id===this.client.userID,i=[...t.latest_answers],a=t.ownAnswer,n=t.ownVotesByOptionId,r=t.maxVotedOptionIds;s?rl(e.poll_vote)?(i=[e.poll_vote,...i.filter(t=>t.id!==e.poll_vote.id)],a=e.poll_vote):e.poll_vote.option_id&&(e.poll.enforce_unique_vote?n={[e.poll_vote.option_id]:e.poll_vote}:(n=Object.entries(n).reduce((t,[s,i])=>(s!==e.poll_vote.option_id&&i.id===e.poll_vote.id||(t[s]=i),t),{}))[e.poll_vote.option_id]=e.poll_vote,a?.id===e.poll_vote.id&&(a=void 0),r=rc(e.poll.vote_counts_by_option)):rl(e.poll_vote)?i=[e.poll_vote,...i]:r=rc(e.poll.vote_counts_by_option);let o=rh(e.poll);this.state.partialNext({...o,latest_answers:i,lastActivityAt:new Date(e.created_at),ownAnswer:a,ownVotesByOptionId:n,maxVotedOptionIds:r}),this.upsertOfflineDb()},this.handleVoteRemoved=e=>{if(e.poll?.id&&e.poll.id!==this.id||"poll.vote_removed"!==e.type)return;let t=this.data,s=e.poll_vote.user_id===this.client.userID,i=[...t.latest_answers],a=t.ownAnswer,n={...t.ownVotesByOptionId},r=t.maxVotedOptionIds;rl(e.poll_vote)?(i=i.filter(t=>t.id!==e.poll_vote.id),s&&(a=void 0)):(r=rc(e.poll.vote_counts_by_option),s&&e.poll_vote.option_id&&delete n[e.poll_vote.option_id]);let o=rh(e.poll);this.state.partialNext({...o,latest_answers:i,lastActivityAt:new Date(e.created_at),ownAnswer:a,ownVotesByOptionId:n,maxVotedOptionIds:r}),this.upsertOfflineDb()},this.query=async e=>{let{poll:t}=await this.client.getPoll(e);return this.state.partialNext({...t,lastActivityAt:new Date}),t},this.update=async e=>await this.client.updatePoll({...e,id:this.id}),this.partialUpdate=async e=>await this.client.partialUpdatePoll(this.id,e),this.close=async()=>
1await this.client.closePoll(this.id),this.delete=async()=>await this.client.deletePoll(this.id),this.createOption=async e=>await this.client.createPollOption(this.id,e),this.updateOption=async e=>await this.client.updatePollOption(this.id,e),this.deleteOption=async e=>await this.client.deletePollOption(this.id,e),this.castVote=async(e,t)=>{let{max_votes_allowed:s,ownVotesByOptionId:i}=this.data;return s&&s===Object.keys(i).length?void this.client.notifications.addInfo({message:"Reached the vote limit. Remove an existing vote first.",origin:{emitter:"Poll",context:{messageId:t,optionId:e}},options:{type:"validation:poll:castVote:limit"}}):await this.client.castPollVote(t,this.id,{option_id:e})},this.removeVote=async(e,t)=>await this.client.removePollVote(t,this.id,e),this.addAnswer=async(e,t)=>await this.client.addPollAnswer(t,this.id,e),this.removeAnswer=async(e,t)=>await this.client.removePollVote(t,this.id,e),this.queryAnswers=async e=>await this.client.queryPollAnswers(this.id,e.filter,e.sort,e.options),this.queryOptionVotes=async e=>await this.client.queryPollVotes(this.id,e.filter,e.sort,e.options),this.client=e,this.id=t.id,this.state=new ag(this.getInitialStateFromPollResponse(t))}get data(){return this.state.getLatestValue()}};function rc(e){let t=0,s=[];for(let[i,a]of Object.entries(e??{}))a>t?(s=[i],t=a):a===t&&s.push(i);return s}function rh(e){return{answers_count:e.answers_count,latest_votes_by_option:e.latest_votes_by_option,vote_count:e.vote_count,vote_counts_by_option:e.vote_counts_by_option}}var ru=class extends af{constructor({client:e}){super(),this.pollCache=new Map,this.fromState=e=>this.pollCache.get(e),this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeMessageNew()),this.addUnsubscribeFunction(this.subscribePollUpdated()),this.addUnsubscribeFunction(this.subscribePollClosed()),this.addUnsubscribeFunction(this.subscribeVoteCasted()),this.addUnsubscribeFunction(this.subscribeVoteChanged()),this.addUnsubscribeFunction(this.subscribeVoteRemoved()))},this.createPoll=async e=>{let{poll:t}=await this.client.createPoll(e);return t.vote_counts_by_option||(t.vote_counts_by_option={}),this.setOrOverwriteInCache(t),this.fromState(t.id)},this.getPoll=async e=>{let t=this.fromState(e);if(t)return this.client.getPoll(e).then(({poll:e})=>this.setOrOverwriteInCache(e,!0)),t;let{poll:s}=await this.client.getPoll(e);return this.setOrOverwriteInCache(s),this.fromState(e)},this.queryPolls=async(e,t=[],s={})=>{let{polls:i,next:a}=await this.client.queryPolls(e,t,s);return{polls:i.map(e=>(this.setOrOverwriteInCache(e,!0),this.fromState(e.id))),next:a}},this.hydratePollCache=(e,t)=>{for(let s of e){if(!s.poll)continue;let e=s.poll;this.setOrOverwriteInCache(e,t)}},this.setOrOverwriteInCache=(e,t)=>{if(!this.client._cacheEnabled())return;let s=this.fromState(e.id);if(s)t&&s.reinitializeState(e);else{let t=new rd({client:this.client,poll:e});this.pollCache.set(t.id,t)}},this.subscribePollUpdated=()=>this.client.on("poll.updated",e=>{e.poll?.id&&this.fromState(e.poll.id)?.handlePollUpdated(e)}).unsubscribe,this.subscribePollClosed=()=>this.client.on("poll.closed",e=>{e.poll?.id&&this.fromState(e.poll.id)?.handlePollClosed(e)}).unsubscribe,this.subscribeVoteCasted=()=>this.client.on("poll.vote_casted",e=>{e.poll?.id&&this.fromState(e.poll.id)?.handleVoteCasted(e)}).unsubscribe,this.subscribeVoteChanged=()=>this.client.on("poll.vote_changed",e=>{e.poll?.id&&this.fromState(e.poll.id)?.handleVoteChanged(e)}).unsubscribe,this.subscribeVoteRemoved=()=>this.client.on("poll.vote_removed",e=>{e.poll?.id&&this.fromState(e.poll.id)?.handleVoteRemoved(e)}).unsubscribe,this.subscribeMessageNew=()=>this.client.on("message.new",e=>{let{message:t}=e;if(t){let e=iY(t);this.hydratePollCache([e])}}).unsubscribe,this.client=e}get data(){return this.pollCache}},rg={"channel.deleted":"channelDeletedHandler","channel.hidden":"channelHiddenHandler","channel.truncated":"channelTruncatedHandler","channel.updated":"channelUpdatedHandler","channel.visible":"channelVisibleHandler","message.new":"newMessageHandler","member.updated":"memberUpdatedHandler","notification.added_to_channel":"notificationAddedToChannelHandler","notification.message_new":"notificationNewMessageHandler","notification.removed_from_channel":"notificationRemovedFromChannelHandler"},rp={abortInFlightQuery:!1,allowNotLoadedChannelPromotionForEvent:{"channel.visible":!0,"message.new":!0,"notification.added_to_channel":!0,"notification.message_new":!0},lockChannelOrder:!1},rm={offset:0},rf=class extends af{constructor({client:e,eventHandlerOverrides:t={},options:s={},queryChannelsOverride:i}){super(),this.eventHandlers=new Map,this.eventHandlerOverrides=new Map,this.options={},this.stateOptions={},this.setChannels=e=>{this.state.next(t=>{let{channels:s}=t,i="function"==typeof e?e(s):e;return s===i?t:{...t,channels:i}});let{channels:t,pagination:{filters:s,sort:i}}=this.state.getLatestValue();this.client.offlineDb?.executeQuerySafely(e=>e.upsertCidsForQuery({cids:t.map(e=>e.cid),filters:s,sort:i}),{method:"upsertCidsForQuery"})},this.setEventHandlerOverrides=(e={})=>{let t=Object.entries(e).reduce((e,[t,s])=>(s&&(e[t]=s),e),{});this.eventHandlerOverrides=new Map(Object.entries(t))},this.setQueryChannelsRequest=e=>{this.queryChannelsRequest=e},this.setOptions=(e={})=>{this.options={...rp,...e}},this.executeChannelsQuery=async(e,t=0)=>{let{filters:s,sort:i,options:a,stateOptions:n}=e,{offset:r,limit:o}={...rm,...a};try{let e=await this.queryChannelsRequest(s,i,a,n),t=r+(e?.length??0),l={...a,offset:t},{pagination:d}=this.state.getLatestValue();this.state.partialNext({channels:e,pagination:{...d,hasNext:(e?.length??0)>=(o??1),isLoading:!1,options:l},initialized:!0,error:void 0}),this.client.offlineDb?.executeQuerySafely(t=>t.upsertCidsForQuery({cids:e.map(e=>e.cid),filters:d.filters,sort:d.sort}),{method:"upsertCidsForQuery"})}catch(s){if(t>=3){console.warn(s);let e=Error(`Maximum number of retries reached in queryChannels. Last error message is: ${s}`),t=this.state.getLatestValue(),i=this.client.offlineDb&&t.channels.length>0;this.state.partialNext({error:i?void 0:e,pagination:{...t.pagination,isLoading:!1,isLoadingNext:!1}});return}return await iB(1e3),this.executeChannelsQuery(e,t+1)}},this.queryChannels=async(e,t=[],s={},i={})=>{let{pagination:{isLoading:a,filters:n},initialized:r}=this.state.getLatestValue();if(a&&!this.options.abortInFlightQuery&&JSON.stringify(n)===JSON.stringify(e))return;
1let o={filters:e,sort:t,options:s,stateOptions:i};try{if(this.stateOptions=i,this.state.next(i=>({...i,pagination:{...i.pagination,isLoading:!0,isLoadingNext:!1,filters:e,sort:t,options:s},error:void 0})),this.client.offlineDb?.getChannelsForQuery&&this.client.user?.id){if(!r){let s=await this.client.offlineDb.getChannelsForQuery({userId:this.client.user.id,filters:e,sort:t});if(s){let e=this.client.hydrateActiveChannels(s,{offlineMode:!0,skipInitialization:[]});this.state.partialNext({channels:e})}}if(!this.client.offlineDb.syncManager.syncStatus)return void this.client.offlineDb.syncManager.scheduleSyncStatusChangeCallback(this.id,async()=>{await this.executeChannelsQuery(o)})}await this.executeChannelsQuery(o)}catch(e){throw this.client.logger("error",e.message),this.state.next(e=>({...e,pagination:{...e.pagination,isLoading:!1}})),e}},this.loadNext=async()=>{let{pagination:e,initialized:t}=this.state.getLatestValue(),{filters:s,sort:i,options:a,isLoadingNext:n,hasNext:r}=e;if(t&&!n&&r)try{let{offset:t,limit:n}={...rm,...a};this.state.partialNext({pagination:{...e,isLoading:!1,isLoadingNext:!0}});let r=await this.queryChannelsRequest(s,i,a,this.stateOptions),{channels:o}=this.state.getLatestValue(),l=t+(r?.length??0),d={...a,offset:l};this.state.partialNext({channels:((e,t)=>{if(!Array.isArray(e))return[];let s=new Set;return e.filter(e=>{let i="function"==typeof t?t(e):t.split(".").reduce((e,t)=>{if(e&&"object"==typeof e&&t in e)return e[t]},e);return!s.has(i)&&(s.add(i),!0)})})([...o||[],...r],"cid"),pagination:{...e,hasNext:(r?.length??0)>=(n??1),isLoading:!1,isLoadingNext:!1,options:d}})}catch(e){throw this.client.logger("error",e.message),this.state.next(e=>({...e,pagination:{...e.pagination,isLoadingNext:!1,isLoading:!1}})),e}},this.notificationAddedToChannelHandler=async e=>{let{id:t,type:s,members:i}=e?.channel??{};if(!s||!this.options.allowNotLoadedChannelPromotionForEvent?.["notification.added_to_channel"])return;let a=await i8({client:this.client,id:t,members:i?.reduce((e,{user:t,user_id:s})=>{let i=s||t?.id;return i&&e.push(i),e},[]),type:s}),{pagination:n,channels:r}=this.state.getLatestValue();if(!r)return;let{sort:o}=n??{};this.setChannels(ar({channels:r,channelToMove:a,sort:o}))},this.channelDeletedHandler=e=>{let{channels:t}=this.state.getLatestValue();if(!t)return;let s=[...t],i=s.findIndex(t=>t.cid===(e.cid||e.channel?.cid));i<0||(s.splice(i,1),this.setChannels(s))},this.channelHiddenHandler=this.channelDeletedHandler,this.newMessageHandler=e=>{let{pagination:t,channels:s}=this.state.getLatestValue();if(!s)return;let{filters:i,sort:a}=t??{},n=e.channel_type,r=e.channel_id;if(!n||!r)return;let o=this.client.channel(n,r),l=s.indexOf(o),d=l>=0,c=i9(o),h=ae(o),u=at(i),g=ai(a);(!u||!h||i.archived)&&(!u||h||!i.archived)&&(!g||!c)&&!this.options.lockChannelOrder&&(d||this.options.allowNotLoadedChannelPromotionForEvent?.["message.new"])&&this.setChannels(ar({channels:s,channelToMove:o,channelToMoveIndexWithinChannels:l,sort:a}))},this.notificationNewMessageHandler=async e=>{let{id:t,type:s}=e?.channel??{};if(!t||!s)return;let i=await i8({client:this.client,id:t,type:s}),{channels:a,pagination:n}=this.state.getLatestValue(),{filters:r,sort:o}=n??{},l=at(r),d=ae(i);a&&(!l||!d||r.archived)&&(!l||d||!r.archived)&&this.options.allowNotLoadedChannelPromotionForEvent?.["notification.message_new"]&&this.setChannels(ar({channels:a,channelToMove:i,sort:o}))},this.channelVisibleHandler=async e=>{let{channel_type:t,channel_id:s}=e;if(!t||!s)return;let i=await i8({client:this.client,id:e.channel_id,type:e.channel_type}),{channels:a,pagination:n}=this.state.getLatestValue(),{sort:r,filters:o}=n??{},l=at(o),d=ae(i);a&&(!l||!d||o.archived)&&(!l||d||!o.archived)&&this.options.allowNotLoadedChannelPromotionForEvent?.["channel.visible"]&&this.setChannels(ar({channels:a,channelToMove:i,sort:r}))},this.notificationRemovedFromChannelHandler=this.channelDeletedHandler,this.memberUpdatedHandler=e=>{let{pagination:t,channels:s}=this.state.getLatestValue(),{filters:i,sort:a}=t;if(!e.member?.user||e.member.user.id!==this.client.userID||!e.channel_type||!e.channel_id)return;let n=e.channel_type,r=e.channel_id,o=ai(a),l=at(i),d=as({atIndex:0,sort:
1a,targetKey:"pinned_at"});if(!s||!o&&!l||this.options.lockChannelOrder)return;let c=this.client.channel(n,r),h=s.indexOf(c),u=h>=0,g=i9(c),p=ae(c),m=[...s];if(u&&m.splice(h,1),l&&!p&&i?.archived||l&&p&&!i?.archived)return void this.setChannels(m);let f=null;1!==d&&(-1!==d||g)||(f=an({channels:m}));let y="number"==typeof f?f+1:0;s[y]!==c&&(m.splice(y,0,c),this.setChannels(m))},this.subscriptionOrOverride=e=>{let t=rg[e.type],s=this.eventHandlers.get(t),i=this.eventHandlerOverrides.get(t);i&&"function"==typeof i?i(this.setChannels,e):s&&"function"==typeof s&&s(e)},this.registerSubscriptions=()=>{if(!this.hasSubscriptions)for(let e of Object.keys(rg))this.addUnsubscribeFunction(this.client.on(e,this.subscriptionOrOverride).unsubscribe)},this.id=`channel-manager-${iz()}`,this.client=e,this.state=new ag({channels:[],pagination:{isLoading:!1,isLoadingNext:!1,hasNext:!1,filters:{},sort:{},options:rm},initialized:!1,error:void 0}),this.setEventHandlerOverrides(t),this.setOptions(s),this.queryChannelsRequest=i??((...e)=>this.client.queryChannels(...e)),this.eventHandlers=new Map(Object.entries({channelDeletedHandler:this.channelDeletedHandler,channelHiddenHandler:this.channelHiddenHandler,channelVisibleHandler:this.channelVisibleHandler,memberUpdatedHandler:this.memberUpdatedHandler,newMessageHandler:this.newMessageHandler,notificationAddedToChannelHandler:this.notificationAddedToChannelHandler,notificationNewMessageHandler:this.notificationNewMessageHandler,notificationRemovedFromChannelHandler:this.notificationRemovedFromChannelHandler}))}},ry={durations:{error:3e3,info:3e3,success:3e3,warning:3e3}},rb=class{constructor(e={}){this.timeouts=new Map,this.store=new ag({notifications:[]}),this.config=aV(ry,e)}get notifications(){return this.store.getLatestValue().notifications}get warning(){return this.notifications.filter(e=>"warning"===e.severity)}get error(){return this.notifications.filter(e=>"error"===e.severity)}get info(){return this.notifications.filter(e=>"info"===e.severity)}get success(){return this.notifications.filter(e=>"success"===e.severity)}add({message:e,origin:t,options:s={}}){let i=iz(),a=Date.now(),n=s.severity,r=s.duration??(n?this.config.durations[n]:void 0),o={id:i,message:e,origin:t,type:s?.type,severity:n,createdAt:a,duration:r,actions:s.actions,metadata:s.metadata,tags:s.tags,originalError:s.originalError},l=[...this.store.getLatestValue().notifications,o];return this.store.partialNext({notifications:this.config.sortComparator?[...l].sort(this.config.sortComparator):l}),i}addError({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"error"}})}addWarning({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"warning"}})}addInfo({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"info"}})}addSuccess({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"success"}})}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}startTimeout(e,t){let s=this.store.getLatestValue().notifications.find(t=>t.id===e),i=t??s?.duration;if(!s||!i)return;this.clearTimeout(e);let a=setTimeout(()=>{this.remove(e)},i);this.timeouts.set(e,a)}remove(e){this.clearTimeout(e),this.store.partialNext({notifications:this.store.getLatestValue().notifications.filter(t=>t.id!==e)})}clear(){this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.store.partialNext({notifications:[]})}},r_=6e4,rw=36e5,rv=864e5,rC=class{constructor({reminder:e,config:t}){this.timeout=null,this.stopRefreshBoundaryMs=12096e5,this.getRefreshIntervalLength=()=>{if(!this.reminder.remindAt)return null;let e=Math.abs(rS(this.reminder.remindAt.getTime()));return 0===e?6e4:e<r_?e:e<=rw?6e4:e<=rv?36e5:864e5},this.init=()=>{if(!this.reminder.remindAt)return null;let e=this.getRefreshIntervalLength();if(null===e)return null;if(this.reminder.remindAt?.getTime()+this.stopRefreshBoundaryMs-Date.now()<=0){this.timeout=null;return}this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(()=>{this.reminder.refreshTimeLeft(),this.init()},e)},this.clear=()=>{this.timeout&&(clearInterval(this.timeout),this.timeout=null)}
1,this.reminder=e,"number"==typeof t?.stopRefreshBoundaryMs&&(this.stopRefreshBoundaryMs=t.stopRefreshBoundaryMs)}},rS=e=>e-new Date().getTime(),rR=class e{constructor({data:t,config:s}){this.setState=t=>{this.state.next(s=>{let i={...s,...e.toStateValue(t)};return i.remind_at&&(i.timeLeftMs=rS(i.remind_at.getTime())),i}),t.remind_at?this.initTimer():t.remind_at||this.clearTimer()},this.refreshTimeLeft=()=>{this.remindAt&&this.state.partialNext({timeLeftMs:rS(this.remindAt.getTime())})},this.initTimer=()=>{this.timer.init()},this.clearTimer=()=>{this.timer.clear()},this.state=new ag(e.toStateValue(t)),this.timer=new rC({reminder:this,config:s}),this.initTimer()}get id(){return this.state.getLatestValue().message_id}get remindAt(){return this.state.getLatestValue().remind_at}get timeLeftMs(){return this.state.getLatestValue().timeLeftMs}};rR.toStateValue=e=>({...e,created_at:new Date(e.created_at),message:e.message||null,remind_at:e.remind_at?new Date(e.remind_at):null,timeLeftMs:e.remind_at?rS(new Date(e.remind_at).getTime()):null,updated_at:new Date(e.updated_at),user:e.user||null});var rU={scheduledOffsetsMs:[12e4,18e5,36e5,72e5,288e5,864e5],stopTimerRefreshBoundaryMs:12096e5},rI=class e extends af{constructor({client:t,config:s}){super(),this.upsertToState=({data:e,overwrite:t=!0})=>{if(!this.client._cacheEnabled())return;let s=this.getFromState(e.message_id);if(s)t&&s.setState(e);else{let t=new rR({data:e,config:{stopRefreshBoundaryMs:this.stopTimerRefreshBoundaryMs}});this.state.partialNext({reminders:new Map(this.reminders.set(e.message_id,t))})}return s},this.removeFromState=e=>{let t=this.getFromState(e);if(!t)return;t.clearTimer();let s=this.reminders;s.delete(e),this.state.partialNext({reminders:new Map(s)})},this.hydrateState=e=>{e.forEach(({reminder:e})=>{e&&this.upsertToState({data:e})})},this.initTimers=()=>{this.reminders.forEach(e=>e.initTimer())},this.clearTimers=()=>{this.reminders.forEach(e=>e.clearTimer())},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeReminderCreated()),this.addUnsubscribeFunction(this.subscribeReminderUpdated()),this.addUnsubscribeFunction(this.subscribeReminderDeleted()),this.addUnsubscribeFunction(this.subscribeNotificationReminderDue()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeMessageUndeleted()),this.addUnsubscribeFunction(this.subscribePaginatorStateUpdated()),this.addUnsubscribeFunction(this.subscribeConfigStateUpdated()))},this.subscribeReminderCreated=()=>this.client.on("reminder.created",t=>{if(!e.isReminderWsEventPayload(t))return;let{reminder:s}=t;this.upsertToState({data:s})}).unsubscribe,this.subscribeReminderUpdated=()=>this.client.on("reminder.updated",t=>{if(!e.isReminderWsEventPayload(t))return;let{reminder:s}=t;this.upsertToState({data:s})}).unsubscribe,this.subscribeReminderDeleted=()=>this.client.on("reminder.deleted",t=>{e.isReminderWsEventPayload(t)&&this.removeFromState(t.message_id)}).unsubscribe,this.subscribeMessageDeleted=()=>this.client.on("message.deleted",e=>{e.message?.id&&this.removeFromState(e.message.id)}).unsubscribe,this.subscribeMessageUndeleted=()=>this.client.on("message.undeleted",e=>{e.message?.reminder&&this.upsertToState({data:e.message.reminder})}).unsubscribe,this.subscribeNotificationReminderDue=()=>this.client.on("notification.reminder_due",()=>null).unsubscribe,this.subscribePaginatorStateUpdated=()=>this.paginator.state.subscribeWithSelector(({items:e})=>[e],([e])=>{if(e)for(let t of e)this.upsertToState({data:t})}),this.subscribeConfigStateUpdated=()=>this.configState.subscribeWithSelector(({stopTimerRefreshBoundaryMs:e})=>({stopTimerRefreshBoundaryMs:e}),({stopTimerRefreshBoundaryMs:e},t)=>{"number"==typeof e&&e!==t?.stopTimerRefreshBoundaryMs&&this.reminders.forEach(t=>{t.timer&&(t.timer.stopRefreshBoundaryMs=e)})}),this.upsertReminder=async e=>{let{messageId:t}=e;if(this.getFromState(t))try{return await this.updateReminder(e)}catch(t){if(t.message.match("reminder does not exist"))return await this.createReminder(e);throw t}try{return await this.createReminder(e)}catch(t){if(t.message.match("already has reminder created for this message_id"))return await this.updateReminder(e);throw t}},this.createReminder=async e=>{let{reminder:t}=await this.client.createReminder(e);return this.upsertToState({data:t,overwrite:!1})},this.updateReminder=async e=>{let{reminder:t}=await this.client.updateReminder(e);return this.upsertToState({data:t})},this.deleteReminder=async e=>{await this.client.deleteReminder(e),this.removeFromState(e)},this.queryNextReminders=async()=>{await this.paginator.next()},this.queryPreviousReminders=async()=>{await this.paginator.prev()},this.client=t,this.configState=new ag({scheduledOffsetsMs:s?.scheduledOffsetsMs??rU.scheduledOffsetsMs,stopTimerRefreshBoundaryMs:s?.stopTimerRefreshBoundaryMs??rU.stopTimerRefreshBoundaryMs}),this.state=new ag({reminders:new Map}),this.paginator=new ny(t)}updateConfig(e){"number"==typeof e.stopTimerRefreshBoundaryMs&&e.stopTimerRefreshBoundaryMs!==this.stopTimerRefreshBoundaryMs&&this.reminders.forEac
1h(t=>{t.timer.stopRefreshBoundaryMs=e?.stopTimerRefreshBoundaryMs}),this.configState.partialNext(e)}get stopTimerRefreshBoundaryMs(){return this.configState.getLatestValue().stopTimerRefreshBoundaryMs}get scheduledOffsetsMs(){return this.configState.getLatestValue().scheduledOffsetsMs}get reminders(){return this.state.getLatestValue().reminders}getFromState(e){return this.reminders.get(e)}};function rx(e){return"string"==typeof e||e instanceof String}rI.isReminderWsEventPayload=e=>!!e.reminder&&(e.type.startsWith("reminder.")||"notification.reminder_due"===e.type);var rL=class e{constructor(e,t,s){this.preventThreadCleanup=!1,this.nextRequestAbortController=null,this._messageComposerSetupState=new ag({setupFunction:null}),this._getConnectionID=()=>this.wsConnection?.connectionID||this.wsFallback?.connectionID,this._hasConnectionID=()=>!!this._getConnectionID(),this.setMessageComposerSetupFunction=e=>{this._messageComposerSetupState.partialNext({setupFunction:e})},this.connectUser=async(e,t)=>{if(!e.id)throw Error('The "id" field on the user is missing');if(this.userID===e.id&&this.setUserPromise)return console.warn("Consecutive calls to connectUser is detected, ideally you should only call this function once in your app."),this.setUserPromise;if(this.userID)throw Error("Use client.disconnect() before trying to connect as a different user. connectUser was called twice.");(this._isUsingServerAuth()||this.node)&&!this.options.allowServerSideConnect&&console.warn('Please do not use connectUser server side. connectUser impacts MAU and concurrent connection usage and thus your bill. If you have a valid use-case, add "allowServerSideConnect: true" to the client options to disable this warning.'),this.userID=e.id,this.anonymous=!1;let s=this._setToken(e,t);this._setUser(e);let i=this.openConnection();this.setUserPromise=Promise.all([s,i]).then(e=>e[1]);try{return await this.setUserPromise}catch(e){throw this.persistUserOnConnectionFailure?this.closeConnection():this.disconnectUser(),e}},this.setUser=this.connectUser,this._setToken=(e,t)=>this.tokenManager.setTokenOrProvider(t,e),this.closeConnection=async e=>(null!=this.cleaningIntervalRef&&(clearInterval(this.cleaningIntervalRef),this.cleaningIntervalRef=void 0),await Promise.all([this.wsConnection?.disconnect(e),this.wsFallback?.disconnect(e)]),this.offlineDb?.executeQuerySafely(async e=>{this.userID&&await e.upsertUserSyncStatus({userId:this.userID,lastSyncedAt:new Date().toString()})},{method:"upsertUserSyncStatus"}),Promise.resolve()),this.createChannelManager=({eventHandlerOverrides:e={},options:t={},queryChannelsOverride:s})=>new rf({client:this,eventHandlerOverrides:e,options:t,queryChannelsOverride:s}),this.openConnection=()=>{if(!this.userID)throw Error("User is not set on client, use client.connectUser or client.connectAnonymousUser instead");return this.wsConnection?.isConnecting&&this.wsPromise?(this.logger("info","client:openConnection() - connection already in progress",{tags:["connection","client"]}),this.wsPromise):(this.wsConnection?.isHealthy||this.wsFallback?.isHealthy())&&this._hasConnectionID()?void this.logger("info","client:openConnection() - openConnection called twice, healthy connection already exists",{tags:["connection","client"]}):(this.clientID=`${this.userID}--${iz()}`,this.wsPromise=this.connect(),this._startCleaning(),this.wsPromise)},this._setupConnection=this.openConnection,this._normalizeDate=e=>{if(e instanceof Date&&(e=e.toISOString()),""===e)throw Error("Don't pass blank string for since, use null instead if resetting the token revoke");return e},this.disconnectUser=e=>{this.logger("info","client:disconnect() - Disconnecting the client",{tags:["connection","client"]}),delete this.user,delete this._user,delete this.userID,this.anonymous=!1;let t=this.closeConnection(e);for(let e of Object.values(this.activeChannels))e._disconnect();return this.activeChannels={},this.state=new n2({client:this}),this.threads.resetState(),t.finally(()=>{this.tokenManager.reset()}).catch(e=>console.error(e)),t},this.disconnect=this.disconnectUser,this.connectAnonymousUser=()=>{(this._isUsingServerAuth()||this.node)&&!this.options.allowServerSideConnect&&console.warn('Please do not use connectUser server side. connectUser impacts MAU and concurrent connection usage and thus your bill. If you have a valid use-case, add "allowServerSideConnect: true" to the client options to disable this warning.'),this.anonymous=!0,this.userID=iz();
1let e={id:this.userID,anon:!0};return this._setToken(e,""),this._setUser(e),this._setupConnection()},this.setAnonymousUser=this.connectAnonymousUser,this.doAxiosRequest=async(e,t,s,i={})=>{await this.tokenManager.tokenReady();let a=this._enrichAxiosOptions(i);try{let i;switch(this._logApiRequest(e,t,s,a),e){case"get":i=await this.axiosInstance.get(t,a);break;case"delete":i=await this.axiosInstance.delete(t,a);break;case"post":i=await this.axiosInstance.post(t,s,a);break;case"postForm":i=await this.axiosInstance.postForm(t,s,a);break;case"put":i=await this.axiosInstance.put(t,s,a);break;case"patch":i=await this.axiosInstance.patch(t,s,a);break;case"options":i=await this.axiosInstance.options(t,a);break;default:throw Error("Invalid request type")}return this._logApiResponse(e,t,i),this.consecutiveFailures=0,this.handleResponse(i)}catch(n){if(n.client_request_id=a.headers?.["x-client-request-id"],this._logApiError(e,t,n),this.consecutiveFailures+=1,n.response){if(40===n.response.data.code&&!this.tokenManager.isStatic())return this.consecutiveFailures>1&&await iB(iW(this.consecutiveFailures)),this.tokenManager.loadToken(),await this.doAxiosRequest(e,t,s,i);return this.handleResponse(n.response)}throw n}},this.dispatchEvent=e=>{e.received_at||(e.received_at=new Date);let t=this._handleClientEvent(e),s=e.cid,i=s?this.activeChannels[s]:void 0;i&&i._handleChannelEvent(e),this._callClientListeners(e),i&&i._callChannelListeners(e),t.forEach(e=>e()),this.offlineDb?.executeQuerySafely(t=>t.handleEvent({event:e}),{method:`handleEvent;${e.type}`})},this.handleEvent=e=>{let t=JSON.parse(e.data);this.dispatchEvent(t)},this._updateMemberWatcherReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let t=this.activeChannels[s];t?.state&&(t.state.members[e.id]&&(t.state.members[e.id].user=e),t.state.watchers[e.id]&&(t.state.watchers[e.id]=e),t.state.read[e.id]&&(t.state.read[e.id].user=e))}},this._updateUserReferences=this._updateMemberWatcherReferences,this._updateUserMessageReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let t=this.activeChannels[s];if(!t)continue;let i=t.state;i?.updateUserMessages(e)}},this._deleteUserMessageReference=(e,t=!1,s)=>{let i=this.state.userChannelReferences[e.id]||{};for(let a in i){let i=this.activeChannels[a];if(i){let a=i.state;a?.deleteUserMessages(e,t,s)}}},this._handleUserEvent=e=>{if(e.user){if("user.presence.changed"===e.type||"user.updated"===e.type){if(e.user.id===this.userID){let t={...this.user},s={...this._user};for(let i in this.user)i in e.user||({channel_mutes:!0,devices:!0,mutes:!0,total_unread_count:!0,unread_channels:!0,unread_count:!0,unread_threads:!0,invisible:!0,privacy_settings:!0,roles:!0,push_preferences:!0,total_unread_count_by_team:!0})[i]||(delete t[i],delete s[i]);for(let t in s)t in e.user&&(s[t]=e.user[t]);this._user=s,this.user={...t,...e.user}}this.state.updateUser(e.user),this._updateMemberWatcherReferences(e.user)}"user.updated"===e.type&&this._updateUserMessageReferences(e.user),"user.deleted"===e.type&&e.user.deleted_at&&(e.mark_messages_deleted||e.hard_delete)&&this._deleteUserMessageReference(e.user,e.hard_delete,e.user.deleted_at?new Date(e.user.deleted_at):null)}},this._callClientListeners=e=>{let t=[];for(let s of(this.listeners.all&&t.push(...this.listeners.all),this.listeners[e.type]&&t.push(...this.listeners[e.type]),t))s(e)},this.recoverState=async()=>{this.logger("info",`client:recoverState() - Start of recoverState with connectionID ${this._getConnectionID()}`,{tags:["connection"]});let e=Object.keys(this.activeChannels);e.length&&this.recoverStateOnReconnect&&(this.logger("info",`client:recoverState() - Start the querying of ${e.length} channels`,{tags:["connection","client"]}),await this.queryChannels({cid:{$in:e}},{last_message_at:-1},{limit:30}),this.logger("info","client:recoverState() - Querying channels finished",{tags:["connection","client"]})),this.dispatchEvent({type:"connection.recovered"}),this.wsPromise=Promise.resolve(),this.setUserPromise=Promise.resolve()},this.getChannelByMembers=(e,t)=>{let s=(t.members??[]).map(e=>"string"==typeof e?e:e.user_id??""),i=s.sort().join(","),a=i7(e,s);if(!a)throw Error("Please specify atleast one member when creating unique conversation");for(let t in this.activeChannels){let s=this.activeChannels[t];if(!s.disconnected&&(t===a||0===t.indexOf(`${e}:!members-`)&&Object.keys(s.state.members).sort().join(",")===i))return s}let n=new n1(this,e,void 0,t);return this._cacheEnabled()&&(this.activeChannels[a]=n),n},this.getChannelById=(e,t,s)=>{if("string"==typeof t&&~t.indexOf(":"))throw Error(`Invalid channel id ${t}, can't contain the : character`);let i=`${e}:${t}`;if(i in this.activeChannels&&this.activeChannels[i]&&!this.activeChannels[i].disconnected){let e=this.activeChannels[i];return Object.keys(s).length>0&&(e.data={...e.data,...s},e._data={...e._data,...s}),e}let a=new n1(this,e,t,s);return this._cacheEnabled()&&(this.activeChannels[a.cid]=a),a},this.updateUsers=this.upsertUsers,this.updateUser=this.upsertUser,this._unblockMessage=this.unblockMessage,this.markAllRead=this.markChannelsRead,this._isUsingServerAuth=()=>!!this.secret,this._cacheEnabled=()=>!this._isUsingServerAuth()||!this.options.disableCache,this._buildWSPayload=e=>JSON.stringify({user_id:this.userID,user_details:this._user,device:this.options.device,client_request_id:e}),this.key=e,this.listeners={},this.state=new n2({client:this}),this.mutedChannels=[],this.mutedUsers=[],this.blockedUsers=new ag({userIds:[]}),this.moderation=new rn(this),this.notifications=s?.notifications??new rb,t&&rx(t)&&(this.secret=t);const i=s||(t&&!rx(t)?t:{});this.browser=void 0!==i.browser?i.browser:"u">typeof window,this.node=!this.browser,this.options={timeout:3e3,withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,disableCache:!1,wsUrlParams:new URLSearchParams({}),...i},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new iO.default.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=tB.create(this.options),this.setBaseURL(this.options.baseURL||"https://chat.stream-io-api.com"),void 0!==u.default&&"env"in u.default&&u.default.env.STREAM_LOCAL_TEST_RUN&&this.setBaseURL("http://localhost:3030"),void 0!==u.default&&"env"in u.default&&u.default.env.STREAM_LOCAL_TEST_HOST&&this.setBaseURL("http://"+u.default.env.STREAM_LOCAL_TEST_HOST),this.wsConnection=null,this.wsPromise=null,this.setUserPromise=null,this.activeChannels={},this.configs={},this.anonymous=!1,this.persistUserOnConnectionFailure=this.options?.persistUserOnConnectionFailure,this.tokenManager=new rt(this.secret),this.consecutiveFailures=0,this.insightMetrics=new n3,this.defaultWSTimeoutWithFallback=6e3,this.defaultWSTimeout=15e3,this.axiosInstance.defaults.paramsSerializer
1=iG,this.logger=i$(i.logger)?i.logger:()=>null,this.recoverStateOnReconnect=this.options.recoverStateOnReconnect,this.threads=new ro({client:this}),this.polls=new ru({client:this}),this.reminders=new rI({client:this}),this.messageDeliveryReporter=new nQ({client:this})}static getInstance(t,s,i){return e._instance||("string"==typeof s?e._instance=new e(t,s,i):e._instance=new e(t,s)),e._instance}setOfflineDBApi(e){this.offlineDb||(this.offlineDb=e)}devToken(e){let t;return["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",(t=JSON.stringify({user_id:e}),(0,H.fromByteArray)(new Uint8Array(function(e,t){let s=[];if(iD(e)&&t&&iD(e)){for(let i=0,a=e.length;i<a;i++)if(e.charAt(i)){let a=t(e.charAt(i),i,e);s[i]=a}}else if(!iD(e)&&!(t&&iD(e))){for(let i=0,a=e.length;i<a;i++)if(i in e){let a=t(e[i],i,e);s[i]=a}}return s}(t,e=>e.charCodeAt(0))))),"devtoken"].join(".")}getAuthType(){return this.anonymous?"anonymous":"jwt"}setBaseURL(e){this.baseURL=e,this.wsBaseURL=this.baseURL.replace("http","ws").replace(":3030",":8800")}_setUser(e){this.user=e,this.userID=e.id,this._user={...e}}async updateAppSettings(e){let t=e.apn_config;return t?.p12_cert&&(e={...e,apn_config:{...t,p12_cert:W.Buffer.from(t.p12_cert).toString("base64")}}),await this.patch(this.baseURL+"/app",e)}async revokeTokens(e){return await this.updateAppSettings({revoke_tokens_issued_before:this._normalizeDate(e)})}async revokeUserToken(e,t){return await this.revokeUsersToken([e],t)}async revokeUsersToken(e,t){t=void 0===t?new Date().toISOString():this._normalizeDate(t);let s=[];for(let i of e)s.push({id:i,set:{revoke_tokens_issued_before:t}});return await this.partialUpdateUsers(s)}async getAppSettings(){return this.appSettingsPromise=this.get(this.baseURL+"/app"),await this.appSettingsPromise}async testPushSettings(e,t={}){return await this.post(this.baseURL+"/check_push",{user_id:e,...t.messageID?{message_id:t.messageID}:{},...t.apnTemplate?{apn_template:t.apnTemplate}:{},...t.firebaseTemplate?{firebase_template:t.firebaseTemplate}:{},...t.firebaseDataTemplate?{firebase_data_template:t.firebaseDataTemplate}:{},...t.skipDevices?{skip_devices:!0}:{},...t.pushProviderName?{push_provider_name:t.pushProviderName}:{},...t.pushProviderType?{push_provider_type:t.pushProviderType}:{}})}async testSQSSettings(e={}){return await this.post(this.baseURL+"/check_sqs",e)}async testSNSSettings(e={}){return await this.post(this.baseURL+"/check_sns",e)}async setGuestUser(e){let t;this.anonymous=!0;try{t=await this.post(this.baseURL+"/guest",{user:e})}catch(e){throw this.anonymous=!1,e}this.anonymous=!1;let{created_at:s,updated_at:i,last_active:a,online:n,...r}=t.user;return await this.connectUser(r,t.access_token)}createToken(e,t,s){if(null==this.secret)throw Error("tokens can only be created server-side using the API Secret");let i={};return t&&(i.exp=t),s&&(i.iat=s),n9(this.secret,e,i,{})}on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Attaching listener for ${s} event`,{tags:["event","client"]}),this.listeners[s].push(i),{unsubscribe:()=>{this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(e=>e!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(e=>e!==i)}_logApiRequest(e,t,s,i){this.logger("info",`client: ${e} - Request - ${t}`,{tags:["api","api_request","client"],url:t,payload:s,config:i})}_logApiResponse(e,t,s){this.logger("info",`client:${e} - Response - url: ${t} > status ${s.status}`,{tags:["api","api_response","client"],url:t,response:s})}_logApiError(e,t,s){this.logger("error",`client:${e} - Error - url: ${t}`,{tags:["api","api_response","client"],url:t,error:s})}get(e,t){return this.doAxiosRequest("get",e,null,{params:t})}put(e,t){return this.doAxiosRequest("put",e,t)}post(e,t){return this.doAxiosRequest("post",e,t)}patch(e,t){return this.doAxiosRequest("patch",e,t)}delete(e,t){return this.doAxiosRequest("delete",e,null,{params:t})}sendFile(e,t,s,i,a){let n=function(e,t,s){let i=new t$.default;return null!==e&&"object"==typeof e&&(e.readable||"function"==typeof e._read)||null!=e&&null!=e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)||"u">typeof window&&"File"in window&&e instanceof File||"u">typeof window&&"Blob"in window&&e instanceof Blob?t?i.append("file",e,t):i.append("file",e):i.append("file",{uri:e,name:t||e.split("/").reverse()[0],contentType:s||void 0,type:s||void 0}),i}(t,s,i||"multipart/form-data");return null!=a&&n.append("user",JSON.stringify(a)),this.doAxiosRequest("postForm",e,n,{headers:n.getHeaders?n.getHeaders():{},config:{timeout:0,maxContentLength:1/0,maxBodyLength:1/0}})}errorFromResponse(e){return new a9(void 0!==e.data.code?`StreamChat error code ${e.data.code}: ${e.data.message}`:`StreamChat error HTTP code: ${e.status}`,{code:e.data.code??null,response:e,status:e.status})}handleResponse(e){let t=e.data;if(!e.status||e.status<200||300<=e.status)throw this.errorFromResponse(e);return t}_handleClientEvent(e){let t=[];if(this.logger("info",`client:_handleClientEvent - Received event of type { ${e.type} }`,{tags:["event","client"],event:e}),("user.presence.changed"===e.type||"user.updated"===e.type||"user.deleted"===e.type)&&this._handleUserEvent(e),"user.messages.deleted"===e.type&&!e.cid&&e.user&&this._deleteUserMessageReference(e.user,e.hard_delete,e.created_at?new Date(e.created_at):null),"health.check"===e.type&&e.me&&(this.user=e.me,this.state.updateUser(e.me),this.mutedChannels=e.me.channel_mutes,this.mutedUsers=e.me.mutes,this.blockedUsers.partialNext({userIds:e.me.blocked_user_ids??[]})),e.channel&&"notification.message_new"===e.type){let{channel:t}=e;this._addChannelConfig(t)}if("notification.channel_mutes_updated"===e.type&&e.me?.channel_mutes&&(this.mutedChannels=e.me.channel_mutes),"notification.mutes_updated"===e.type&&e.me?.mutes&&(this.mutedUsers=e.me.mutes),"notification.mark_read"===e.type&&0===e.unread_channels&&Object.keys(this.activeChannels).forEac
1h(e=>this.activeChannels[e].state.unreadCount=0),("channel.deleted"===e.type||"notification.channel_deleted"===e.type)&&e.cid){let{cid:s}=e;this.state.deleteAllChannelReference(s),this.activeChannels[e.cid]?._disconnect(),t.push(()=>{s&&delete this.activeChannels[s]})}return t}_muteStatus(e){let t;for(let s=0;s<this.mutedChannels.length;s++){let i=this.mutedChannels[s];if(i.channel?.cid===e){t={muted:!i.expires||new Date(i.expires).getTime()>new Date().getTime(),createdAt:i.created_at?new Date(i.created_at):new Date,expiresAt:i.expires?new Date(i.expires):null};break}}return t||{muted:!1,createdAt:null,expiresAt:null}}async connect(){if(!this.userID||!this._user)throw Error("Call connectUser or connectAnonymousUser before starting the connection");if(!this.wsBaseURL)throw Error("Websocket base url not set");if(!this.clientID)throw Error("clientID is not set");!this.wsConnection&&(this.options.warmUp||this.options.enableInsights)&&this._sayHi(),this.options.wsConnection&&this.node?(this.options.wsConnection.setClient(this),this.wsConnection=this.options.wsConnection):this.wsConnection=new n6({client:this});try{if(this.wsFallback)return await this.wsFallback.connect();return await this.wsConnection.connect(this.options.enableWSFallback?this.defaultWSTimeoutWithFallback:this.defaultWSTimeout)}catch(t){let e;if(this.options.enableWSFallback&&function(e){if("boolean"==typeof e.isWSFailure)return e.isWSFailure;try{return JSON.parse(e.message).isWSFailure}catch(e){return!1}}(t)&&((e="u">typeof navigator?navigator:"u">typeof window&&window.navigator?window.navigator:void 0)?"boolean"!=typeof e.onLine||e.onLine:(console.warn("isOnline failed to access window.navigator and assume browser is online"),!0)))return this.logger("info","client:connect() - WS failed, fallback to longpoll",{tags:["connection","client"]}),this.dispatchEvent({type:"transport.changed",mode:"longpoll"}),this.wsConnection._destroyCurrentWSConnection(),this.wsConnection.disconnect().then(),this.wsFallback=new rs({client:this}),await this.wsFallback.connect();throw t}}_sayHi(){let e=iz();this.doAxiosRequest("get",this.baseURL+"/hi",null,{headers:{"x-client-request-id":e}}).catch(t=>{this.options.enableInsights&&n4("http_hi_failed",{api_key:this.key,err:t,client_request_id:e})})}async queryUsers(e,t=[],s={}){let i={presence:!1};await this.wsPromise,this._hasConnectionID()||(i.presence=!1);let a=await this.get(this.baseURL+"/users",{payload:{filter_conditions:e,sort:iV(t),...i,...s}});return this.state.updateUsers(a.users),a}async queryBannedUsers(e={},t=[],s={}){return await this.get(this.baseURL+"/query_banned_users",{payload:{filter_conditions:e,sort:iV(t),...s}})}async queryFutureChannelBans(e={}){return await this.get(this.baseURL+"/query_future_channel_bans",{payload:e})}async queryMessageFlags(e={},t={}){return await this.get(this.baseURL+"/moderation/flags/message",{payload:{filter_conditions:e,...t}})}async queryChannelsRequest(e,t=[],s={}){let i={state:!0,watch:!0,presence:!1};await this.wsPromise,this._hasConnectionID()||(i.watch=!1);let{predefined_filter:a,filter_values:n,sort_values:r,...o}=s,l=a?{predefined_filter:a,filter_values:n,sort_values:r,...i,...o}:{filter_conditions:e,sort:iV(t),...i,...o};return(await this.post(this.baseURL+"/channels",l)).channels}async queryChannels(e,t=[],s={},i={}){let a=await this.queryChannelsRequest(e,t,s);return this.dispatchEvent({type:"channels.queried",queriedChannels:{channels:a,isLatestMessageSet:!0}}),a?.length&&this.offlineDb?.upsertChannels&&await this.offlineDb.upsertChannels({channels:a,isLatestMessagesSet:!0}),this.hydrateActiveChannels(a,i,s)}async queryReactions(e,t,s=[],i={}){let a={filter:t,sort:iV(s),...i};if(this.offlineDb?.getReactions&&!i.next)try{let a=await this.offlineDb.getReactions({messageId:e,filters:t,sort:s,limit:i.limit});a&&this.dispatchEvent({type:"offline_reactions.queried",offlineReactions:a})}catch(e){this.logger("warn","An error has occurred while querying offline reactions",{error:e})}return await this.wsPromise,await this.post(this.baseURL+"/messages/"+encodeURIComponent(e)+"/reactions",a)}hydrateActiveChannels(e=[],t={},s){let{skipInitialization:i,offlineMode:a=!1}=t,n=[];for(let t of e){let e;this._addChannelConfig(t.channel);
1let r=this.channel(t.channel.type,t.channel.id);if(r.data=t.channel,r.offlineMode=a,r.initialized=!a,r.push_preferences=t.push_preferences,void 0===i){let{messageSet:s}=r._initializeState(t,"latest");e=s}else if(!i.includes(t.channel.id)){r.state.clearMessages();let{messageSet:s}=r._initializeState(t,"latest");e=s}e&&(e.pagination={...e.pagination,...i5({parentSet:e,requestedPageSize:s?.message_limit||25,returnedPage:t.messages,logger:this.logger})},this.polls.hydratePollCache(t.messages,!0),this.reminders.hydrateState(t.messages)),r.messageComposer.initStateFromChannelResponse(t),r.cooldownTimer.refresh(),n.push(r)}return this.syncDeliveredCandidates(n),n}async search(e,t,s={}){if(s.offset&&s.next)throw Error("Cannot specify offset with next");let i={filter_conditions:e,...s,sort:s.sort?iV(s.sort):void 0};if("string"==typeof t)i.query=t;else if("object"==typeof t)i.message_filter_conditions=t;else throw Error(`Invalid type ${typeof t} for query parameter`);return await this.wsPromise,await this.get(this.baseURL+"/search",{payload:i})}setLocalDevice(e){if(this.wsConnection?.isConnecting&&this.wsPromise||(this.wsConnection?.isHealthy||this.wsFallback?.isHealthy())&&this._hasConnectionID())throw Error("you can only set device before opening a websocket connection");this.options.device=e}async addDevice(e,t,s,i){return await this.post(this.baseURL+"/devices",{id:e,push_provider:t,...null!=s?{user_id:s}:{},...null!=i?{push_provider_name:i}:{}})}async getDevices(e){return await this.get(this.baseURL+"/devices",e?{user_id:e}:{})}async getUnreadCount(e){return await this.get(this.baseURL+"/unread",e?{user_id:e}:{})}async getUnreadCountBatch(e){return await this.post(this.baseURL+"/unread_batch",{user_ids:e})}async setPushPreferences(e){return await this.post(this.baseURL+"/push_preferences",{preferences:e})}async removeDevice(e,t){return await this.delete(this.baseURL+"/devices",{id:e,...t?{user_id:t}:{}})}getRateLimits(e){let{serverSide:t,web:s,android:i,ios:a,endpoints:n}=e||{};return this.get(this.baseURL+"/rate_limits",{server_side:t,web:s,android:i,ios:a,endpoints:n?n.join(","):void 0})}async getHookEvents(e){let t=e&&e.length>0?{product:e.join(",")}:{};return await this.get(this.baseURL+"/hook/events",t)}_addChannelConfig({cid:e,config:t}){this._cacheEnabled()&&(this.configs[e]=t)}channel(e,t,s={}){if(!this.userID&&!this._isUsingServerAuth())throw Error("Call connectUser or connectAnonymousUser before creating a channel");if(~e.indexOf(":"))throw Error(`Invalid channel group ${e}, can't contain the : character`);return t&&"object"==typeof t?this.getChannelByMembers(e,t):!t&&"object"==typeof s&&s.members?.length?this.getChannelByMembers(e,s):t?this.getChannelById(e,t,s):new n1(this,e,void 0,s)}async partialUpdateUser(e){return await this.partialUpdateUsers([e])}async upsertUsers(e){let t={};for(let s of e){if(!s.id)throw Error("User ID is required when updating a user");t[s.id]=s}return await this.post(this.baseURL+"/users",{users:t})}upsertUser(e){return this.upsertUsers([e])}async partialUpdateUsers(e){for(let t of e)if(!t.id)throw Error("User ID is required when updating a user");return await this.patch(this.baseURL+"/users",{users:e})}async deleteUser(e,t){return await this.delete(this.baseURL+`/users/${encodeURIComponent(e)}`,t)}async restoreUsers(e){return await this.post(this.baseURL+"/users/restore",{user_ids:e})}async reactivateUser(e,t){return await this.post(this.baseURL+`/users/${encodeURIComponent(e)}/reactivate`,{...t})}async reactivateUsers(e,t){return await this.post(this.baseURL+"/users/reactivate",{user_ids:e,...t})}async deactivateUser(e,t){return await this.post(this.baseURL+`/users/${encodeURIComponent(e)}/deactivate`,{...t})}async deactivateUsers(e,t){return await this.post(this.baseURL+"/users/deactivate",{user_ids:e,...t})}async exportUser(e,t){return await this.get(this.baseURL+`/users/${encodeURIComponent(e)}/export`,{...t})}async banUser(e,t){return await this.post(this.baseURL+"/moderation/ban",{target_user_id:e,...t})}async unbanUser(e,t){return await this.delete(this.baseURL+"/moderation/ban",{target_user_id:e,...t})}async shadowBan(e,t){return await this.banUser(e,{shadow:!0,...t})}async removeShadowBan(e,t){return await this.unbanUser(e,{shadow:!0,...t})}async blockUser(e,t){let s=await this.post(this.baseURL+"/users/block",{blocked_user_id:e,...t?{user_id:t}:{}});return this._cacheEnabled()&&this.blockedUsers.next(({userIds:t})=>({userIds:t.concat(e)})),s}async getBlockedUsers(e){let t=await this.get(this.baseURL+"/users/block",{...e?{user_id:e}:{}});return this._cacheEnabled()&&this.blockedUsers.partialNext({userIds:t.blocks.map(({blocked_user_id:e})=>e)}
1),t}async unBlockUser(e,t){let s=await this.post(this.baseURL+"/users/unblock",{blocked_user_id:e,...t?{user_id:t}:{}});return this._cacheEnabled()&&this.blockedUsers.next(({userIds:t})=>({userIds:t.filter(t=>t!==e)})),s}async getSharedLocations(){return await this.get(this.baseURL+"/users/live_locations")}async muteUser(e,t,s={}){return await this.post(this.baseURL+"/moderation/mute",{target_id:e,...t?{user_id:t}:{},...s})}async unmuteUser(e,t){return await this.post(this.baseURL+"/moderation/unmute",{target_id:e,...t?{user_id:t}:{}})}userMuteStatus(e){if(!this.user||!this.wsPromise)throw Error("Make sure to await connectUser() first.");for(let t=0;t<this.mutedUsers.length;t+=1)if(this.mutedUsers[t].target.id===e)return!0;return!1}async flagMessage(e,t={}){return await this.post(this.baseURL+"/moderation/flag",{target_message_id:e,...t})}async flagUser(e,t={}){return await this.post(this.baseURL+"/moderation/flag",{target_user_id:e,...t})}async unflagMessage(e,t={}){return await this.post(this.baseURL+"/moderation/unflag",{target_message_id:e,...t})}async unflagUser(e,t={}){return await this.post(this.baseURL+"/moderation/unflag",{target_user_id:e,...t})}async _queryFlags(e={},t={}){return await this.post(this.baseURL+"/moderation/flags",{filter_conditions:e,...t})}async _queryFlagReports(e={},t={}){return await this.post(this.baseURL+"/moderation/reports",{filter_conditions:e,...t})}async _reviewFlagReport(e,t,s={}){return await this.patch(this.baseURL+`/moderation/reports/${encodeURIComponent(e)}`,{review_result:t,...s})}async unblockMessage(e,t={}){return await this.post(this.baseURL+"/moderation/unblock_message",{target_message_id:e,...t})}async markChannelsRead(e={}){await this.post(this.baseURL+"/channels/read",{...e})}createCommand(e){return this.post(this.baseURL+"/commands",e)}getCommand(e){return this.get(this.baseURL+`/commands/${encodeURIComponent(e)}`)}updateCommand(e,t){return this.put(this.baseURL+`/commands/${encodeURIComponent(e)}`,t)}deleteCommand(e){return this.delete(this.baseURL+`/commands/${encodeURIComponent(e)}`)}listCommands(){return this.get(this.baseURL+"/commands")}createChannelType(e){let t=Object.assign({},{commands:["all"]},e);return this.post(this.baseURL+"/channeltypes",t)}getChannelType(e){return this.get(this.baseURL+`/channeltypes/${encodeURIComponent(e)}`)}updateChannelType(e,t){return this.put(this.baseURL+`/channeltypes/${encodeURIComponent(e)}`,t)}deleteChannelType(e){return this.delete(this.baseURL+`/channeltypes/${encodeURIComponent(e)}`)}listChannelTypes(){return this.get(this.baseURL+"/channeltypes")}async translateMessage(e,t){return await this.post(this.baseURL+`/messages/${encodeURIComponent(e)}/translate`,{language:t})}async translate(e,t,s){return await this.post(this.baseURL+"/translate",{text:e,source_language:s,destination_language:t})}_normalizeExpiration(e){let t=null;if("number"==typeof e){let s=new Date;s.setSeconds(s.getSeconds()+e),t=s.toISOString()}else rx(e)?t=e:e instanceof Date&&(t=e.toISOString());return t}_validateAndGetMessageId(e,t){let s;if("string"==typeof e)s=e;else{if(!e.id)throw Error(t);s=e.id}return s}pinMessage(e,t,s,i){let a=this._validateAndGetMessageId(e,"Please specify the message id when calling unpinMessage");return this.partialUpdateMessage(a,{set:{pinned:!0,pin_expires:this._normalizeExpiration(t),pinned_at:this._normalizeExpiration(i)}},s)}unpinMessage(e,t){let s=this._validateAndGetMessageId(e,"Please specify the message id when calling unpinMessage");return this.partialUpdateMessage(s,{set:{pinned:!1}},t)}async updateMessage(e,t,s){if(!e.id)throw Error("Please specify the message.id when calling updateMessage");let i=iX(e);return"string"==typeof t?i.user_id=t:"string"==typeof t?.id&&(i.user_id=t.id),await this.post(this.baseURL+`/messages/${encodeURIComponent(e.id)}`,{message:i,...s})}async partialUpdateMessage(e,t,s,i){let a;if(!e)throw Error("Please specify the message.id when calling partialUpdateMessage");return"string"==typeof s?a={id:s}:"string"==typeof s?.id&&(a={id:s.id}),await this.put(this.baseURL+`/messages/${encodeURIComponent(e)}`,{...t,...i,user:a})}async ephemeralUpdateMessage(e,t,s,i){let a;if(!e)throw Error("messageId is required");return"string"==typeof s?a={id:s}:"string"==typeof s?.id&&(a={id:s.id}),await this.patch(`${this.baseURL}
1/messages/${encodeURIComponent(e)}/ephemeral`,{...t,...i,user:a})}async deleteMessage(e,t){let s={};"boolean"==typeof t?s=t?{hardDelete:!0}:{}:t?.deleteForMe?s={deleteForMe:!0}:t?.hardDelete&&(s={hardDelete:!0});try{if(this.offlineDb)return s.hardDelete?await this.offlineDb.hardDeleteMessage({id:e}):await this.offlineDb.softDeleteMessage({id:e,deleteForMe:s.deleteForMe}),await this.offlineDb.queueTask({task:{messageId:e,payload:[e,s],type:"delete-message"}})}catch(e){this.logger("error","offlineDb:deleteMessage",{tags:["channel","offlineDb"],error:e})}return this._deleteMessage(e,s)}async _deleteMessage(e,t){let{deleteForMe:s,hardDelete:i}="boolean"==typeof t?{hardDelete:t}:t??{},a={};i&&(a={hard:!0}),s&&(a={...a,delete_for_me:!0});let n=await this.delete(this.baseURL+`/messages/${encodeURIComponent(e)}`,a);return s&&(n.message.deleted_for_me=!0,n.message.type="deleted"),n}async undeleteMessage(e,t){return await this.post(this.baseURL+`/messages/${encodeURIComponent(e)}/undelete`,{undeleted_by:t})}async getMessage(e,t){return await this.get(this.baseURL+`/messages/${encodeURIComponent(e)}`,{...t})}async queryThreads(e={}){let t={limit:10,participant_limit:10,reply_limit:3,watch:!0,...e},s={...t};t.filter&&Object.keys(t.filter).length>0&&(s.filter=t.filter),t.sort&&(Array.isArray(t.sort)?t.sort.length>0:Object.keys(t.sort).length>0)&&(s.sort=iV(t.sort));let i=await this.post(`${this.baseURL}/threads`,s),a=i.threads.map(e=>e.parent_message);return this.polls.hydratePollCache(a),{threads:i.threads.map(e=>new nq({client:this,threadData:e})),next:i.next}}async getThread(e,t={}){if(!e)throw Error("Please specify the messageId when calling getThread");let s={participant_limit:100,reply_limit:3,watch:!0,...t};return new nq({client:this,threadData:(await this.get(`${this.baseURL}/threads/${encodeURIComponent(e)}`,s)).thread})}async partialUpdateThread(e,t){if(!e)throw Error("Please specify the message id when calling partialUpdateThread");let s=["created_at","id","last_message_at","type","updated_at","user","reply_count","participants","channel","custom"];for(let e in{...t.set,...t.unset})if(s.includes(e))throw Error(`You cannot set ${e} field on Thread object. ${e} is reserved for server-side use. Please omit ${e} from your set object.`);return await this.patch(`${this.baseURL}/threads/${encodeURIComponent(e)}`,t)}getUserAgent(){if(this.userAgent)return this.userAgent;let e="9.38.0",t="";t=this.sdkIdentifier?`stream-chat-${this.sdkIdentifier.name}-v${this.sdkIdentifier.version}-llc-v${e}`:`stream-chat-js-v${e}-${this.node?"node":"browser"}`;let{os:s,model:i}=this.deviceIdentifier??{};return[["os",s],["device_model",i],["client_bundle","browser-esm"]].reduce((e,[t,s])=>s&&s.length>0?e.concat(`|${t}=${s}`):e,t)}setUserAgent(e){this.userAgent=e}_enrichAxiosOptions(e={params:{},headers:{},config:{}}){let t=this._getToken(),s=null;null!==this.nextRequestAbortController&&(s=this.nextRequestAbortController.signal,this.nextRequestAbortController=null),e.headers?.["x-client-request-id"]||(e.headers={...e.headers,"x-client-request-id":iz()});let{params:i,headers:a,...n}=this.options.axiosRequestConfig||{};return{params:{user_id:this.userID,connection_id:this._getConnectionID(),api_key:this.key,...e.params,...i||{}},headers:{...t?{Authorization:t}:void 0,"stream-auth-type":this.getAuthType(),"X-Stream-Client":this.getUserAgent(),...e.headers,...a||{}},...s?{signal:s}:{},...e.config,...n||{}}}_getToken(){return!this.tokenManager||this.anonymous?null:this.tokenManager.getToken()}_startCleaning(){let e=this;null==this.cleaningIntervalRef&&(this.cleaningIntervalRef=setInterval(()=>{for(let t of Object.values(e.activeChannels))t.clean()},500))}verifyWebhook(e,t){return!!this.secret&&function(e,t,s){let i=W.Buffer.from(t,"utf8"),a=n7.default.createHmac("sha256",i).update(e).digest("hex");try{return n7.default.timingSafeEqual(W.Buffer.from(a),W.Buffer.from(s))}catch{return!1}}(e,this.secret,t)}getPermission(e){return this.get(`${this.baseURL}/permissions/${encodeURIComponent(e)}`)}createPermission(e){return this.post(`${this.baseURL}/permissions`,{...e})}updatePermission(e,t){return this.put(`${this.baseURL}
1/permissions/${encodeURIComponent(e)}`,{...t})}deletePermission(e){return this.delete(`${this.baseURL}/permissions/${encodeURIComponent(e)}`)}listPermissions(){return this.get(`${this.baseURL}/permissions`)}createRole(e){return this.post(`${this.baseURL}/roles`,{name:e})}listRoles(){return this.get(`${this.baseURL}/roles`)}deleteRole(e){return this.delete(`${this.baseURL}/roles/${encodeURIComponent(e)}`)}sync(e,t,s={}){return this.post(`${this.baseURL}/sync`,{channel_cids:e,last_sync_at:t,...s})}async sendUserCustomEvent(e,t){return await this.post(`${this.baseURL}/users/${encodeURIComponent(e)}/event`,{event:t})}createBlockList(e){return this.post(`${this.baseURL}/blocklists`,e)}listBlockLists(e){return this.get(`${this.baseURL}/blocklists`,e)}getBlockList(e,t){return this.get(`${this.baseURL}/blocklists/${encodeURIComponent(e)}`,t)}updateBlockList(e,t){return this.put(`${this.baseURL}/blocklists/${encodeURIComponent(e)}`,t)}deleteBlockList(e,t){return this.delete(`${this.baseURL}/blocklists/${encodeURIComponent(e)}`,t)}exportChannels(e,t={}){let s={channels:e,...t};return this.post(`${this.baseURL}/export_channels`,s)}exportUsers(e){return this.post(`${this.baseURL}/export/users`,e)}exportChannel(e,t){return this.exportChannels([e],t)}getExportChannelStatus(e){return this.get(`${this.baseURL}/export_channels/${encodeURIComponent(e)}`)}campaign(e,t){return e&&"object"==typeof e?new iT(this,null,e):new iT(this,e,t)}channelBatchUpdater(){return new iP(this)}segment(e,t,s){return"string"==typeof t?new ri(this,e,t,s):new ri(this,e,null,t)}validateServerSideAuth(){if(!this.secret)throw Error("This feature can be used server-side only. Please initialize the client with a secret to use this feature.")}createSegment(e,t,s){this.validateServerSideAuth();let i={id:t,type:e,...s};return this.post(this.baseURL+"/segments",i)}createUserSegment(e,t){return this.validateServerSideAuth(),this.createSegment("user",e,t)}createChannelSegment(e,t){return this.validateServerSideAuth(),this.createSegment("channel",e,t)}getSegment(e){return this.validateServerSideAuth(),this.get(this.baseURL+`/segments/${encodeURIComponent(e)}`)}updateSegment(e,t){return this.validateServerSideAuth(),this.put(this.baseURL+`/segments/${encodeURIComponent(e)}`,t)}addSegmentTargets(e,t){return this.validateServerSideAuth(),this.post(this.baseURL+`/segments/${encodeURIComponent(e)}/addtargets`,{target_ids:t})}querySegmentTargets(e,t={},s=[],i={}){return this.validateServerSideAuth(),this.post(this.baseURL+`/segments/${encodeURIComponent(e)}/targets/query`,{filter:t||{},sort:s||[],...i})}removeSegmentTargets(e,t){return this.validateServerSideAuth(),this.post(this.baseURL+`/segments/${encodeURIComponent(e)}/deletetargets`,{target_ids:t})}querySegments(e,t,s={}){return this.validateServerSideAuth(),this.post(this.baseURL+"/segments/query",{filter:e,sort:t,...s})}deleteSegment(e){return this.validateServerSideAuth(),this.delete(this.baseURL+`/segments/${encodeURIComponent(e)}`)}segmentTargetExists(e,t){return this.validateServerSideAuth(),this.get(this.baseURL+`/segments/${encodeURIComponent(e)}/target/${encodeURIComponent(t)}`)}createCampaign(e){return this.validateServerSideAuth(),this.post(this.baseURL+"/campaigns",{...e})}getCampaign(e,t){return this.validateServerSideAuth(),this.get(this.baseURL+`/campaigns/${encodeURIComponent(e)}`,{...t?.users})}startCampaign(e,t){return this.validateServerSideAuth(),this.post(this.baseURL+`/campaigns/${encodeURIComponent(e)}/start`,{scheduled_for:t?.scheduledFor,stop_at:t?.stopAt})}async queryCampaigns(e,t,s){return this.validateServerSideAuth(),await this.post(this.baseURL+"/campaigns/query",{filter:e,sort:t,...s||{}})}updateCampaign(e,t){return this.validateServerSideAuth(),this.put(this.baseURL+`/campaigns/${encodeURIComponent(e)}`,t)}deleteCampaign(e){return this.validateServerSideAuth(),this.delete(this.baseURL+`/campaigns/${encodeURIComponent(e)}`)}stopCampaign(e){return this.validateServerSideAuth(),this.post(this.baseURL+`/campaigns/${encodeURIComponent(e)}/stop`)}enrichURL(e){return this.get(this.baseURL+"/og",{url:e})}getTask(e){return this.get(`${this.baseURL}
1/tasks/${encodeURIComponent(e)}`)}async deleteChannels(e,t={}){return await this.post(this.baseURL+"/channels/delete",{cids:e,...t})}async deleteUsers(e,t={}){if(void 0!==t.user&&!["soft","hard","pruning"].includes(t.user))throw Error("Invalid delete user options. user must be one of [soft hard pruning]");if(void 0!==t.conversations&&!["soft","hard"].includes(t.conversations))throw Error("Invalid delete user options. conversations must be one of [soft hard]");if(void 0!==t.messages&&!["soft","hard","pruning"].includes(t.messages))throw Error("Invalid delete user options. messages must be one of [soft hard pruning]");return await this.post(this.baseURL+"/users/delete",{user_ids:e,...t})}async _createImportURL(e){return await this.post(this.baseURL+"/import_urls",{filename:e})}async _createImport(e,t={mode:"upsert"}){return await this.post(this.baseURL+"/imports",{path:e,...t})}async _getImport(e){return await this.get(this.baseURL+`/imports/${encodeURIComponent(e)}`)}async _listImports(e){return await this.get(this.baseURL+"/imports",e)}async upsertPushProvider(e){return await this.post(this.baseURL+"/push_providers",{push_provider:e})}async deletePushProvider({type:e,name:t}){return await this.delete(this.baseURL+`/push_providers/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async listPushProviders(){return await this.get(this.baseURL+"/push_providers")}createAbortControllerForNextRequest(){return this.nextRequestAbortController=new AbortController}async commitMessage(e){return await this.post(this.baseURL+`/messages/${encodeURIComponent(e)}/commit`)}async createPoll(e,t){return await this.post(this.baseURL+"/polls",{...e,...t?{user_id:t}:{}})}async getPoll(e,t){return await this.get(this.baseURL+`/polls/${encodeURIComponent(e)}`,t?{user_id:t}:{})}async updatePoll(e,t){return await this.put(this.baseURL+"/polls",{...e,...t?{user_id:t}:{}})}async partialUpdatePoll(e,t,s){return await this.patch(this.baseURL+`/polls/${encodeURIComponent(e)}`,{...t,...s?{user_id:s}:{}})}async deletePoll(e,t){return await this.delete(this.baseURL+`/polls/${encodeURIComponent(e)}`,{...t?{user_id:t}:{}})}closePoll(e,t){return this.partialUpdatePoll(e,{set:{is_closed:!0}},t)}async createPollOption(e,t,s){return await this.post(this.baseURL+`/polls/${encodeURIComponent(e)}/options`,{...t,...s?{user_id:s}:{}})}async getPollOption(e,t,s){return await this.get(this.baseURL+`/polls/${encodeURIComponent(e)}/options/${encodeURIComponent(t)}`,s?{user_id:s}:{})}async updatePollOption(e,t,s){return await this.put(this.baseURL+`/polls/${encodeURIComponent(e)}/options`,{...t,...s?{user_id:s}:{}})}async deletePollOption(e,t,s){return await this.delete(this.baseURL+`/polls/${encodeURIComponent(e)}/options/${encodeURIComponent(t)}`,s?{user_id:s}:{})}async castPollVote(e,t,s,i){return await this.post(this.baseURL+`/messages/${encodeURIComponent(e)}/polls/${encodeURIComponent(t)}/vote`,{vote:s,...i?{user_id:i}:{}})}addPollAnswer(e,t,s,i){return this.castPollVote(e,t,{answer_text:s},i)}async removePollVote(e,t,s,i){return await this.delete(this.baseURL+`/messages/${encodeURIComponent(e)}/polls/${encodeURIComponent(t)}/vote/${encodeURIComponent(s)}`,{...i?{user_id:i}:{}})}async queryPolls(e={},t=[],s={},i){let a=i?`?user_id=${i}`:"";return await this.post(this.baseURL+`/polls/query${a}`,{filter:e,sort:iV(t),...s})}async queryPollVotes(e,t={},s=[],i={},a){let n=a?`?user_id=${a}`:"";return await this.post(this.baseURL+`/polls/${encodeURIComponent(e)}/votes${n}`,{filter:t,sort:iV(s),...i})}async queryPollAnswers(e,t={},s=[],i={},a){let n=a?`?user_id=${a}`:"";return await this.post(this.baseURL+`/polls/${encodeURIComponent(e)}/votes${n}`,{filter:{...t,is_answer:!0},sort:iV(s),...i})}async queryMessageHistory(e={},t=[],s={}){return await this.post(this.baseURL+"/messages/history",{filter:e,sort:iV(t),...s})}async updateFlags(e,t,s={}){return await this.post(this.baseURL+"/automod/v1/moderation/update_flags",{message_ids:e,reviewed_by:t,...s})}async queryDrafts(e={}){let t={...e,sort:e.sort?iV(e.sort):void 0};return await this.post(this.baseURL+"/drafts/query",t)}async createReminder({messageId:e,...t}){return await this.post(`${this.baseURL}
1/messages/${e}/reminders`,t)}async updateReminder({messageId:e,...t}){return await this.patch(`${this.baseURL}/messages/${e}/reminders`,t)}async deleteReminder(e,t){return await this.delete(`${this.baseURL}/messages/${e}/reminders`,t?{user_id:t}:{})}async queryReminders({filter:e,sort:t,...s}={}){return await this.post(`${this.baseURL}/reminders/query`,{filter:e,sort:t&&iV(t),...s})}async queryTeamUsageStats(e={}){return await this.post(`${this.baseURL}/stats/team_usage`,e)}async updateLocation(e){return await this.put(this.baseURL+"/users/live_locations",e)}uploadFile(e,t,s,i){return this.sendFile(`${this.baseURL}/uploads/file`,e,t,s,i)}uploadImage(e,t,s,i){return this.sendFile(`${this.baseURL}/uploads/image`,e,t,s,i)}deleteFile(e){return this.delete(`${this.baseURL}/uploads/file`,{url:e})}deleteImage(e){return this.delete(`${this.baseURL}/uploads/image`,{url:e})}async markChannelsDelivered(e){if(e?.latest_delivered_messages?.length)return await this.post(this.baseURL+"/channels/delivered",e)}syncDeliveredCandidates(e){this.messageDeliveryReporter.syncDeliveredCandidates(e)}async updateChannelsBatch(e){return await this.put(this.baseURL+"/channels/batch",e)}async createPredefinedFilter(e){return this.validateServerSideAuth(),await this.post(`${this.baseURL}/predefined_filters`,e)}async getPredefinedFilter(e){return this.validateServerSideAuth(),await this.get(`${this.baseURL}/predefined_filters/${encodeURIComponent(e)}`)}async updatePredefinedFilter(e,t){return this.validateServerSideAuth(),await this.put(`${this.baseURL}/predefined_filters/${encodeURIComponent(e)}`,t)}async deletePredefinedFilter(e){return this.validateServerSideAuth(),await this.delete(`${this.baseURL}/predefined_filters/${encodeURIComponent(e)}`)}async listPredefinedFilters(e={}){this.validateServerSideAuth();let{sort:t,...s}=e;return await this.get(`${this.baseURL}/predefined_filters`,{...s,...t?{sort:JSON.stringify(t)}:{}})}},rM="Allow",rE=["*"],rA=["*"],rk=class{constructor(e,t,s=rE,i=rA,a=!1,n=rM){this.name=e,this.action=n,this.owner=a,this.priority=t,this.resources=s,this.roles=i}};new rk("Allow all",999,rE,rA,!1,rM),new rk("Deny all",1,rE,rA,!1,"Deny");var rD=e=>new Date(e.end_at).getTime()<Date.now();function rT(e){return!!e&&"deleted"!==e.type&&!!e.shared_location?.end_at&&!rD(e.shared_location)}var rP=class e extends af{constructor({client:e,getDeviceId:t,watchLocation:s}){if(!e.userID)throw Error("Live-location sharing is reserved for client-side use only");super(),this.registerSubscriptions=()=>{this.incrementRefCount(),this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeLiveLocationSharingUpdates()),this.addUnsubscribeFunction(this.subscribeTargetMessagesChange()))},this.unregisterSubscriptions=()=>super.unregisterSubscriptions(),this.client=e,this.state=new ag({messages:new Map,ready:!1}),this._deviceId=t(),this.getDeviceId=t,this.watchLocation=s}
1async init(){await this.assureStateInit(),this.registerSubscriptions()}get messages(){return this.state.getLatestValue().messages}get stateIsReady(){return this.state.getLatestValue().ready}get deviceId(){return this._deviceId||(this._deviceId=this.getDeviceId()),this._deviceId}async assureStateInit(){if(this.stateIsReady)return;let{active_live_locations:e}=await this.client.getSharedLocations();this.state.next({messages:new Map(e.filter(e=>!rD(e)).map(e=>[e.message_id,{...e,stopSharingTimeout:setTimeout(()=>{this.unregisterMessages([e.message_id])},new Date(e.end_at).getTime()-Date.now())}])),ready:!0})}subscribeTargetMessagesChange(){let e=null,t=this.state.subscribeWithSelector(({messages:e})=>({messages:e}),({messages:t})=>{t.size?t.size&&!e&&(e=this.subscribeWatchLocation()):(e?.(),e=null)});return()=>{t(),e?.()}}subscribeWatchLocation(){let t=Date.now();return this.watchLocation(({latitude:s,longitude:i})=>{Date.now()<t||(t=Date.now()+3e3,aD(e.symbol,async()=>{let e=[];await this.assureStateInit();let t=[];for(let[a,n]of this.messages){if(rD(n)){t.push(n.message_id);continue}if(n.latitude===s&&n.longitude===i)continue;let r=this.client.updateLocation({created_by_device_id:n.created_by_device_id,message_id:a,latitude:s,longitude:i});e.push(r)}this.unregisterMessages(t),e.length>0&&await Promise.allSettled(e)}))})}subscribeLiveLocationSharingUpdates(){let e=[...["live_location_sharing.started","message.updated","message.deleted"].map(e=>this.client.on(e,e=>{e.message&&("live_location_sharing.started"===e.type?this.registerMessage(e.message):"message.updated"===e.type?(this.messages.has(e.message.id)&&!rT(e.message)&&this.unregisterMessages([e.message.id]),this.registerMessage(e.message)):this.unregisterMessages([e.message.id]))})),this.client.on("live_location_sharing.stopped",e=>{e.live_location&&this.unregisterMessages([e.live_location?.message_id])})];return()=>e.forEach(e=>e.unsubscribe())}registerMessage(e){this.client.userID&&e?.user?.id===this.client.userID&&rT(e)&&this.state.next(t=>{let s=new Map(t.messages);return s.set(e.id,{...e.shared_location,stopSharingTimeout:setTimeout(()=>{this.unregisterMessages([e.id])},new Date(e.shared_location.end_at).getTime()-Date.now())}),{...t,messages:s}})}unregisterMessages(e){let t=this.messages,s=new Set(e),i=new Map(Array.from(t).filter(([e,t])=>(s.has(e)&&t.stopSharingTimeout&&(clearTimeout(t.stopSharingTimeout),t.stopSharingTimeout=null),!s.has(e))));i.size!==t.size&&this.state.partialNext({messages:i})}};rP.symbol=Symbol(rP.name);var rO=class{constructor(e,t){if(!e)throw Error("Size must be greater than 0");this.keys=[],this.size=e,this.map=new Map,this.dispose=t?.dispose??null}add(e,t){if(this.keys.indexOf(e)>-1)this.keys.splice(this.keys.indexOf(e),1);else if(this.keys.length>=this.size){let e=this.keys.shift();if(e){let t=this.peek(e);t&&this.dispose?.(e,t),this.map.delete(e)}}this.keys.push(e),this.map.set(e,t)}peek(e){return this.map.get(e)}get(e){let t=this.peek(e);return t&&this.keys.indexOf(e)!==this.size-1&&(this.keys.splice(this.keys.indexOf(e),1),this.keys.push(e)),t}};e.s(["ChannelSearchSource",0,n_,"FixedSizeQueueCache",0,rO,"LinkPreviewsManager",0,aX,"MessageComposer",0,nz,"MessageSearchSource",0,nw,"SearchController",0,ng,"StateStore",0,ag,"StreamChat",0,rL,"UserSearchSource",0,nb,"VotingVisibility",0,ne,"formatMessage",0,iY,"isAudioAttachment",0,aR,"isFileAttachment",0,av,"isImageAttachment",0,aC,"isLocalAttachment",0,aw,"isLocalAudioAttachment",0,e=>aR(e)&&aw(e),"isLocalFileAttachment",0,e=>av(e)&&aw(e),"isLocalImageAttachment",0,aS,"isLocalUploadAttachment",0,e=>!!e?.localMetadata?.uploadState,"isLocalVideoAttachment",0,e=>aI(e)&&aw(e),"isLocalVoiceRecordingAttachment",0,e=>aU(e)&&aw(e),"isScrapedContent",0,a_,"isSharedLocationResponse",0,e=>!!e.latitude&&!!e.longitude&&!!e.channel_cid,"isVideoAttachment",0,aI,"isVoiceRecordingAttachment",0,aU,"isVoteAnswer",0,rl,"localMessageToNewMessagePayload",0,e=>{let{created_at:t,updated_at:s,deleted_at:i,error:a,status:n,latest_reactions:r,own_reactions:o,reaction_counts:l,reaction_scores:d,reply_count:c,command:h,html:u,i18n:g,quoted_message:p,mentioned_users:m,...f}=e;return{...f,pinned_at:f.pinned_at?.toISOString(),mentioned_users:m?.map(e=>e.id)}}],28367);var rN=e.i(71645),rF=e.i(46696);let rq="gt9bznhd6exc",rj=(0,rN.createContext)(null);async function rB(e){let t=await fetch("https://owvlsbcdtsbwuvnncfqb.supabase.co/functions/v1/stream-token",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok)throw Error((await t.json().catch(()=>({}))).error||"Failed to fetch Stream token");let{token:s,streamUserId:i}=await t.json();return{token:s,streamUserId:i}}function r$(e){"granted"===(0,f.getNotificationPermissionState)()&&(0,f.registerWebPushSubscription)(e).catch(e=>{console.error("Web push registration failed",e)})}e.s(["StreamChatProvider",0,function({children:e}){let{user:t,session:s}=(0,p.useAuth)(),[i,a]=(0,rN.useState)(null),[n,r]=(0,rN.useState)(!1),[o,l]=(0,rN.useState)(null),[d,c]=(0,rN.useState)(null),[h,u]=(0,rN.useState)(null),y=(0,rN.useRef)(null),b=(0,rN.useRef)(!1),_=(0,rN.useCallback)(async()=>
1{if(rq&&t?.id&&s?.access_token&&!b.current){b.current=!0,l(null);try{let e=y.current??rL.getInstance(rq);y.current=e;let{token:i,streamUserId:n}=await rB(s.access_token);if(e.userID===n){u(n),a(e),r(!0),r$(n),S(t.id,{streamUserId:n,firebaseUid:V(t)});return}e.userID&&await e.disconnectUser();let{data:o}=await m.supabase.from("users").select("username, firstName, lastName, avatar").eq("id",t.id).maybeSingle(),l=o?.username||[o?.firstName,o?.lastName].filter(Boolean).join(" ")||t.email?.split("@")[0]||"User";await e.connectUser({id:n,name:l,image:o?.avatar??void 0},i),u(n),a(e),r(!0),r$(n),S(t.id,{streamUserId:n,firebaseUid:V(t)})}catch(e){console.error("Stream connection failed",e),r(!1),l(e instanceof Error?e.message:"Could not connect to chat")}finally{b.current=!1}}},[s?.access_token,t]),w=(0,rN.useCallback)(async()=>{(0,f.removeWebPushSubscription)().catch(e=>{console.error("Web push unsubscribe failed",e)}),y.current?.userID&&await y.current.disconnectUser(),a(null),r(!1),u(null)},[]);(0,rN.useEffect)(()=>{t?.id&&s?.access_token?_():w()},[_,w,s?.access_token,t?.id]),(0,rN.useEffect)(()=>{if(!i||!n)return;let e=i.on("message.new",e=>{if((0,f.shouldIgnoreNotificationEvent)(e,h??t?.id,d)||"visible"!==document.visibilityState)return;if("granted"===(0,f.getNotificationPermissionState)())return void(0,f.showNativeNotificationForEvent)(e).catch(t=>{console.error("Native notification failed",t);let s=(0,f.buildForegroundNotificationText)(e);s&&rF.toast.info(s.title,{description:s.description})});let s=(0,f.buildForegroundNotificationText)(e);s&&rF.toast.info(s.title,{description:s.description})});return()=>{e.unsubscribe()}},[d,i,n,h,t?.id]),(0,rN.useEffect)(()=>{if(h)return(0,f.listenForWebPushResubscribe)(h)},[h]),(0,rN.useEffect)(()=>()=>{y.current?.disconnectUser()},[]);let v=(0,rN.useMemo)(()=>({chatClient:i,isReady:n,connectionError:o,retryConnection:()=>{_()}
1,activeCid:d,setActiveCid:c,streamUserId:h}),[d,i,_,o,n,h]);return(0,g.jsx)(rj.Provider,{value:v,children:e})},"useStreamChat",0,function(){let e=(0,rN.useContext)(rj);if(!e)throw Error("useStreamChat must be used within StreamChatProvider");return e}],43270)}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.