@talkjs/core
Version:
Lets you connect to your TalkJS chat as a user and read, subscribe to, and update your chat data.
1 lines • 202 kB
JavaScript
"use strict";var e,t,s,n,r=Object.defineProperty,i=Object.defineProperties,a=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable,u=e=>{throw TypeError(e)},h=(e,t,s)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,d=(e,t)=>{for(var s in t||(t={}))l.call(t,s)&&h(e,s,t[s]);if(o)for(var s of o(t))c.call(t,s)&&h(e,s,t[s]);return e},p=(e,t)=>i(e,a(t)),f=(e,t)=>{var s={};for(var n in e)l.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&o)for(var n of o(e))t.indexOf(n)<0&&c.call(e,n)&&(s[n]=e[n]);return s},m=(e,t,s)=>t.has(e)||u("Cannot "+s),g=(e,t,s)=>(m(e,t,"read from private field"),s?s.call(e):t.get(e)),v=(e,t,s)=>t.has(e)?u("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),y=(e,t,s,n)=>(m(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s),b=(e,t,s)=>new Promise((n,r)=>{var i=e=>{try{o(s.next(e))}catch(Nt){r(Nt)}},a=e=>{try{o(s.throw(e))}catch(Nt){r(Nt)}},o=e=>e.done?n(e.value):Promise.resolve(e.value).then(i,a);o((s=s.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=Symbol("*"),k=w,C=w,S=w,I=w,T=w;function x(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(t[s]!==w&&e[s]!==t[s])return!1;return!0}function E(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}function M(e,t){return e*(1-t+2*Math.random()*t)}const R=()=>!0;function A(e,t,s){return b(this,arguments,function*(e,t,{initialDelay:s,maxDelay:n,log:r,shouldRetry:i=R}){return t().catch(a=>b(null,null,function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*s*1.2,l=M(n?Math.min(1e3*n,o):o,.05);return E(l).then(()=>A(e-1,t,{initialDelay:l/1e3,maxDelay:n,log:r,shouldRetry:i}))}))})}function _(){const e={},t=new Promise(function(t,s){e.resolve=t,e.reject=s});return e.promise=t,e}class N{constructor(e,t,s){this.layer=e,this.states=t,this.transitions=s,this._state=t[0]}get state(){return this._state}transition(e){const t=this.transitions[e];if(!t)return;if(!this.canTransition(e))return;const s=this.state;this._state=t.to,t.afterTransition({from:s,to:this.state})}canTransition(e){const t=this.transitions[e];return!!t&&("ANY"===t.from||t.from.includes(this.state))}}function O(e){return{ok:!0,value:e}}function D(e){return{ok:!1,where:"client",value:e}}function P(e){return{ok:!1,where:"server",value:e}}function j(){const e={},t=new Promise(t=>{e.ok=e=>b(null,null,function*(){return t(O(e))}),e.clientErr=e=>t(D(e)),e.serverErr=e=>t(P(e)),e.resolve=e=>t(e)});return e.promise=t,e}function U(e){return e.filter(e=>e.ok).map(e=>e.value)}function $(e,t){if(t.ok)return t.value.data;if("SESSION_DESTROYED"===t.value)throw new Error(`${e} failed because the session was destroyed`);if("server"===t.where)throw new Error(W(e,t.value));throw"unreachable"}function W(e,t){let s;return s=Array.isArray(t.reasons)?t.reasons.join():JSON.stringify(t.reasons),`${e} failed, got status ${t.status} ${t.errorCode}, reasons: ${s}`}let q=null;class L{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new N("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(q)return q;if(globalThis.WebSocket)return globalThis.WebSocket;throw new Error("Missing WebSocket implementation")}())(this.realtimeUrl+"&talkjs-time="+Date.now());this.socket=e,e.addEventListener("open",()=>{this.socket===e&&this.stateMachine.transition("onOpen")}),e.addEventListener("close",()=>{this.socket===e&&this.stateMachine.transition("onClose")}),e.addEventListener("message",t=>{this.socket===e&&this.handlers.onMessage(t)})}},onOpen:{from:["CONNECTING"],to:"READY",afterTransition:()=>{this.handlers.onOpen()}},onClose:{from:["CONNECTING","READY"],to:"DISCONNECTED",afterTransition:e=>b(this,[e],function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=M(1e4,.5);setTimeout(()=>{"DISCONNECTED"===this.stateMachine.state&&this.stateMachine.transition("startWs")},t)})},stopWs:{from:["CONNECTING","DISCONNECTED","READY"],to:"STOPPED",afterTransition:({from:e})=>{"READY"===e&&this.handlers.onClose();const t=this.socket;this.socket=null,null==t||t.close(1e3)}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{const e=this.socket;this.socket=null,null==e||e.close(1e3)}}})}stopWs(){this.stateMachine.transition("stopWs")}startWs(){this.stateMachine.transition("startWs")}send(e){return"READY"===this.stateMachine.state?(this.socket.send(e),O(void 0)):D("SOCKET_NOT_READY")}terminate(){const e=this.socket;this.stateMachine.canTransition("onClose")&&this.stateMachine.transition("onClose"),e&&("terminate"in e?e.terminate():e.close(1e3))}destroy(){this.stateMachine.transition("destroy")}}class B{constructor(e,t){this.handlers=t,this.socket=new L(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t){const s=`/${t.path.map(e=>encodeURIComponent(e)).join("/")}`,n=JSON.stringify([e,t.method,s,t.data,t.headers]);return this.socket.send(n)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){try{const t=JSON.parse(e.data);if("PUBLISH"===t[1]){const e=t[0],s=JSON.stringify([e,"ACK"]);this.socket.send(s);const n=t.slice(2),r=[];n.forEach(e=>{"session.expired"===e.type?this.handlers.onAuthExpired():"upstream.restarting"===e.type?this.handlers.onUpstreamRestarting():r.push(e)}),r.length>0&&this.handlers.onPublish(e,r)}else{const e=t[0],s=t[1],n=t[2];this.handlers.onResponse(e,s,n)}}catch(t){}}}class G{constructor(e){this.delayMs=e,this.timeout=void 0}schedule(e){this.stop(),this.timeout=setTimeout(()=>{void 0!==this.timeout&&(this.stop(),e())},this.delayMs)}stop(){void 0!==this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)}}const F="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class H{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class z{constructor(e,t){this.handlers=t,this.seqCounter=new H,this.responseHandlers={},this.heartbeats=new J(this),this.socket=new B(e,{onUpstreamRestarting:()=>{this.heartbeats.serverActive(),this.handlers.onUpstreamRestarting()},onOpen:()=>{this.heartbeats.clientActive(),this.heartbeats.serverActive(),this.handlers.onReady()},onClose:()=>{this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.seqCounter.reset(),this.handlers.onNotReady()},onResponse:(e,t,s)=>{this.heartbeats.serverActive(),this.onResponse(e,t,s)},onPublish:(e,t)=>{this.heartbeats.serverActive(),this.handlers.onPublish(e,t),this.heartbeats.clientActive()},onAuthExpired:()=>{this.heartbeats.serverActive(),this.handlers.onAuthExpired()}})}sync(){return b(this,null,function*(){yield new Promise(e=>F(()=>e()));const e=Object.values(this.responseHandlers).map(e=>e.promise.catch(()=>{}));return Promise.all(e)})}call(e){const t=this.seqCounter.next(),s=j();this.responseHandlers[t]=s;const n=this.socket.call(t,e);return n.ok||(s.resolve(n),delete this.responseHandlers[t]),this.heartbeats.clientActive(),s.promise}onResponse(e,t,s){return b(this,null,function*(){const n=this.responseHandlers[e];n&&(200===t?n.ok({status:t,data:s}):n.serverErr({status:t,errorCode:s.errorCode,reasons:s.reasons}),delete this.responseHandlers[e])})}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.socket.destroy()}terminate(){this.socket.terminate()}}class J{constructor(e){this.connection=e,this.clientInactivityTimer=new G(25e3),this.serverInactivityTimer=new G(1e4),this.serverTimeoutTimer=new G(5e3)}clientActive(){this.clientInactivityTimer.schedule(()=>{this.sendHeartbeat()})}serverActive(){this.serverTimeoutTimer.stop(),this.serverInactivityTimer.schedule(()=>{this.sendHeartbeat(),this.serverTimeoutTimer.schedule(()=>{this.connection.terminate()})})}stop(){this.clientInactivityTimer.stop(),this.serverInactivityTimer.stop(),this.serverTimeoutTimer.stop()}sendHeartbeat(){this.connection.call({method:"GET",path:["ping"],data:{},headers:{}}).catch(()=>{})}}class Y{constructor(e,t,s){this.authProvider=t,this.handlers=s,this.stateMachine=new N("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){yield this.renewSession()})},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>b(this,null,function*(){yield this.renewSession()})},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>b(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},authenticated:{from:["LOGGING_IN","RENEWING_SESSION"],to:"READY",afterTransition:({from:e})=>{"LOGGING_IN"===e&&this.handlers.onReady()}},authExpired:{from:["READY","RENEWING_SESSION"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){this.handlers.onNotReady(),this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},wsDisconnected:{from:["READY","LOGGING_IN","RENEWING_SESSION"],to:"WAITING_FOR_WS",afterTransition:({from:e})=>{"READY"!==e&&"RENEWING_SESSION"!==e||this.handlers.onNotReady(),this.authProvider.clearScheduledRefresh()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.authProvider.clearScheduledRefresh(),this.connection.destroy()}}}),this.connection=new z(e,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onReady:()=>this.stateMachine.transition("logIn"),onNotReady:()=>{this.stateMachine.transition("wsDisconnected")},onAuthExpired:()=>{this.stateMachine.transition("authExpired")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}}),t.onTokenChanged(()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauth")})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){const t=this.connection.call(e);return t.then(e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")}),t}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs(),this.authProvider.getToken().catch(()=>{})}destroy(){this.stateMachine.transition("destroy")}renewSession(){return b(this,null,function*(){let e;try{const t=this.authProvider.getCachedToken();e=t||(yield this.authProvider.getToken())}catch(r){return}const t=yield this.connection.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}});if(!t.ok&&"client"===t.where)return;const s=t.value;if(s.status,200===s.status){const t=s.data.expiresInSeconds;return void(null!==t&&t<120?(console.warn(`[TalkJS] Authenticated with a token that expires in ${t}s. Treating it as already expired and refreshing. Newly generated tokens should last at least 10 minutes.`),"LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed")):(this.authProvider.scheduleRefresh(t),this.authProvider.emitTokenAccepted(e),this.stateMachine.canTransition("authenticated")&&this.stateMachine.transition("authenticated")))}if(401===s.status)return void("LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed"));if(400===s.status)return void this.authProvider.emitTokenRefreshFailed(W("Authentication",s));if(402===s.status)return void this.authProvider.emitTokenRefreshFailed(W("Authentication",s));const n=5e3*Math.random()+5e3;setTimeout(()=>{this.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}}).catch(()=>{})},n)})}}class V{constructor(e,t,s){this.handlers=s,this.stateMachine=new N("StopStartConnection",["STOPPED","WAITING_FOR_WS","READY","TERMINATED"],{unexpectedDisconnect:{from:["READY"],to:"WAITING_FOR_WS",afterTransition:()=>{this.inactivityTimer.stop(),this.handlers.onNotReady()}},stop:{from:["WAITING_FOR_WS","READY"],to:"STOPPED",afterTransition:()=>{this.connection.stopWs(),this.inactivityTimer.stop(),this.handlers.onNotReady()}},start:{from:["STOPPED"],to:"WAITING_FOR_WS",afterTransition:()=>{this.connection.startWs()}},ready:{from:["WAITING_FOR_WS"],to:"READY",afterTransition:()=>{this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),this.handlers.onReady()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.inactivityTimer.stop(),this.connection.destroy()}}}),this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer=new G(3e3),this.connection=new Y(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("ready")},onNotReady:()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("unexpectedDisconnect")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}get inactive(){return 0===this.pendingCalls&&0===this.activeSubscriptions}sync(){return b(this,null,function*(){return this.connection.sync()})}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e){return b(this,null,function*(){this.inactivityTimer.stop(),this.pendingCalls++,this.logTrace("Called",e.path,e.data);const t=yield this.connection.call(e);return this.pendingCalls--,this.logTrace("Received",e.path,e.data),"SUBSCRIBE"===e.method&&t.ok?(this.activeSubscriptions++,this.logTrace("Subscribed",e.path,e.data)):"UNSUBSCRIBE"===e.method&&t.ok&&(this.activeSubscriptions--,this.logTrace("Unsubscribed",e.path,e.data)),this.inactive&&this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),t})}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}logTrace(e,t,s){}}class Q{constructor(e,t,s){this.handlers=s,this.stateMachine=new N("QueuedConnection",["NOT_READY","PROCESSING_QUEUE","READY","TERMINATED"],{processQueue:{from:["NOT_READY"],to:"PROCESSING_QUEUE",afterTransition:()=>{this.sendQueuedCalls()}},ready:{from:["PROCESSING_QUEUE"],to:"READY",afterTransition:()=>{this.handlers.onReady()}},notReady:{from:["PROCESSING_QUEUE","READY"],to:"NOT_READY",afterTransition:()=>{Object.values(this.subscribeQueue).forEach(e=>e.deferred.ok({status:200,data:{}})),this.subscribeQueue={},this.handlers.onSubscriptionsLost()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{for(var e;this.callQueue.length;){const t=null==(e=this.callQueue.shift())?void 0:e.deferred;null==t||t.clientErr("SESSION_DESTROYED")}this.connection.destroy()}}}),this.subscribeQueue={},this.callQueue=[],this.connection=new V(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return"READY"===this.stateMachine.state?this.connection.call(e):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e.method||"UNSUBSCRIBE"===e.method?this._subscribe(e):this._call(e))}_subscribe(e){const t=e.path.join("/"),s=this.subscribeQueue[t];if(s&&s.params.method===e.method)return s.deferred.promise;s&&s.params.method!==e.method&&(s.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[t]);const n={deferred:j(),params:e};return this.subscribeQueue[t]=n,n.deferred.promise}_call(e){const t={deferred:j(),params:e};return this.callQueue.push(t),t.deferred.promise}dequeue(){for(const e in this.subscribeQueue){const t=this.subscribeQueue[e];return delete this.subscribeQueue[e],t}return this.callQueue.shift()}destroy(){this.stateMachine.transition("destroy")}sendQueuedCalls(){return b(this,null,function*(){let e=0;for(;"PROCESSING_QUEUE"===this.stateMachine.state;){e++;const t=this.dequeue();if(!t)return void this.stateMachine.transition("ready");this.connection.call(t.params).then(e=>{t.deferred.resolve(e)}),e>50&&(yield new Promise(e=>setTimeout(e,100)))}})}isConnected(){return"READY"===this.stateMachine.state||"PROCESSING_QUEUE"===this.stateMachine.state}}function K(e){return Object.freeze(e)}function Z(e){return K(e.map(e=>function(e){switch(e.type){case"text":return Object.freeze({type:"text",children:X(e.children)});case"file":case"location":return Object.freeze(e)}}(e)))}function X(e){return K(e.map(e=>function(e){if("string"==typeof e)return e;switch(e.type){case"bold":case"italic":case"strikethrough":case"bulletList":case"bulletPoint":case"link":case"actionLink":case"actionButton":return Object.freeze(p(d({},e),{children:X(e.children)}));case"mention":case"autoLink":case"codeSpan":case"customEmoji":return Object.freeze(e)}}(e)))}function ee(e,t){return void 0===t?e:t}function te(e,t){return void 0===t?e:K(t)}function se(e,t){if(void 0===t)return e;if(null===t)return K({});const s=d({},e);for(const n in t){const e=t[n];null===e?delete s[n]:s[n]=e}return K(s)}function ne(e,t){if(e===t)return!0;if(!e||!t)return!1;if("object"!=typeof e||"object"!=typeof t)return!1;if(e.constructor!==t.constructor)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!ne(e[s],t[s]))return!1}else{const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(const n of s){if(!Object.hasOwnProperty.call(t,n))return!1;if(!ne(e[n],t[n]))return!1}}return!0}const re="undefined"!=typeof window&&null!=(t=window.queueMicrotask)?t:setTimeout;class ie{constructor(e,t,s){this.headers=e,this.clearPendingBatch=t,this.sendCalls=s,this.sent=!1,re(()=>this.send())}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class ae extends ie{constructor(e,t,s){super(t,s,()=>{this.sendSubscribe(),this.sendGet()}),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e){return ae.isCorrectBatchTypeFor(e)&&ne(this.headers,e.headers)}static isCorrectBatchTypeFor(e){const t=x(e.path,["users",S]),s="GET"===e.method||"SUBSCRIBE"===e.method;return t&&s}push(e){const t=e.path[1],s=j();return"GET"===e.method?this.getCalls.push({userId:t,deferred:s}):this.subscribeCalls.push({userId:t,deferred:s}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),s.promise}sendGet(){return b(this,null,function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map(e=>e.userId))],t=yield this.connection.call({method:"GET",path:["users"],data:{ids:e,includePrivateFields:!1},headers:this.headers});if(t.ok)for(const s of this.getCalls){const e=t.value.data[s.userId];e?s.deferred.ok({status:200,data:e}):s.deferred.serverErr({status:404,errorCode:"NOT_FOUND",reasons:["No user with that ID exists"]})}else this.getCalls.forEach(e=>e.deferred.resolve(t))})}sendSubscribe(){if(0===this.subscribeCalls.length)return;const e=[...new Set(this.subscribeCalls.map(e=>e.userId))];this.connection.call({method:"SUBSCRIBE",path:["users"],data:{ids:e},headers:this.headers}).then(e=>this.subscribeCalls.forEach(t=>t.deferred.resolve(e)))}}class oe extends ie{constructor(e,t,s,n){super(s,n,()=>this.sendMutate()),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e){return!(!oe.isCorrectBatchTypeFor(e)||e.path[1]!==this.conversationId||!ne(this.headers,e.headers))}static isCorrectBatchTypeFor(e){return!(!x(e.path,["conversations",k,"participants",S])||"PUT"!==e.method&&"POST"!==e.method&&"PATCH"!==e.method)}push(e){const t=e.path[3],s=j();return this.calls.push({action:{id:t,method:e.method,params:e.data},deferred:s}),100===this.calls.length&&this.send(),s.promise}sendMutate(){return b(this,null,function*(){const e=this.calls.map(e=>e.action),t=yield this.connection.call({method:"POST",path:["conversations",this.conversationId,"participants"],data:{actions:e},headers:this.headers});if(!t.ok)return void this.calls.forEach(e=>e.deferred.resolve(t));const s=t.value.data.responses;for(let n=0;n<s.length;n++){const e=this.calls[n].deferred,t=s[n];200===t.status?e.ok(p(d({},t),{data:{}})):e.serverErr(t)}})}}class le{constructor(e,t,s){this.pendingBatch=null,this.connection=new Q(e,t,s)}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return b(this,null,function*(){var t;if(null==(t=this.pendingBatch)?void 0:t.canPush(e))return this.pendingBatch.push(e);this.pendingBatch&&this.pendingBatch.send();const s=this.createEmptyBatchFor(e);return s?(this.pendingBatch=s,s.push(e)):this.connection.call(e)})}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e){var t,s;if(ae.isCorrectBatchTypeFor(e))return new ae(this.connection,null!=(t=e.headers)?t:{},()=>this.pendingBatch=null);if(oe.isCorrectBatchTypeFor(e)){const t=e.path[1];return new oe(t,this.connection,null!=(s=e.headers)?s:{},()=>this.pendingBatch=null)}return null}}const ce={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class ue{constructor(e,t,s){this.throttler=new he,this.alive=!0,this.connection=new le(e,t,s)}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return b(this,null,function*(){let t=0;for(;this.alive;){const s=yield this.connection.call(e);if((s.ok||"client"!==s.where||"SOCKET_NOT_READY"!==s.value)&&(s.ok||"server"!==s.where||500!==s.value.status)||t++,10===t)return s;if(s.ok||"client"!==s.where){const e=s.value,t=e.status,n=ce[t];if("RESOLVE"===n)return this.throttler.resetDelay(),s;if("RETRY"===n)continue;if("DELAY"===n){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===s.value)return D("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==s.value&&("SOCKET_NOT_READY"!==s.value?s.value:yield this.throttler.wait())}return D("SESSION_DESTROYED")})}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class he{constructor(){this.initialDelayMs=200,this.exponentialFactor=1.2,this.maxDelayMs=3e4,this.currentDelayMs=this.initialDelayMs,this.lastCall=0}getCurrentDelay(){return this.currentDelayMs}wait(){const e=(new Date).getTime(),t=M(this.currentDelayMs,.05),s=this.lastCall+t,n=Math.max(0,s-e);return this.lastCall=e+n,this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs),E(n)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function de(e){return e.map(e=>encodeURIComponent(e)).join()}class pe{constructor(){this.paths={}}add(e){this.paths[de(e)]=e}delete(e){delete this.paths[de(e)]}has(e){return Object.hasOwnProperty.call(this.paths,de(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach(t=>e(t))}}class fe{constructor(e,t,s){this.handlers=s,this.targetSubscriptions=new pe,this.connection=new ue(e,t,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onSubscriptionsLost:()=>{this.targetSubscriptions.forEach(e=>{this.resubscribe(e)}),this.handlers.onResubscribeSent()},onReady:()=>this.handlers.onReady(),onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return this.connection.call(e)}subscribe(e){return b(this,null,function*(){return this.targetSubscriptions.add(e),this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}})})}unsubscribe(e){return b(this,null,function*(){return this.targetSubscriptions.delete(e),this.connection.call({method:"UNSUBSCRIBE",path:e,data:{},headers:{}})})}resubscribe(e){return b(this,null,function*(){const t=yield this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}});t.ok||this.handlers.onResubscribeError(e,t)})}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class me{constructor(e,t,s){this.handlers=s,this.virtualPathsPerRealSubscription=new Map,this.connection=new fe(e,t,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onResubscribeSent:()=>this.handlers.onResubscribeSent(),onResubscribeError:(e,t)=>this.handlers.onResubscribeError(e,t),onReady:()=>this.handlers.onReady(),onPublish:(e,t)=>this.handlers.onPublish(e,t)})}toRealPath(e){return x(e,["<filtered>","me","conversations",T])?["me","conversations"]:e}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return this.connection.call(e)}subscribe(e){return b(this,null,function*(){const t=e.join("/"),s=this.toRealPath(e),n=s.join("/"),r=this.virtualPathsPerRealSubscription.get(n);return r?(r.add(t),{ok:!0,value:{status:200,data:{}}}):(this.virtualPathsPerRealSubscription.set(n,new Set([t])),this.connection.subscribe(s))})}unsubscribe(e){return b(this,null,function*(){const t=e.join("/"),s=this.toRealPath(e),n=s.join("/"),r=this.virtualPathsPerRealSubscription.get(n);return r?(r.delete(t),0===r.size?(this.virtualPathsPerRealSubscription.delete(n),this.connection.unsubscribe(s)):{ok:!0,value:{status:200,data:{}}}):{ok:!0,value:{status:200,data:{}}}})}destroy(){this.virtualPathsPerRealSubscription.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class ge{constructor(){this.prev=Promise.resolve()}runExclusive(e){return b(this,null,function*(){const t=this.prev.then(()=>e());return this.prev=t,t})}sync(){return b(this,null,function*(){return this.runExclusive(()=>{})})}}class ve{constructor(e){this.initialised=!1,this.getPointer=void 0,this.pendingStates=[e],e.resultPromise.then(()=>this.initialised=!0)}get pendingPointer(){if(0!==this.pendingStates.length)return this.pendingStates[this.pendingStates.length-1]}get mostRecentState(){var e;return null!=(e=this.pendingPointer)?e:this.getPointer}canAppendState(e){var t,s;const n=null==(t=this.getPointer)?void 0:t.seq;if(void 0!==n&&e<=n)return!1;const r=null==(s=this.pendingPointer)?void 0:s.seq;return!(void 0!==r&&e<r)}set(e){if(!this.canAppendState(e.seq))throw"Appending in the past";this.pendingStates.push(e)}mutate(e,t){if(!this.initialised)return;if(!this.canAppendState(e))throw"Mutating in the past";const s=this.mostRecentState.resultPromise.then(e=>e.ok?t(e):e);this.pendingStates.push({seq:e,resultPromise:s})}get(e){for(;this.pendingStates.length>0&&(void 0===this.getPointer||this.pendingStates[0].seq<=e);)this.getPointer=this.pendingStates.shift();return this.getPointer}}class ye extends ve{constructor(e,t){super(e),this.onTeardown=t,this._error=null,this._lastGoodState=Promise.resolve(void 0),this.registerNewState(e.resultPromise)}get error(){return this._error}get lastGoodState(){return this._lastGoodState}mutate(e,t){super.mutate(e,t),this.registerNewState(this.mostRecentState.resultPromise)}set(e){super.set(e),this.registerNewState(this.mostRecentState.resultPromise)}registerNewState(e){const t=this.lastGoodState;this._lastGoodState=e.then(e=>e.ok?e.value:t),e.then(e=>{e.ok||this.setError(e)})}setError(e){var t;this._error||(this._error=e,null==(t=this.onTeardown)||t.call(this,e),this.lastGoodState.then(e=>{void 0!==e&&this.teardownNested(e)}))}}class be extends ye{constructor(e,t){const s=new Promise(e=>setTimeout(e)).then(()=>this.fetchInitial(e));super({seq:e,resultPromise:s},t.onTeardown),this.initialSeq=e,this.getDeepMutex=new ge,this.lastDeep=void 0}refetchInitial(e){return b(this,null,function*(){const t=this.mostRecentState.resultPromise,s=this.fetchInitial(e),[n,r]=yield Promise.all([t,s]);return void 0!==n&&n.ok&&r.ok&&this.equal(n.value,r.value)?n:r})}refetch(e){if(null!==this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.set(t)}changedBetween(e,t){return b(this,null,function*(){if(e>=t)return!1;const s=this.get(t),n=yield s.resultPromise;return!!n.ok&&(n.value.lastChanged>Math.max(this.initialSeq,e)&&n.value.lastChanged<=t||(yield this.anyChildChanged(e,t,n.value)))})}getDeep(e){return b(this,null,function*(){return this.getDeepMutex.runExclusive(()=>b(this,null,function*(){var t;if(null!==this.error)return this.error;const s=null==(t=this.lastDeep)?void 0:t.seq;if(e===s)return this.lastDeep.deep;if(void 0!==s){if(e<s)throw`Trying to load seq ${e} when we have previously loaded seq ${s}`;if(!(yield this.changedBetween(s,e)))return this.lastDeep.seq=e,this.lastDeep.deep}const n=this.get(e).resultPromise,r=n.then(t=>t.ok?this.loadNested(e,t.value):t);this.lastDeep={seq:e,shallow:n,deep:r};const i=yield r;return null!==this.error?this.error:(i.ok||this.setError(i),i)}))})}}class we extends be{constructor(e,t,s){super(e,s),this.emitMutex=t,this.externallyIdleTimer=new ke,this.externallyIdle=!0,this.internallyIdleTimer=new ke,this.internallyIdle=!0,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive(()=>b(this,null,function*(){yield this.emit(e)}))}registerInternalSubscription(){this.internallyIdleTimer.stop(),this.internallyIdle=!1,this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,0===this.referencedByOtherStores&&this.internallyIdleTimer.restart(()=>{this.internallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs),this.tryFullyUnsubscribe())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){this.externallyIdleTimer.stop(),this.externallyIdle=!1,this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult);let t=!0;return()=>{t&&(t=!1,this.listeners=this.listeners.filter(t=>t!==e),0===this.listeners.length&&this.externallyIdleTimer.restart(()=>{this.externallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs))}}tryFullyUnsubscribe(){this.externallyIdle&&this.internallyIdle&&this.setError(D("UNSUBSCRIBED"))}emit(e){return b(this,null,function*(){var t;if(this.lastEmitSeq&&this.lastEmitSeq>=e)return;if(!1===(null==(t=this.lastEmitResult)?void 0:t.ok))return;this.lastEmitSeq=e;const s=yield this.getDeep(e);s!==this.lastEmitResult&&(this.lastEmitResult=s,this.listeners.forEach(e=>e(s)))})}}class ke{constructor(){this.timerId=void 0}restart(e,t){void 0!==this.timerId&&clearTimeout(this.timerId),this.timerId=setTimeout(()=>e(),t)}stop(){clearTimeout(this.timerId)}}var Ce,Se={};function Ie(e,t){const s=t.lastIndex;let n;const r=[];for(;null!==(n=t.exec(e));)r.push(n),""===n[0]&&(t.lastIndex+=1);return t.lastIndex=s,r}function Te(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1"),s=decodeURIComponent(t);if(/%[0-9A-Fa-f]{2}/.test(s))try{return decodeURIComponent(s.replace(/\+/g,"%20"))}catch(n){return s}return s}function xe(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(Ce)return Se;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}Ce=1,Object.defineProperty(Se,"__esModule",{value:!0}),Se.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},Se.decode=function(e){return decodeURIComponent(Array.from(atob(e),t).join(""))}}(),(e=>{function t(e,t){(function(e,t){switch(t){case"undefined":return void 0===e;case String:return"string"==typeof e||e instanceof String;case Boolean:return"boolean"==typeof e||e instanceof Boolean;case Number:return"number"==typeof e||e instanceof Number;default:return e instanceof t}})(e,t)||(t.name,String(e))}e.defined=function(e){},e.has=function(e,t){e[t]},e.is=t,e.equals=function(e,t){},e.oneOf=function(e,t){t.includes(e)||JSON.stringify(t)},e.isArray=function(e,s){t(e,Array),e&&e.length>0&&t(e[0],s)},e.optional=function(e,s){void 0!==e&&t(e,s)},e.falsy=function(e){},e.never=function(e){}})(xe||(xe={}));const Ee=xe,Me=/^\/.*[^\\]\/[im]*$/;function Re(e){return!!Me.test(e)&&!Ae(e).test("")}function Ae(e){const t=e.match(/^\/(.*[^\\])\/(.*)$/);if(!t)throw new Error(`Expected ${e} to be a (non-empty) regex`);let s=t[2]||"";return s=s.replace(/[^im]/g,"")+"g",new RegExp(t[1],s)}class _e{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:s,allowedMatches:n,forbiddenMatches:r,forbiddenWords:i,suppressLinks:a,suppressEmailAddresses:o,suppressPhoneNumbers:l,replacement:c}){if(Ee.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==a,this.suppressEmailAddresses=!1!==o,this.suppressPhoneNumbers=!1!==l,this.allowedHostnames=t||[],this.allowedPhoneNrs=(s||[]).filter(e=>e).map(e=>e.replace(/[^0-9]/g,"")),this.allowedMatches=(n||[]).filter(Re).map(e=>Ae(e)),this.forbiddenMatches=(r||[]).filter(Re).map(e=>Ae(e)),i){const e=i.split("\n").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0&&!e.startsWith("#")).map(e=>e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"));e.length&&this.forbiddenMatches.push(new RegExp(`\\b(${e.join("|")})\\b`,"gi"))}Ee(()=>this.allowedMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),Ee(()=>this.forbiddenMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),c=null==c?void 0:c.trim(),this.replacement=c&&c.length>0?c:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function Ne(e,t){return e.map(e=>function(e,t){if("text"===e.type)return Oe(e.children,function(e){var t,s,n,r,i,a,o,l,c,u,h,d,p,f;let m="";return e.t&&(m=`(${e.t("CONTACT_INFORMATION_HIDDEN")})`),{formattedLinks:null!=(t=e.formattedLinks)?t:"plaintext",markup:null!=(s=e.markup)&&s,useFallbackMentions:null!=(n=e.useFallbackMentions)&&n,sameTabLinkRules:null!=(r=e.sameTabLinkRules)?r:[],enableEmojiImageFallback:null!=(i=e.enableEmojiImageFallback)&&i,highlight:null!=(a=e.highlight)?a:[],highlightFromWordBeginnings:null!=(o=e.highlightFromWordBeginnings)&&o,contactInfo:null!=(l=e.contactInfo)&&l,suppression:null!=(c=e.suppression)?c:new _e({mode:"off"}),contactInfoHiddenText:null!=(d=null!=(h=e.contactInfoHiddenText)?h:null==(u=e.suppression)?void 0:u.replacement)?d:m,customEmojiUrls:null!=(p=e.customEmojiUrls)?p:{},enableActions:null==(f=e.enableActions)||f}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${Te(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${Te(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${Te(e.url)}`;if("file"===e.type&&"voice"===e.subtype){const t=e.duration;return void 0===t?"🎙️":`🎙️ (${Math.floor(t/60)}:${Math.floor(t%60).toString().padStart(2,"0")})`}return"file"===e.type?(e.subtype,`📎 ${Te(e.url)}`):"location"===e.type?"📍":""}(e,t)).join("\n\n")}function Oe(e,t){return e.flatMap(e=>{if("string"==typeof e)return e;switch(e.type){case"blockquote":case"bold":case"italic":case"strikethrough":case"link":case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return Oe(e.children,t);case"bulletlist":case"bulletList":return"\n"+Oe(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+Oe(e.children,t)+"\n";case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"emoji":case"customemoji":case"customEmoji":return e.text;case"suppressed":return t.contactInfoHiddenText;case"mention":return`@${e.text}`}}).join("")}function De(e){return K({id:e.id,name:e.name,custom:K(e.custom),locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage})}function Pe(e,t){return K({user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt})}function je(e){const t=Object.entries(e);return t.sort(([e,t],[s,n])=>{const r=t.createdAt-n.createdAt;return 0!==r?r:e.localeCompare(s)}),K(t.map(([e,t])=>({emoji:e,count:t.count,currentUserReacted:t.currentUserReacted})))}class Ue extends we{constructor(e,t,s,n,r){super(e,n,r),this.userId=t,this.realtimeClient=s,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return b(this,null,function*(){const t=yield this.realtimeClient.call({method:"GET",path:["users",this.userId],data:{includePrivateFields:!1},flags:{bypassCache:!0}});return t.ok?O({snapshot:De(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?O({snapshot:null,lastChanged:e}):t})}equal(e,t){return ne(e.snapshot,t.snapshot)}loadNested(e,t){return b(this,null,function*(){return O(t)})}userCreated(e,t){this.mutate(e,s=>null!==s.value.snapshot?s:O({snapshot:De(t.state),lastChanged:e}))}userEdited(e,t){this.mutate(e,s=>{const n=s.value.snapshot;return null===n?(console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."),s):O({snapshot:{id:n.id,name:ee(n.name,t.diff.name),custom:se(n.custom,t.diff.custom),locale:ee(n.locale,t.diff.locale),photoUrl:ee(n.photoUrl,t.diff.photoUrl),role:ee(n.role,t.diff.role),welcomeMessage:ee(n.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})})}getFromCache(){return b(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?P({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):O({status:200,data:{id:e.value.snapshot.id,name:e.value.snapshot.name,custom:e.value.snapshot.custom,locale:e.value.snapshot.locale,photoUrl:e.value.snapshot.photoUrl,role:e.value.snapshot.role,welcomeMessage:e.value.snapshot.welcomeMessage}}):D("NOT_IN_CACHE")})}teardownNested(e){}anyChildChanged(e,t,s){return b(this,null,function*(){return!1})}}class $e extends be{constructor(e,t,s,n){super(e,{}),this.conversationId=t,this.message=s,this.realtimeClient=n}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return b(this,null,function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId,"messages",this.message],data:{},flags:{bypassCache:!0}});if(!e.ok)return e;t=e.value.data}const s=null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),n={};return Object.entries(t.reactions).forEach(([e,{createdAt:t}])=>{n[e]=t}),O({lastChanged:e,sender:s,data:{id:t.id,type:t.type,custom:K(t.custom),createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:Ne(t.content,{}),content:Z(t.content),reactions:je(t.reactions),reactionsCreatedAt:n}})})}refetch(e){throw"Do not call refetch on message data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return ne(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){var n;const r=null==(n=s.sender)?void 0:n.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))})}loadNested(e,t){return b(this,null,function*(){var s,n,r;const i=yield null==(n=null==(s=t.sender)?void 0:s.store)?void 0:n.getDeep(e);if(!1===(null==i?void 0:i.ok))return i;if(null===t.data)return O({snapshot:null});const a=null==i?void 0:i.value;return O({snapshot:K({sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:K(t.data.custom),createdAt:t.data.createdAt,editedAt:t.data.editedAt,origin:t.data.origin,plaintext:t.data.plaintext,content:t.data.content,referencedMessageId:t.data.referencedMessageId,reactions:t.data.reactions})})})}messageEdited(e,t){this.mutate(e,s=>{if(null===s.value.data)return s;const n=s.value.data.content,r=(i=n,void 0===(a=t.diff.content)?i:Z(a));var i,a;const o=n===r?s.value.data.plaintext:Ne(r,{}),{reactions:l,reactionsCreatedAt:c}=function(e,t,s){const n=function(e,t){if(void 0===t)return e;if(null===t)return{};if(Object.values(t).every(e=>null!==e&&void 0===e.createdAt))return e;const s=d({},e);return Object.entries(t).forEach(([t,n])=>{null===n?delete s[t]:s[t]=t in e?ee(e[t],n.createdAt):n.createdAt}),s}(t,s);let r=function(e,t){if(void 0===t)return e;if(null===t)return[];if(Object.values(t).every(e=>null!==e&&void 0===e.count&&void 0===e.currentUserReacted))return e;const s=e.map(e=>{const s=t[e.emoji];return void 0===s?e:K(null===s?p(d({},e),{count:0}):{emoji:e.emoji,count:ee(e.count,s.count),currentUserReacted:ee(e.currentUserReacted,s.currentUserReacted)})}).filter(e=>e.count>0),n=new Set(s.map(e=>e.emoji));for(const r in t){const e=t[r];e&&!n.has(r)&&s.push(K({emoji:r,count:e.count,currentUserReacted:e.currentUserReacted}))}return s}(e,s);return n!==t&&(r=[...r],r.sort((e,t)=>{const s=n[e.emoji]-n[t.emoji];return 0!==s?s:e.emoji.localeCompare(t.emoji)})),r=K(r),{reactions:r,reactionsCreatedAt:n}}(s.value.data.reactions,s.value.data.reactionsCreatedAt,t.diff.reactions);return O({lastChanged:e,sender:s.value.sender,data:{id:s.value.data.id,type:s.value.data.type,createdAt:s.value.data.createdAt,origin:s.value.data.origin,referencedMessageId:s.value.data.referencedMessageId,editedAt:ee(s.value.data.editedAt,t.diff.editedAt),custom:se(s.value.data.custom,t.diff.custom),plaintext:o,content:r,reactions:l,reactionsCreatedAt:c}})})}messageDeleted(e,t){this.mutate(e,s=>null===s.value.data?s:this.messageId===t.messageId?(this.teardownNested(s.value),O({lastChanged:e,sender:null,data:null})):s.value.data.referencedMessageId===t.messageId?O({lastChanged:e,sender:s.value.sender,data:{id:s.value.data.id,type:s.value.data.type,createdAt:s.value.data.createdAt,origin:s.value.data.origin,referencedMessageId:null,editedAt:s.value.data.editedAt,custom:s.value.data.custom,plaintext:s.value.data.plaintext,content:s.value.data.content,reactions:s.value.data.reactions,reactionsCreatedAt:s.value.data.reactionsCreatedAt}}):s)}getFromCache(){return b(this,null,function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return D("NOT_IN_CACHE");if(null===t.value.data)return P({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const s=t.value,{sender:n}=s,r=f(s,["sender"]).data,{reactions:i,reactionsCreatedAt:a}=r,o=f(r,["reactions","reactionsCreatedAt"]),l={};return i.forEach(({emoji:e,count:t,currentUserReacted:s})=>{const n=e;l[n]={count:t,createdAt:a[n],currentUserReacted:s}}),O({status:200,data:p(d({},o),{senderId:null!=(e=null==n?void 0:n.store.userId)?e:null,reactions:l})})})}}class We extends be{constructor(e,t,s,n){super(e,{}),this.createdAt=t,this.dataStore=s,this.referencedDataStore=n}get messageId(){return this.dataStore.messageId}fetchInitial(e){return b(this,null,function*(){return O({lastChanged:e,dataStore:this.dataStore,referencedDataStore:this.referencedDataStore})})}refetch(e){throw"Do not call refetch on message stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return!0}teardownNested(e){}anyChildChanged(e,t,s){return b(this,arguments,function*(e,t,{dataStore:s,referencedDataStore:n}){return!0===(yield s.changedBetween(e,t))||!0===(yield null==n?void 0:n.changedBetween(e,t))})}loadNested(e,t){return b(this,null,function*(){var s,n,r;const i=yield t.dataStore.getDeep(e);if(!i.ok)return i;const a=i.value;if(null===a.snapshot)return O({snapshot:null});const o=yield null==(s=t.referencedDataStore)?void 0:s.getDeep(e);if(o&&!o.ok)return o;const l=null!=(n=null==o?void 0:o.value)?n:null,c=null!=(r=null==l?void 0:l.snapshot)?r:null;return O({snapshot:K({id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:K(a.snapshot.custom),createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:c,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content,reactions:a.snapshot.reactions})})})}}class qe extends we{constructor(e,t,s,n,r){super(e,n,r),this.conversationId=t,this.realtimeClient=s,this.handlers=r,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}listen(e){return this.onlyUsedInternally&&this.mostRecentState.resultPromise.then(e=>{if(e.ok&&null!==e.value.inWindow){const t=30-e.value.inWindow.length;t>0&&this.loadMore(t)}}),super.listen(e)}fetchInitial(e){return b(this,null,function*(){const t=this.onlyUsedInternally?1:30,s=yield Le({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return s.ok?null===s.value.messages?O({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):Be({seq:e,messages:s.value.messages,cursor:s.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):s})}teardownNested(e){if(e.stores){const t=D("TERMINATED");Object.values(e.stores).forEach(e=>e.setError(t)),e.inWindow.forEach(e=>e.setError(t))}}anyChildChanged(e,t,s){return b(this,null,function*(){for(const n in s.stores){const r=s.stores[n];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1})}lastMessageChangedBetween(e,t){return b(this,null,function*(){if(e>=t)return!1;const s=yield this.get(t).resultPromise;if(!s.ok)return!1;if(s.value.lastMessageChanged>e)return!0;if(null===s.value.stores)return!1;const n=s.value.inWindow[0];return void 0!==n&&!0===(yield n.changedBetween(e,t))})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!ne(Object.keys(e.stores),Object.keys(t.stores))&&!!ne(e.inWindow.map(e=>e.messageId),t.inWindow.map(e=>e.messageId))&&ne(e.windowEnd,t.windowEnd)}loadNested(e,t){return b(this,null,function*(){if(null===t.stores)return O({snapshot:null,loadedAll:!0});const s=yield Promise.all(t.inWindow.map(t=>t.getDeep(e))),n=s.find(e=>!e.ok);return n||O({snapshot:K(s.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot)),loadedAll:null===t.windowEnd})})}loadMore(e=30){return b(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=_();this.pendingLoadMore=t.promise;const s=yield this.mostRecentState.resultPromise;if(!s.ok){if("client"===s.where)throw t.reject(s.value),this.pendingLoadMore=void 0,s.value;{const e=W("Loading more messages",s.value);throw t.reject(s.value),this.pendingLoadMore=void 0,e}}if(null===s.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const n=s.value.windowEnd.cursor,r=yield Le({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.messages.loadedMore",conversationId:this.conversationId,data:r})})}loadedMore(e,t){this.mutate(e,s=>null===s.value.windowEnd?s:t.data.ok?null===t.data.value.messages?(console.warn("[TalkJS] When loading more messages, the conversation no longer existed. We should have been told about this."),s):Be({seq:e,prevState:s.value,messages:t.data.value.messages,cursor:t.data.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t.data)}messageCreated(e,t){this.mutate(e,s=>{if(null===s.value.stores)return console.warn("[TalkJS] Received a 'message.created' event for a nonexistent conversation."),s;if(s.value.windowEnd&&t.state.createdAt<s.value.windowEnd.oldestMessageTs)return s;if(Object.hasOwnProperty.call(s.value.stores,t.state.id))return s;const n=d({},s.value.stores),r=new $e(e,this.conversationId,t.state,this.realtimeClient);n[t.state.id]=r;const i=t.state.referencedMessageId;let a;null===i?a=null:i in n?a=n[i]:(a=new $e(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new We(e,t.state.createdAt,r,a),l=[...s.value.inWindow,o];l.sort((e,t)=>t.createdAt-e.createdAt);const c=l[0].messageId===t.messageId?e:s.value.lastMessageChanged;return O({lastChanged:e,lastMessageChanged:c,stores:n,inWindow:l,windowEnd:s.value.windowEnd})})}messageEdited(e,t){this.mutate(e,s=>{var n;return null===s.value.stores?(console.warn("[TalkJS] Received a 'message.edited' event for a nonexistent conversation."),s):(null==(n=s.value.stores[t.messageId])||n.messageEdited(e,t),s)})}messageDeleted(e,t){this.mutate(e,s=>{if(null===s.value.stores)return console.warn("[TalkJS] Received a 'message.deleted' event for a conversation that we thought didn't exist."),s;if(Object.values(s.value.stores).forEach(s=>s.messageDeleted(e,t)),void 0===s.value.stores[t.messageId])return s;const n=d({},s.value.stores);delete n[t.messageId];const r=s.value.inWindow.filter(e=>e.messageId!==t.messageId);if(t.newLastMessage&&0===r.length){const s=new $e(e,this.conversationId,t.newLastMessage,this.realtimeClient);n[s.messageId]=s;const i=t.newLastMessage.referencedMessageId;let a;null===i?a=null:i in n?a=n[i]:(a=new $e(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new We(e,t.newLastMessage.createdAt,s,a);r.push(o)}const i=void 0!==t.newLastMessage?e:s.value.lastMessageChanged;return O({lastChanged:e,lastMessageChanged:i,stores:n,inWindow:r,windowEnd:s.value.windowEnd})})}conversationCleared(e,t){this.mutate(e,t=>{var s;return 0===(null==(s=t.value.inWindow)?void 0:s.length)&&null===t.value.windowEnd?t:(this.teardownNested(t.value),O({lastChanged:e,lastMessageChanged:e,stores:{},inWindow:[],windowEnd:null}))})}sideCreated(e,t){const s=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.stores?(s.then(e=>{e.ok&&this.teardownNested(e.value)}),e):s)}sideDeleted(e,t){this.mutate(e,t=>null===t.value.stores?t:(this.teardownNested(t.value),O({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null})))}getMessageFromCache(e){return b(this,null,function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return D("NOT_IN_CACHE");if(null===t.value.stores)return D("NOT_IN_CACHE");const s=t.value.stores[e];return void 0===s?D("NOT_IN_CACHE"):s.getFromCache()})}}function Le(e){return b(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:s,count:n}){const r={limit:n,cursor:e},i=yield t.call({method:"GET",path:["me","