@talkjs/core 1.5.6 → 1.5.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/talkSession.cjs +1 -1
- package/dist/talkSession.js +55 -45
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -69,6 +69,14 @@ If you encounter any problems with `@talkjs/core`, please open a [chat with supp
|
|
|
69
69
|
|
|
70
70
|
## Changelog
|
|
71
71
|
|
|
72
|
+
### 1.5.8
|
|
73
|
+
|
|
74
|
+
- Bugfix for React Native.
|
|
75
|
+
|
|
76
|
+
### 1.5.7
|
|
77
|
+
|
|
78
|
+
- Fixed a bug that would cause a crash in React Native.
|
|
79
|
+
|
|
72
80
|
### 1.5.6
|
|
73
81
|
|
|
74
82
|
- Bugfix for on-prem deployments, no impact on the SAAS offering.
|
package/dist/talkSession.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e,t=Object.defineProperty,n=Object.defineProperties,s=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,o=(e,n,s)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s,u=(e,t)=>{for(var n in t||(t={}))i.call(t,n)&&o(e,n,t[n]);if(r)for(var n of r(t))a.call(t,n)&&o(e,n,t[n]);return e},l=(e,t)=>n(e,s(t)),c=(e,t)=>{var n={};for(var s in e)i.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&r)for(var s of r(e))t.indexOf(s)<0&&a.call(e,s)&&(n[s]=e[s]);return n},h=(e,t,n)=>new Promise(((s,r)=>{var i=e=>{try{o(n.next(e))}catch(Ke){r(Ke)}},a=e=>{try{o(n.throw(e))}catch(Ke){r(Ke)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(i,a);o((n=n.apply(e,t)).next())}));function d(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(p(e,t.value));throw"unreachable"}function p(e,t){let n;return n=Array.isArray(t.reasons)?t.reasons.join():JSON.stringify(t.reasons),`${e} failed, got status ${t.status} ${t.errorCode}, reasons: ${n}`}function f(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if("*"!==t[n]&&e[n]!==t[n])return!1;return!0}function m(e){return e<=0?Promise.resolve():new Promise((t=>setTimeout(t,e)))}function g(e,t){return e*(1-t+2*Math.random()*t)}Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=()=>!0;function b(e,t,n){return h(this,arguments,(function*(e,t,{initialDelay:n,maxDelay:s,log:r,shouldRetry:i=v}){return t().catch((a=>h(this,null,(function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*n*1.2,u=g(s?Math.min(1e3*s,o):o,.05);return m(u).then((()=>b(e-1,t,{initialDelay:u/1e3,maxDelay:s,log:r,shouldRetry:i})))}))))}))}function y(){const e={},t=new Promise((function(t,n){e.resolve=t,e.reject=n}));return e.promise=t,e}class w{constructor(e,t,n){this.layer=e,this.states=t,this.transitions=n,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 n=this.state;this._state=t.to,t.afterTransition({from:n,to:this.state})}canTransition(e){const t=this.transitions[e];return!!t&&("ANY"===t.from||t.from.includes(this.state))}}function C(e){return{ok:!0,value:e}}function A(e){return{ok:!1,where:"client",value:e}}function E(e){return{ok:!1,where:"server",value:e}}function k(){const e={},t=new Promise((t=>{e.ok=e=>h(this,null,(function*(){return t(C(e))})),e.clientErr=e=>t(A(e)),e.serverErr=e=>t(E(e)),e.resolve=e=>t(e)}));return e.promise=t,e}let x=null;class I{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new w("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(x)return x;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=>h(this,[e],(function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=g(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),C(void 0)):A("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 T{constructor(e,t){this.handlers=t,this.socket=new I(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t,n,s){const r=`/${n.map((e=>encodeURIComponent(e))).join("/")}`,i=JSON.stringify([e,t,r,s]);return this.socket.send(i)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){if("Auth token expired"!==e.data)try{const t=JSON.parse(e.data);if("PUBLISH"===t[1]){const e=t[0],n=JSON.stringify([e,"ACK"]);this.socket.send(n);const s=t.slice(2),r=[];s.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],n=t[1],s=t[2];this.handlers.onResponse(e,n,s)}}catch(t){}else this.handlers.onAuthExpired()}}class D{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)}}class S{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class M{constructor(e,t){this.handlers=t,this.seqCounter=new S,this.responseHandlers={},this.heartbeats=new F(this),this.socket=new T(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,n)=>{this.heartbeats.serverActive(),this.onResponse(e,t,n)},onPublish:(e,t)=>{this.heartbeats.serverActive(),this.handlers.onPublish(e,t),this.heartbeats.clientActive()},onAuthExpired:()=>{this.heartbeats.serverActive(),this.handlers.onAuthExpired()}})}call(e,t,n){const s=this.seqCounter.next(),r=k();this.responseHandlers[s]=r;const i=this.socket.call(s,e,t,n);return i.ok||r.resolve(i),this.heartbeats.clientActive(),r.promise}onResponse(e,t,n){return h(this,null,(function*(){const s=this.responseHandlers[e];s&&(200===t?s.ok({status:t,data:n}):s.serverErr({status:t,errorCode:n.errorCode,reasons:n.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 F{constructor(e){this.connection=e,this.clientInactivityTimer=new D(25e3),this.serverInactivityTimer=new D(1e4),this.serverTimeoutTimer=new D(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("GET",["ping"],{}).catch((()=>{}))}}class B{constructor(e,t,n){this.authProvider=t,this.handlers=n,this.stateMachine=new w("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>h(this,null,(function*(){yield this.renewSession()}))},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>h(this,null,(function*(){this.authProvider.refreshToken(),yield this.renewSession()}))},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>h(this,null,(function*(){yield this.renewSession()}))},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>h(this,null,(function*(){this.authProvider.refreshToken(),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:()=>h(this,null,(function*(){this.handlers.onNotReady(),this.authProvider.refreshToken(),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 M(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")}))}call(e,t,n){const s=this.connection.call(e,t,n);return s.then((e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")})),s}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs()}destroy(){this.stateMachine.transition("destroy")}renewSession(){return h(this,null,(function*(){const e=yield this.authProvider.getToken(),t=yield this.connection.call("POST",["session","renew"],{token:e});if(!t.ok&&"client"===t.where)return;const n=t.value;if(n.status,200===n.status){const t=n.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===n.status)return void("LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed"));if(400===n.status)return void this.authProvider.emitTokenRefreshFailed(p("Authentication",n));if(402===n.status)return void this.authProvider.emitTokenRefreshFailed(p("Authentication",n));const s=5e3*Math.random()+5e3;setTimeout((()=>{this.call("POST",["session","renew"],{token:e}).catch((()=>{}))}),s)}))}}class R{constructor(e,t,n){this.handlers=n,this.stateMachine=new w("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 D(3e3),this.connection=new B(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}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e,t,n){return h(this,null,(function*(){this.inactivityTimer.stop(),this.pendingCalls++,this.logTrace("Called",t,n);const s=yield this.connection.call(e,t,n);return this.pendingCalls--,this.logTrace("Received",t,n),"SUBSCRIBE"===e&&s.ok?(this.activeSubscriptions++,this.logTrace("Subscribed",t,n)):"UNSUBSCRIBE"===e&&s.ok&&(this.activeSubscriptions--,this.logTrace("Unsubscribed",t,n)),this.inactive&&this.inactivityTimer.schedule((()=>{this.stateMachine.transition("stop")})),s}))}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}logTrace(e,t,n){}}class N{constructor(e,t,n){this.handlers=n,this.stateMachine=new w("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 R(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}call(e,t,n){return"READY"===this.stateMachine.state?this.connection.call(e,t,n):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e||"UNSUBSCRIBE"===e?this._subscribe(e,t,n):this._call(e,t,n))}_subscribe(e,t,n){const s=t.join("/"),r=this.subscribeQueue[s];if(r&&r.method===e)return r.deferred.promise;r&&r.method!==e&&(r.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[s]);const i={deferred:k(),method:e,path:t,data:n};return this.subscribeQueue[s]=i,i.deferred.promise}_call(e,t,n){const s={deferred:k(),method:e,path:t,data:n};return this.callQueue.push(s),s.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 h(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.method,t.path,t.data).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}}const O="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class _{constructor(e,t){this.clearPendingBatch=e,this.sendCalls=t,this.sent=!1,O((()=>this.send()))}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class P extends _{constructor(e,t){super(t,(()=>{this.sendSubscribe(),this.sendGet()})),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e,t){return P.isCorrectBatchTypeFor(e,t)}static isCorrectBatchTypeFor(e,t){return f(t,["users","*"])&&("GET"===e||"SUBSCRIBE"===e)}push(e,t,n){const s=t[1],r=k();return"GET"===e?this.getCalls.push({userId:s,deferred:r}):this.subscribeCalls.push({userId:s,deferred:r}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),r.promise}sendGet(){return h(this,null,(function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map((e=>e.userId)))],t=yield this.connection.call("GET",["users"],{ids:e,includePrivateFields:!1});if(t.ok)for(const n of this.getCalls){const e=t.value.data[n.userId];e?n.deferred.ok({status:200,data:e}):n.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("SUBSCRIBE",["users"],{ids:e}).then((e=>this.subscribeCalls.forEach((t=>t.deferred.resolve(e)))))}}class j extends _{constructor(e,t,n){super(n,(()=>this.sendMutate())),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e,t){return!!j.isCorrectBatchTypeFor(e,t)&&t[1]===this.conversationId}static isCorrectBatchTypeFor(e,t){return f(t,["conversations","*","participants","*"])&&("PUT"===e||"POST"===e||"PATCH"===e)}push(e,t,n){const s=t[3],r=k();return this.calls.push({action:{id:s,method:e,params:n},deferred:r}),100===this.calls.length&&this.send(),r.promise}sendMutate(){return h(this,null,(function*(){const e=this.calls.map((e=>e.action)),t=yield this.connection.call("POST",["conversations",this.conversationId,"participants"],{actions:e});if(!t.ok)return void this.calls.forEach((e=>e.deferred.resolve(t)));const n=t.value.data.responses;for(let s=0;s<n.length;s++){const e=this.calls[s].deferred,t=n[s];200===t.status?e.ok(l(u({},t),{data:{}})):e.serverErr(t)}}))}}class U{constructor(e,t,n){this.pendingBatch=null,this.connection=new N(e,t,n)}call(e,t,n){return h(this,null,(function*(){var s;if(null==(s=this.pendingBatch)?void 0:s.canPush(e,t))return this.pendingBatch.push(e,t,n);this.pendingBatch&&this.pendingBatch.send();const r=this.createEmptyBatchFor(e,t);return r?(this.pendingBatch=r,r.push(e,t,n)):this.connection.call(e,t,n)}))}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e,t){if(P.isCorrectBatchTypeFor(e,t))return new P(this.connection,(()=>this.pendingBatch=null));if(j.isCorrectBatchTypeFor(e,t)){const e=t[1];return new j(e,this.connection,(()=>this.pendingBatch=null))}return null}}const $={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class W{constructor(e,t,n){this.throttler=new q,this.alive=!0,this.connection=new U(e,t,n)}call(e,t,n){return h(this,null,(function*(){let s=0;for(;this.alive;){const r=yield this.connection.call(e,t,n);if((r.ok||"client"!==r.where||"SOCKET_NOT_READY"!==r.value)&&(r.ok||"server"!==r.where||500!==r.value.status)||s++,10===s)return r;if(r.ok||"client"!==r.where){const e=r.value,t=e.status,n=$[t];if("RESOLVE"===n)return this.throttler.resetDelay(),r;if("RETRY"===n)continue;if("DELAY"===n){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===r.value)return A("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==r.value&&("SOCKET_NOT_READY"!==r.value?r.value:yield this.throttler.wait())}return A("SESSION_DESTROYED")}))}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class q{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=g(this.currentDelayMs,.05),n=this.lastCall+t,s=Math.max(0,n-e);return this.lastCall=e+s,this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs),m(s)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function H(e){return e.map((e=>encodeURIComponent(e))).join()}class L{constructor(){this.paths={}}add(e){this.paths[H(e)]=e}delete(e){delete this.paths[H(e)]}has(e){return Object.hasOwnProperty.call(this.paths,H(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach((t=>e(t)))}}class G{constructor(e,t,n){this.handlers=n,this.targetSubscriptions=new L,this.connection=new W(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)}})}call(e,t,n){return this.connection.call(e,t,n)}subscribe(e){return h(this,null,(function*(){return this.targetSubscriptions.add(e),this.connection.call("SUBSCRIBE",e,{})}))}unsubscribe(e){return h(this,null,(function*(){return this.targetSubscriptions.delete(e),this.connection.call("UNSUBSCRIBE",e,{})}))}resubscribe(e){return h(this,null,(function*(){const t=yield this.connection.call("SUBSCRIBE",e,{});t.ok||this.handlers.onResubscribeError(e,t)}))}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}function z(e){return Object.freeze(e)}function J(e){return z(e.map((e=>function(e){switch(e.type){case"text":return Object.freeze({type:"text",children:Y(e.children)});case"file":case"location":return Object.freeze(e)}}(e))))}function Y(e){return z(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(l(u({},e),{children:Y(e.children)}));case"mention":case"autoLink":case"codeSpan":case"customEmoji":return Object.freeze(e)}}(e))))}function Q(e,t){return void 0===t?e:t}function V(e,t){return void 0===t?e:z(t)}function Z(e,t){if(void 0===t)return e;if(null===t)return z({});const n=u({},e);for(const s in t){const e=t[s];null===e?delete n[s]:n[s]=e}return z(n)}function K(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 n=0;n<e.length;n++)if(!K(e[n],t[n]))return!1}else{const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const s of n){if(!Object.hasOwnProperty.call(t,s))return!1;if(!K(e[s],t[s]))return!1}}return!0}class X{constructor(){this.prev=Promise.resolve()}runExclusive(e){return h(this,null,(function*(){const t=this.prev.then((()=>e()));return this.prev=t,t}))}}class ee{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,n;const s=null==(t=this.getPointer)?void 0:t.seq;if(void 0!==s&&e<=s)return!1;const r=null==(n=this.pendingPointer)?void 0:n.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 n=this.mostRecentState.resultPromise.then((e=>e.ok?t(e):e));this.pendingStates.push({seq:e,resultPromise:n})}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 te extends ee{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 ne extends te{constructor(e,t){const n=new Promise((e=>setTimeout(e))).then((()=>this.fetchInitial(e)));super({seq:e,resultPromise:n},t.onTeardown),this.initialSeq=e,this.getDeepMutex=new X,this.lastDeep=void 0}refetchInitial(e){return h(this,null,(function*(){const t=this.mostRecentState.resultPromise,n=this.fetchInitial(e),[s,r]=yield Promise.all([t,n]);return void 0!==s&&s.ok&&r.ok&&this.equal(s.value,r.value)?s:r}))}refetch(e){if(null!==this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.set(t)}changedBetween(e,t){return h(this,null,(function*(){if(e>=t)return!1;const n=this.get(t),s=yield n.resultPromise;return!!s.ok&&(s.value.lastChanged>Math.max(this.initialSeq,e)&&s.value.lastChanged<=t||(yield this.anyChildChanged(e,t,s.value)))}))}getDeep(e){return h(this,null,(function*(){return this.getDeepMutex.runExclusive((()=>h(this,null,(function*(){var t;if(null!==this.error)return this.error;const n=null==(t=this.lastDeep)?void 0:t.seq;if(e===n)return this.lastDeep.deep;if(void 0!==n){if(e<n)throw`Trying to load seq ${e} when we have previously loaded seq ${n}`;if(!(yield this.changedBetween(n,e)))return this.lastDeep.seq=e,this.lastDeep.deep}const s=this.get(e).resultPromise,r=s.then((t=>t.ok?this.loadNested(e,t.value):t));this.lastDeep={seq:e,shallow:s,deep:r};const i=yield r;return i.ok||this.setError(i),i}))))}))}}class se extends ne{constructor(e,t,n){super(e,n),this.emitMutex=t,this.unsubscribeTimer=new re,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive((()=>h(this,null,(function*(){yield this.emit(e)}))))}registerInternalSubscription(){this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,this.startUnsubscribeTimerIfOrphan())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){return this.unsubscribeTimer.stop(),this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult),()=>{this.listeners=this.listeners.filter((t=>t!==e)),this.startUnsubscribeTimerIfOrphan()}}startUnsubscribeTimerIfOrphan(){0===this.referencedByOtherStores&&0===this.listeners.length&&this.unsubscribeTimer.restart((()=>{this.setError(A("UNSUBSCRIBED"))}),this.unsubscribeDebounceMs)}emit(e){return h(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 n=yield this.getDeep(e);n!==this.lastEmitResult&&(this.lastEmitResult=n,this.listeners.forEach((e=>e(n))))}))}}class re{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 ie,ae={};function oe(e,t){const n=t.lastIndex;let s;const r=[];for(;null!==(s=t.exec(e));)r.push(s);return t.lastIndex=n,r}function ue(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function le(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(ie)return ae;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}ie=1,Object.defineProperty(ae,"__esModule",{value:!0}),ae.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},ae.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,n){t(e,Array),e&&e.length>0&&t(e[0],n)},e.optional=function(e,n){void 0!==e&&t(e,n)},e.falsy=function(e){},e.never=function(e){}})(le||(le={}));const ce=le,he=/^\/.*[^\\]\/[im]*$/;function de(e){return!!he.test(e)&&!pe(e).test("")}function pe(e){const t=e.match(/^\/(.*[^\\])\/(.*)$/);if(!t)throw new Error(`Expected ${e} to be a (non-empty) regex`);let n=t[2]||"";return n=n.replace(/[^im]/g,"")+"g",new RegExp(t[1],n)}class fe{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:n,allowedMatches:s,forbiddenMatches:r,suppressLinks:i,suppressEmailAddresses:a,suppressPhoneNumbers:o,replacement:u}){ce.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==i,this.suppressEmailAddresses=!1!==a,this.suppressPhoneNumbers=!1!==o,this.allowedHostnames=t||[],this.allowedPhoneNrs=(n||[]).filter((e=>e)).map((e=>e.replace(/[^0-9]/g,""))),this.allowedMatches=(s||[]).filter(de).map((e=>pe(e))),this.forbiddenMatches=(r||[]).filter(de).map((e=>pe(e))),ce((()=>this.allowedMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),ce((()=>this.forbiddenMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),u=null==u?void 0:u.trim(),this.replacement=u&&u.length>0?u:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function me(e,t){return e.map((e=>function(e,t){if("text"===e.type)return ge(e.children,function(e){var t,n,s,r,i,a,o,u,l,c,h,d,p;let f="";return e.t&&(f=`(${e.t("CONTACT_INFORMATION_HIDDEN")})`),{formattedLinks:null!=(t=e.formattedLinks)?t:"plaintext",markup:null!=(n=e.markup)&&n,useFallbackMentions:null!=(s=e.useFallbackMentions)&&s,sameTabLinkRules:null!=(r=e.sameTabLinkRules)?r:[],enableEmojiImageFallback:null!=(i=e.enableEmojiImageFallback)&&i,highlight:null!=(a=e.highlight)?a:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(u=e.suppression)?u:new fe({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(c=e.contactInfoHiddenText)?c:null==(l=e.suppression)?void 0:l.replacement)?h:f,customEmojiUrls:null!=(d=e.customEmojiUrls)?d:{},enableActions:null==(p=e.enableActions)||p}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${ue(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${ue(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${ue(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,`📎 ${ue(e.url)}`):"location"===e.type?"📍":""}(e,t))).join("\n\n")}function ge(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 ge(e.children,t);case"bulletlist":case"bulletList":return"\n"+ge(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+ge(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 ve(e){return z({id:e.id,name:e.name,custom:z(e.custom),locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage})}function be(e,t){return z({user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt})}function ye(e){const t=Object.entries(e).map((([e,t])=>z({emoji:e,count:t.count,currentUserReacted:t.currentUserReacted})));return t.sort(((e,t)=>e.emoji.localeCompare(t.emoji))),z(t)}class we extends se{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return h(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["users",this.userId],{includePrivateFields:!1},{bypassCache:!0});return t.ok?C({snapshot:ve(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?C({snapshot:null,lastChanged:e}):t}))}equal(e,t){return K(e.snapshot,t.snapshot)}loadNested(e,t){return h(this,null,(function*(){return C(t)}))}userCreated(e,t){this.mutate(e,(n=>null!==n.value.snapshot?n:C({snapshot:ve(t.state),lastChanged:e})))}userEdited(e,t){this.mutate(e,(n=>{const s=n.value.snapshot;return null===s?(console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."),n):C({snapshot:{id:s.id,name:Q(s.name,t.diff.name),custom:Z(s.custom,t.diff.custom),locale:Q(s.locale,t.diff.locale),photoUrl:Q(s.photoUrl,t.diff.photoUrl),role:Q(s.role,t.diff.role),welcomeMessage:Q(s.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})}))}getFromCache(){return h(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?E({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):C({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}}):A("NOT_IN_CACHE")}))}teardownNested(e){}anyChildChanged(e,t,n){return h(this,null,(function*(){return!1}))}}class Ce extends ne{constructor(e,t,n,s){super(e,{}),this.conversationId=t,this.message=n,this.realtimeClient=s}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return h(this,null,(function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"messages",this.message],{},{bypassCache:!0});if(!e.ok)return e;t=e.value.data}return C({lastChanged:e,sender:null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),data:{id:t.id,type:t.type,custom:z(t.custom),createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:me(t.content,{}),content:J(t.content),reactions:ye(t.reactions)}})}))}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 K(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,n){return h(this,null,(function*(){var s;const r=null==(s=n.sender)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))}))}loadNested(e,t){return h(this,null,(function*(){var n,s,r;const i=yield null==(s=null==(n=t.sender)?void 0:n.store)?void 0:s.getDeep(e);if(!1===(null==i?void 0:i.ok))return i;if(null===t.data)return C({snapshot:null});const a=null==i?void 0:i.value;return C({snapshot:z({sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:z(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,(n=>{if(null===n.value.data)return n;const s=n.value.data.content,r=(i=s,void 0===(a=t.diff.content)?i:J(a));var i,a;const o=s===r?n.value.data.plaintext:me(r,{});return C({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:n.value.data.referencedMessageId,editedAt:Q(n.value.data.editedAt,t.diff.editedAt),custom:Z(n.value.data.custom,t.diff.custom),plaintext:o,content:r,reactions:Ae(n.value.data.reactions,t.diff.reactions)}})}))}messageDeleted(e,t){this.mutate(e,(n=>null===n.value.data?n:this.messageId===t.messageId?(this.teardownNested(n.value),C({lastChanged:e,sender:null,data:null})):n.value.data.referencedMessageId===t.messageId?C({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:null,editedAt:n.value.data.editedAt,custom:n.value.data.custom,plaintext:n.value.data.plaintext,content:n.value.data.content,reactions:n.value.data.reactions}}):n))}getFromCache(){return h(this,null,(function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.data)return E({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const n=t.value,{sender:s}=n,r=c(n,["sender"]),i={};return r.data.reactions.forEach((e=>{i[e.emoji]={count:e.count,currentUserReacted:e.currentUserReacted}})),C({status:200,data:l(u({},r.data),{senderId:null!=(e=null==s?void 0:s.store.userId)?e:null,reactions:i})})}))}}function Ae(e,t){if(void 0===t)return e;const n=e.map((e=>{const n=t[e.emoji];return void 0===n?e:z(null===n?l(u({},e),{count:0}):{emoji:e.emoji,count:Q(e.count,n.count),currentUserReacted:Q(e.currentUserReacted,n.currentUserReacted)})})).filter((e=>e.count>0)),s=new Set(n.map((e=>e.emoji)));for(const r in t){const e=t[r];e&&!s.has(r)&&n.push(z({emoji:r,count:e.count,currentUserReacted:e.currentUserReacted}))}return n.sort(((e,t)=>e.emoji.localeCompare(t.emoji))),z(n)}class Ee extends ne{constructor(e,t,n,s){super(e,{}),this.createdAt=t,this.dataStore=n,this.referencedDataStore=s}get messageId(){return this.dataStore.messageId}fetchInitial(e){return h(this,null,(function*(){return C({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,n){return h(this,arguments,(function*(e,t,{dataStore:n,referencedDataStore:s}){return!0===(yield n.changedBetween(e,t))||!0===(yield null==s?void 0:s.changedBetween(e,t))}))}loadNested(e,t){return h(this,null,(function*(){var n,s,r;const i=yield t.dataStore.getDeep(e);if(!i.ok)return i;const a=i.value;if(null===a.snapshot)return C({snapshot:null});const o=yield null==(n=t.referencedDataStore)?void 0:n.getDeep(e);if(o&&!o.ok)return o;const u=null!=(s=null==o?void 0:o.value)?s:null,l=null!=(r=null==u?void 0:u.snapshot)?r:null;return C({snapshot:z({id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:z(a.snapshot.custom),createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:l,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content,reactions:a.snapshot.reactions})})}))}}class ke extends se{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,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._loadMoreMessages(t)}})),super.listen(e)}fetchInitial(e){return h(this,null,(function*(){const t=this.onlyUsedInternally?1:30,n=yield xe({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return n.ok?null===n.value.messages?C({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):Ie({seq:e,messages:n.value.messages,cursor:n.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):n}))}teardownNested(e){if(e.stores){const t=A("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t))),e.inWindow.forEach((e=>e.setError(t)))}}anyChildChanged(e,t,n){return h(this,null,(function*(){for(const s in n.stores){const r=n.stores[s];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1}))}lastMessageChangedBetween(e,t){return h(this,null,(function*(){if(e>=t)return!1;const n=yield this.get(t).resultPromise;if(!n.ok)return!1;if(n.value.lastMessageChanged>e)return!0;if(null===n.value.stores)return!1;const s=n.value.inWindow[0];return void 0!==s&&!0===(yield s.changedBetween(e,t))}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&!!K(e.inWindow.map((e=>e.messageId)),t.inWindow.map((e=>e.messageId)))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return h(this,null,(function*(){if(null===t.stores)return C({snapshot:null,loadedAll:!0});const n=yield Promise.all(t.inWindow.map((t=>t.getDeep(e)))),s=n.find((e=>!e.ok));return s||C({snapshot:z(n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot))),loadedAll:null===t.windowEnd})}))}loadMore(e){return h(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=y();this.pendingLoadMore=t.promise,yield this._loadMoreMessages(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreMessages(e=30){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield xe({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.messages.loadedmore",conversationId:this.conversationId,data:s})}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n: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."),n):Ie({seq:e,prevState:n.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,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.created' event for a nonexistent conversation."),n;if(n.value.windowEnd&&t.state.createdAt<n.value.windowEnd.oldestMessageTs)return n;if(Object.hasOwnProperty.call(n.value.stores,t.state.id))return n;const s=u({},n.value.stores),r=new Ce(e,this.conversationId,t.state,this.realtimeClient);s[t.state.id]=r;const i=t.state.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Ce(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Ee(e,t.state.createdAt,r,a),l=[...n.value.inWindow,o];l.sort(((e,t)=>t.createdAt-e.createdAt));const c=l[0].messageId===t.messageId?e:n.value.lastMessageChanged;return C({lastChanged:e,lastMessageChanged:c,stores:s,inWindow:l,windowEnd:n.value.windowEnd})}))}messageEdited(e,t){this.mutate(e,(n=>{var s;return null===n.value.stores?(console.warn("[TalkJS] Received a 'message.edited' event for a nonexistent conversation."),n):(null==(s=n.value.stores[t.messageId])||s.messageEdited(e,t),n)}))}messageDeleted(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.deleted' event for a conversation that we thought didn't exist."),n;if(Object.values(n.value.stores).forEach((n=>n.messageDeleted(e,t))),void 0===n.value.stores[t.messageId])return n;const s=u({},n.value.stores);delete s[t.messageId];const r=n.value.inWindow.filter((e=>e.messageId!==t.messageId));if(t.newLastMessage&&0===r.length){const n=new Ce(e,this.conversationId,t.newLastMessage,this.realtimeClient);s[n.messageId]=n;const i=t.newLastMessage.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Ce(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Ee(e,t.newLastMessage.createdAt,n,a);r.push(o)}const i=void 0!==t.newLastMessage?e:n.value.lastMessageChanged;return C({lastChanged:e,lastMessageChanged:i,stores:s,inWindow:r,windowEnd:n.value.windowEnd})}))}conversationCleared(e,t){this.mutate(e,(t=>{var n;return 0===(null==(n=t.value.inWindow)?void 0:n.length)&&null===t.value.windowEnd?t:(this.teardownNested(t.value),C({lastChanged:e,lastMessageChanged:e,stores:{},inWindow:[],windowEnd:null}))}))}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.stores?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.stores?t:(this.teardownNested(t.value),C({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getMessageFromCache(e){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.stores)return A("NOT_IN_CACHE");const n=t.value.stores[e];return void 0===n?A("NOT_IN_CACHE"):n.getFromCache()}))}}function xe(e){return h(this,arguments,(function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call("GET",["me","conversations",n,"messages"],r,{bypassCache:!0});if(i.ok){const{data:e,cursor:t}=i.value.data;return C({messages:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?C({messages:null,nextCursor:null}):i}))}function Ie({seq:e,prevState:t,messages:n,cursor:s,conversationId:r,realtimeClient:i}){var a,o,l,c;const h=t?u({},t.stores):{};for(const u of n)if(void 0===h[u.id]){const t=new Ce(e,r,u,i);h[t.messageId]=t}for(const u of n){const t=u.referencedMessageId;if(t&&void 0===h[t]){const n=new Ce(e,r,t,i);h[n.messageId]=n}}const d=t?[...t.inWindow]:[];for(const u of n)d.push(new Ee(e,u.createdAt,h[u.id],u.referencedMessageId?h[u.referencedMessageId]:null));d.sort(((e,t)=>t.createdAt-e.createdAt));const p=(null==(o=null==(a=null==t?void 0:t.inWindow)?void 0:a[0])?void 0:o.messageId)===(null==(l=null==d?void 0:d[0])?void 0:l.messageId)&&null!=(c=null==t?void 0:t.lastMessageChanged)?c:e;return C(null===s?{lastChanged:e,lastMessageChanged:p,stores:h,inWindow:d,windowEnd:null}:{lastChanged:e,lastMessageChanged:p,stores:h,inWindow:d,windowEnd:{cursor:s,oldestMessageTs:n[n.length-1].createdAt}})}class Te extends se{constructor(e,t,n,s,r){super(e,s,r),this.convData=t,this.realtimeClient=n,this.unsubscribeDebounceMs=0}fetchInitial(e){return h(this,null,(function*(){return C({lastChanged:e,convData:this.convData})}))}teardownNested(e){e.convData.unsubscribe()}anyChildChanged(e,t,n){return h(this,null,(function*(){return n.convData.store.changedBetween(e,t)}))}equal(e,t){return!0}loadNested(e,t){return h(this,null,(function*(){return t.convData.store.getDeep(e)}))}getFromCache(){return h(this,null,(function*(){return this.convData.store.getFromCache()}))}}function De(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(e[n],n)}function Se(e,t){return function(e){let n={};return De(e,((e,s)=>{const[r,i]=(([e,n])=>[e,t(n,e)])([s,e],0);n[r]=i})),n}(e)}class Me extends se{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return h(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"typing"],{},{bypassCache:!0});if(!t.ok&&"server"===t.where&&404===t.value.status)return C({data:null,lastChanged:e});if(!t.ok&&"server"===t.where&&403===t.value.status&&"NOT_A_PARTICIPANT"===t.value.errorCode)return C({data:null,lastChanged:e});if(!t.ok)return t;const n=t.value.data;return n.many?C({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e}):C({data:n,userSubscriptions:Se(n.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t]))),lastChanged:e})}))}equal(e,t){return K(e.data,t.data)}loadNested(e,t){return h(this,null,(function*(){if(null===t.data)return C({snapshot:null,lastChanged:t.lastChanged});if(t.data.many)return C({snapshot:z({many:!0}),lastChanged:t.lastChanged});const n=Object.entries(t.data.usersTyping).sort((([e,t],[n,s])=>t-s)).map((([e,t])=>e)).map((n=>t.userSubscriptions[n].store.getDeep(e))),s=yield Promise.all(n),r=s.find((e=>!e.ok));if(r)return r;const i=s.map((e=>e.value)),a=i.map((e=>e.snapshot)),o=i.map((e=>e.lastChanged)),u=Math.max(t.lastChanged,...o);return C({snapshot:z({users:z(a),many:!1}),lastChanged:u})}))}typingAvailable(e,t){this.mutate(e,(()=>C({data:t.state,userSubscriptions:t.state.many?{}:Se(t.state.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t]))),lastChanged:e})))}typingChanged(e,t){this.mutate(e,(n=>{if(null===n.value.data)return n;if(void 0===t.diff.many){if(!0===n.value.data.many)return n;const s=u({},n.value.data.usersTyping),r=u({},n.value.userSubscriptions);return De(t.diff.usersTyping,((e,t)=>{var n;"number"==typeof e?(s[t]=e,r[t]=this.realtimeClient.internalSubscribe(["users",t])):null===e&&(delete s[t],null==(n=r[t])||n.unsubscribe(),delete r[t])})),C({data:{usersTyping:s,many:!1},userSubscriptions:r,lastChanged:e})}if(!0===t.diff.many)return n.value.data.many?n:C({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e});if(!1===t.diff.many){if(!1===n.value.data.many)return n;const s=Se(t.diff.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t])));return C({data:t.diff,userSubscriptions:s,lastChanged:e})}throw t.diff,"Unreachable"}))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:C({data:null,lastChanged:e})))}teardownNested(e){e.data&&De(e.userSubscriptions,(e=>e.unsubscribe()))}anyChildChanged(e,t,n){return h(this,null,(function*(){var s;if(null===n.data)return!1;for(const r in n.userSubscriptions){const i=n.userSubscriptions[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1}))}}class Fe extends ne{constructor(e,t,n,s){super(e,{}),this.conversationId=t,this.participantData=n,this.realtimeClient=s}fetchInitial(e){return h(this,null,(function*(){return C({lastChanged:e,user:this.realtimeClient.internalSubscribe(["users",this.participantData.id]),data:this.participantData})}))}refetch(e){throw"Do not call refetch on participant data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){var n,s,r,i;return(null==(s=null==(n=e.user)?void 0:n.store)?void 0:s.userId)===(null==(i=null==(r=t.user)?void 0:r.store)?void 0:i.userId)&&K(e.data,t.data)}teardownNested(e){var t;null==(t=e.user)||t.unsubscribe()}anyChildChanged(e,t,n){return h(this,null,(function*(){var s;const r=null==(s=n.user)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))}))}loadNested(e,t){return h(this,null,(function*(){if(null===t.data)return C({snapshot:null});const n=yield t.user.store.getDeep(e);if(!1===n.ok)return n;const s=n.value.snapshot;return C({snapshot:be(t.data,s)})}))}participantEdited(e,t){this.mutate(e,(n=>null===n.value.data?n:C({lastChanged:e,user:n.value.user,data:{id:n.value.data.id,access:Q(n.value.data.access,t.diff.access),notify:Q(n.value.data.notify,t.diff.notify),joinedAt:n.value.data.joinedAt}})))}participantDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:(this.teardownNested(t.value),C({lastChanged:e,user:null,data:null}))))}getFromCache(){return h(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.data?E({status:404,errorCode:"PARTICIPANT_NOT_FOUND",reasons:["No participant with that ID exists"]}):C({status:200,data:e.value.data}):A("NOT_IN_CACHE")}))}}class Be extends se{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}fetchInitial(e){return h(this,null,(function*(){const t=yield Re({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:10});return t.ok?null===t.value.participants?C({lastChanged:e,stores:null,inWindow:null,windowEnd:null}):Ne({seq:e,participants:t.value.participants,cursor:t.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t}))}teardownNested(e){if(e.stores){const t=A("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t)))}}anyChildChanged(e,t,n){return h(this,null,(function*(){for(const s in n.stores){const r=n.stores[s];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return h(this,null,(function*(){if(null===t.stores)return C({snapshot:null,loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map((t=>t.getDeep(e)))),s=n.find((e=>!e.ok));if(s)return s;const r=n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot));return r.sort(((e,t)=>t.joinedAt-e.joinedAt)),C({snapshot:z(r),loadedAll:null===t.windowEnd})}))}loadMore(e){return h(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=y();this.pendingLoadMore=t.promise,yield this._loadMoreParticipants(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreParticipants(e=10){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield Re({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.participants.loadedmore",conversationId:this.conversationId,data:s})}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.participants?(console.warn("[TalkJS] When loading more participants, the conversation no longer existed. We should have been told about this."),n):Ne({seq:e,prevStores:n.value.stores,participants:t.data.value.participants,cursor:t.data.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t.data))}participantCreated(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'participant.created' event for a nonexistent conversation."),n;if(n.value.windowEnd&&t.state.joinedAt<n.value.windowEnd.oldestParticipantTs)return n;if(Object.hasOwnProperty.call(n.value.stores,t.state.id))return n;const s=u({},n.value.stores),r=new Fe(e,this.conversationId,t.state,this.realtimeClient);return s[t.state.id]=r,C({lastChanged:e,stores:s,windowEnd:n.value.windowEnd})}))}participantEdited(e,t){this.mutate(e,(n=>{var s;return null===n.value.stores?(console.warn("[TalkJS] Received a 'participant.edited' event for a nonexistent conversation."),n):(null==(s=n.value.stores[t.userId])||s.participantEdited(e,t),n)}))}participantDeleted(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'participant.deleted' event for a conversation that we thought didn't exist."),n;const s=n.value.stores[t.userId];if(void 0===s)return n;s.participantDeleted(e,t);const r=u({},n.value.stores);return delete r[t.userId],C({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})}))}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.stores?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.stores?t:(this.teardownNested(t.value),C({lastChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getParticipantFromCache(e){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.stores)return A("NOT_IN_CACHE");const n=t.value.stores[e];return void 0===n?A("NOT_IN_CACHE"):n.getFromCache()}))}}function Re(e){return h(this,arguments,(function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call("GET",["me","conversations",n,"participants"],r,{bypassCache:!0});if(i.ok){const{data:e,cursor:t}=i.value.data;return C({participants:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?C({participants:null,nextCursor:null}):i}))}function Ne({seq:e,prevStores:t,participants:n,cursor:s,conversationId:r,realtimeClient:i}){const a=t?u({},t):{};for(const o of n)if(void 0===a[o.id]){const t=new Fe(e,r,o,i);a[o.id]=t}return C(null===s?{lastChanged:e,stores:a,windowEnd:null}:{lastChanged:e,stores:a,windowEnd:{cursor:s,oldestParticipantTs:n[n.length-1].joinedAt}})}class Oe extends se{constructor(e,t,n,s,r){super(e,s,r),this.getConvDataStore=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}fetchInitial(e){return h(this,null,(function*(){const t=yield _e({realtimeClient:this.realtimeClient,count:20});return t.ok?null===t.value.conversations?C({lastChanged:e,stores:null,windowEnd:null}):Pe({seq:e,conversations:t.value.conversations,cursor:t.value.nextCursor,getConvDataStore:this.getConvDataStore}):t}))}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach((e=>e.unsubscribe()))}anyChildChanged(e,t,n){return h(this,null,(function*(){var s;for(const r in n.stores){const i=n.stores[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return h(this,null,(function*(){if(null===t.stores)return C({snapshot:z([]),loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map((t=>t.store.getDeep(e)))),s=n.find((e=>!e.ok));if(s)return s;const r=n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot));return r.sort(((e,t)=>{var n,s,r,i;const a=null!=(s=null==(n=e.lastMessage)?void 0:n.createdAt)?s:e.joinedAt;return(null!=(i=null==(r=t.lastMessage)?void 0:r.createdAt)?i:t.joinedAt)-a})),C({snapshot:z(r),loadedAll:null===t.windowEnd})}))}loadMore(e){return h(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=y();this.pendingLoadMore=t.promise,yield this._loadMoreConversations(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreConversations(e=20){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield _e({count:e,cursor:n,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.conversations.loadedmore",data:s})}))}getConvFromCache(e){return h(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.stores)return E({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const n=t.value.stores[e];return void 0===n?A("NOT_IN_CACHE"):n.store.getFromCache()}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.conversations?(console.warn("[TalkJS] When loading more conversations, the user stopped existing, which should be impossible."),n):Pe({seq:e,prevStores:n.value.stores,conversations:t.data.value.conversations,cursor:t.data.value.nextCursor,getConvDataStore:this.getConvDataStore}):t.data))}userCreated(e,t){this.mutate(e,(e=>null!==e.value.stores?e:C({lastChanged:e.value.lastChanged,stores:{},windowEnd:null})))}sideCreated(e,t){const n=this.getConvDataStore(t.state);this.mutate(e,(s=>{let r=s.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'side.created' event when we thought your user didn't exist."),r={}),Object.hasOwnProperty.call(r,t.conversationId)?(n.unsubscribe(),s):C({lastChanged:e,stores:l(u({},r),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})}))}sideDeleted(e,t){this.mutate(e,(n=>{var s;if(!Object.hasOwnProperty.call(n.value.stores,t.conversationId))return n;const r=u({},n.value.stores);return null==(s=r[t.conversationId])||s.unsubscribe(),delete r[t.conversationId],C({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})}))}sideEdited(e,t){const n=t.diff.lastMessageAt;void 0!==n&&this.mutate(e,(s=>{var r;if(null===s.value.stores)return console.warn("[TalkJS] Received a 'side.edited' event when we thought your user didn't exist."),s;if(null===s.value.windowEnd)return s;const i=Object.hasOwnProperty.call(s.value.stores,t.conversationId);if(i&&n<s.value.windowEnd.oldestMessageTs){const n=u({},s.value.stores);return null==(r=n[t.conversationId])||r.unsubscribe(),delete n[t.conversationId],C({lastChanged:e,stores:n,windowEnd:s.value.windowEnd})}if(!i&&n>=s.value.windowEnd.oldestMessageTs){const n=this.getConvDataStore(t.conversationId);return C({lastChanged:e,stores:l(u({},s.value.stores),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})}return s}))}}function _e(e){return h(this,arguments,(function*({cursor:e,realtimeClient:t,count:n}){const s={limit:n,cursor:e},r=yield t.call("GET",["me","conversations"],s,{bypassCache:!0});if(r.ok){const{data:e,cursor:t}=r.value.data;return C({conversations:e,nextCursor:t})}return r.ok||"server"!==r.where||404!==r.value.status||"USER_NOT_FOUND"!==r.value.errorCode?r:C({conversations:null,nextCursor:null})}))}function Pe({seq:e,prevStores:t,conversations:n,cursor:s,getConvDataStore:r}){const i=t?u({},t):{};for(const a of n)void 0===i[a.id]&&(i[a.id]=r(a));return C(null===s?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:s,oldestMessageTs:Math.min(...n.map((e=>e.lastMessageAt)))}})}class je extends se{constructor(e,t,n,s,r){super(e,s,r),this.conversation=t,this.realtimeClient=n,this.unsubscribeDebounceMs=5e3}get conversationId(){return"string"==typeof this.conversation?this.conversation:this.conversation.id}fetchInitial(e){return h(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]);if("object"==typeof this.conversation)return C({lastChanged:e,snapshot:this.conversation,messageWindow:t});const n=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId],{},{bypassCache:!0});let s;if(n.ok)s=n.value.data;else if("server"===n.where&&404===n.value.status)s=null;else{if("server"!==n.where||403!==n.value.status||"NOT_A_PARTICIPANT"!==n.value.errorCode)return t.unsubscribe(),n;s=null}return C({lastChanged:e,snapshot:s,messageWindow:t})}))}teardownNested(e){var t;null==(t=e.messageWindow)||t.unsubscribe()}anyChildChanged(e,t,n){return h(this,null,(function*(){return!0===(yield n.messageWindow.store.lastMessageChangedBetween(e,t))}))}equal(e,t){return K(e.snapshot,t.snapshot)}loadNested(e,t){return h(this,null,(function*(){var n;if(!t.snapshot)return C({snapshot:null,loadedAll:!0});const s=yield t.messageWindow.store.getDeep(e);if(!s.ok)return s;const r=s.value.snapshot,i=null!=(n=null==r?void 0:r[0])?n:null;return C({snapshot:z(l(u({},t.snapshot),{custom:z(t.snapshot.custom),welcomeMessages:z(t.snapshot.welcomeMessages),lastMessage:i}))})}))}participantEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'participant.edited' event for a conversation that we thought didn't exist."),n):C({lastChanged:e,snapshot:Ue(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}conversationEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'conversation.edited' event for a conversation that we thought didn't exist."),n):C({lastChanged:e,snapshot:Ue(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}sideEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'side.edited' event for a conversation that we thought didn't exist."),n):C({lastChanged:e,snapshot:Ue(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}sideCreated(e,t){this.mutate(e,(n=>n.value.snapshot?n:C({lastChanged:e,snapshot:t.state,messageWindow:n.value.messageWindow})))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.snapshot?t:C({lastChanged:e,snapshot:null,messageWindow:t.value.messageWindow})))}getFromCache(){return h(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok&&e.value.snapshot?C({status:200,data:e.value.snapshot}):A("NOT_IN_CACHE")}))}}function Ue(e,t){const n=t;return{id:e.id,createdAt:e.createdAt,subject:Q(e.subject,n.subject),photoUrl:Q(e.photoUrl,n.photoUrl),welcomeMessages:V(e.welcomeMessages,n.welcomeMessages),custom:Z(e.custom,n.custom),lastMessageAt:Q(e.lastMessageAt,n.lastMessageAt),unreadMessageCount:Q(e.unreadMessageCount,n.unreadMessageCount),isUnread:Q(e.isUnread,n.isUnread),access:Q(e.access,n.access),notify:Q(e.notify,n.notify),readUntil:Q(e.readUntil,n.readUntil),everyoneReadUntil:Q(e.everyoneReadUntil,n.everyoneReadUntil),joinedAt:e.joinedAt}}class $e extends se{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e3}fetchInitial(e){return h(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]),n=yield this.realtimeClient.call("GET",["users",this.userId,"online"],{},{bypassCache:!0});return n.ok||"server"!==n.where||404!==n.value.status||"USER_NOT_FOUND"!==n.value.errorCode?n.ok?C({lastChanged:e,user:t,data:n.value.data}):n:C({lastChanged:e,user:t,data:null})}))}equal(e,t){return K(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,n){return h(this,null,(function*(){return n.user.store.changedBetween(e,t)}))}loadNested(e,t){return h(this,null,(function*(){const n=yield t.user.store.getDeep(e);if(!n.ok)return n;const s=n.value.snapshot;return null===t.data||null===s?C({snapshot:null}):C({snapshot:z(l(u({},t.data),{user:s}))})}))}userCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.data?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}userOnlineChanged(e,t){this.mutate(e,(n=>null===n.value.data?n:C({lastChanged:e,user:n.value.user,data:t.diff})))}getFromCache(){return h(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;if(!e.ok)return A("NOT_IN_CACHE");if(null===e.value.data)return E({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const t=e.value,{user:n}=t,s=c(t,["user"]);return C({status:200,data:u({},s.data)})}))}}class We{constructor(e,t,n){this.realtimeClient=n,this.convDataStores={},this.storeMap={},this.emitMutex=new X,this.virtualSeqOffset=0,this.realPublishSeq=0,this.refetchOnNextNetworkLoss=!0,this.connection=new G(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.virtualSeqOffset+=this.realPublishSeq,this.realPublishSeq=0,this.refetchOnNextNetworkLoss){this.virtualSeqOffset++;const e=this.virtualSeq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var n;null==(n=this.storeMap[qe(e)])||n.setError(t)},onPublish:(e,t)=>{this.realPublishSeq=e;const n=this.virtualSeq;for(const s of t)this.handlePublish(n,s);this.emitAll(n)}})}get virtualSeq(){return this.realPublishSeq+this.virtualSeqOffset}refetchAll(e){Object.values(this.storeMap).forEach((t=>null==t?void 0:t.refetch(e)))}emitAll(e){return this.emitMutex.runExclusive((()=>h(this,null,(function*(){const t=Object.values(this.storeMap).map((t=>null==t?void 0:t.emit(e)));yield Promise.all(t)}))))}handlePublish(e,t){var n,s,r,i,a,o,u,l,c,h,d,p,f,m,g,v,b,y,w,C,A,E,k,x,I,T,D,S,M,F;switch(t.type){case"user.created":return null==(n=this.storeMap[`/users/${t.userId}`])||n.userCreated(e,t),null==(s=this.storeMap["/me/conversations"])||s.userCreated(e,t),void(null==(r=this.storeMap[`/users/${t.userId}/online`])||r.userCreated(e,t));case"user.edited":return void(null==(i=this.storeMap[`/users/${t.userId}`])||i.userEdited(e,t));case"side.created":return null==(a=this.convDataStores[t.conversationId])||a.sideCreated(e,t),null==(o=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||o.sideCreated(e,t),null==(u=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||u.sideCreated(e,t),void(null==(l=this.storeMap["/me/conversations"])||l.sideCreated(e,t));case"side.edited":return null==(c=this.convDataStores[t.conversationId])||c.sideEdited(e,t),void(null==(h=this.storeMap["/me/conversations"])||h.sideEdited(e,t));case"side.deleted":return null==(d=this.convDataStores[t.conversationId])||d.sideDeleted(e,t),null==(p=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||p.sideDeleted(e,t),null==(f=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||f.sideDeleted(e,t),null==(m=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||m.sideDeleted(e,t),void(null==(g=this.storeMap["/me/conversations"])||g.sideDeleted(e,t));case"conversation.edited":return void(null==(v=this.convDataStores[t.conversationId])||v.conversationEdited(e,t));case"message.created":return void(null==(b=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||b.messageCreated(e,t));case"message.edited":return void(null==(y=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||y.messageEdited(e,t));case"message.deleted":return void(null==(w=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||w.messageDeleted(e,t));case"typing.available":return void(null==(C=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||C.typingAvailable(e,t));case"typing.changed":return void(null==(A=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||A.typingChanged(e,t));case"conversation.cleared":return void(null==(E=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||E.conversationCleared(e,t));case"participant.edited":return null==(k=this.convDataStores[t.conversationId])||k.participantEdited(e,t),void(null==(x=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||x.participantEdited(e,t));case"participant.created":return void(null==(I=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||I.participantCreated(e,t));case"participant.deleted":return void(null==(T=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||T.participantDeleted(e,t));case"user.online.changed":return void(null==(D=this.storeMap[`/users/${t.userId}/online`])||D.userOnlineChanged(e,t));case"virtual.conversations.loadedmore":return void(null==(S=this.storeMap["/me/conversations"])||S.loadedMore(e,t));case"virtual.messages.loadedmore":return void(null==(M=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||M.loadedMore(e,t));case"virtual.participants.loadedmore":return void(null==(F=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||F.loadedMore(e,t))}}call(e,t,n,s){return h(this,null,(function*(){if(!s.bypassCache&&"GET"===e){const e=qe(t);if(e in this.storeMap){const t=e,n=this.storeMap[t];if(n&&"getFromCache"in n){const e=yield n.getFromCache();if("NOT_IN_CACHE"!==e.value)return e}}else if(f(t,["me","conversations","*","messages","*"])){const e=this.storeMap[`/me/conversations/${t[2]}/messages`];if(e){const n=yield e.getMessageFromCache(t[4]);if("NOT_IN_CACHE"!==n.value)return n}}else if(f(t,["me","conversations","*","participants","*"])){const e=this.storeMap[`/me/conversations/${t[2]}/participants`];if(e){const n=yield e.getParticipantFromCache(t[4]);if("NOT_IN_CACHE"!==n.value)return n}}else if(f(t,["me","conversations","*"])){const e=this.storeMap["/me/conversations"];if(e){const n=yield e.getConvFromCache(t[2]);if("NOT_IN_CACHE"!==n.value)return n}}}return this.connection.call(e,t,n)}))}subscribe(e,t){const n=this.getOrCreateStore(e),s=y(),r=y();s.promise.catch((()=>{})),r.promise.catch((()=>{}));const i={state:{type:"pending",latestSnapshot:void 0},connected:s.promise,terminated:r.promise,loadMore:e=>h(this,null,(function*(){"loadMore"in n&&(yield n.loadMore(e))})),unsubscribe:()=>{}},a=n.listen((n=>{if(n.ok){const e=!("loadedAll"in n.value)||n.value.loadedAll,r={type:"active",latestSnapshot:n.value.snapshot,loadedAll:e};i.state=r,null==t||t(n.value.snapshot,e),s.resolve(r)}else if("pending"===i.state.type||"active"===i.state.type){if("server"===n.where){const t={type:"error",error:new Error(p(`Subscribe to ${e.join("/")}`,n.value))};return i.state=t,r.resolve(t),void s.reject("Subscription encountered an error during initial connection")}if("SESSION_DESTROYED"===n.value){const e={type:"error",error:new Error("Session was destroyed causing all subscriptions to be terminated")};return i.state=e,r.resolve(e),void s.reject("Subscription encountered an error during initial connection")}if("UNSUBSCRIBED"===n.value)return;if("TERMINATED"===n.value)return;n.value}}));return i.unsubscribe=()=>{if("pending"===i.state.type||"active"===i.state.type){a();const e={type:"unsubscribed"};i.state=e,r.resolve(e),s.reject("Subscription was unsubscribed before connecting")}},i}onVirtualPublish(e){return h(this,null,(function*(){this.virtualSeqOffset++;const t=this.virtualSeq;this.handlePublish(t,e),yield this.emitAll(t)}))}getOrCreateStore(e){const t=qe(e);if(t in this.storeMap)return this.storeMap[t];this.connection.subscribe(e).then((e=>{e.ok||n.setError(e)}));const n=this.instantiateStore(e,(()=>{delete this.storeMap[t],this.connection.unsubscribe(e)}));return this.storeMap[t]=n,n}destroy(){this.storeMap={},this.convDataStores={},this.connection.destroy()}isConnected(){return this.connection.isConnected()}instantiateStore(e,t){if(f(e,["users","*"]))return new we(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});if(f(e,["me","conversations","*"]))return new Te(this.virtualSeq,this.subscribeConvData(e[2]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(f(e,["me","conversations","*","messages"]))return new ke(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(f(e,["me","conversations","*","participants"]))return new Be(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(f(e,["me","conversations","*","typing"]))return new Me(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t});if(f(e,["me","conversations"]))return new Oe(this.virtualSeq,(e=>this.subscribeConvData(e)),this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(f(e,["users","*","online"]))return new $e(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});throw"Unreachable"}subscribeConvData(e){const t="string"==typeof e?e:e.id;if(Object.hasOwnProperty.call(this.convDataStores,t)){const e=this.convDataStores[t];return{store:e,unsubscribe:e.registerInternalSubscription()}}const n=new je(this.virtualSeq,e,this.realtimeClient,this.emitMutex,{onTeardown:()=>{delete this.convDataStores[t]}});return this.convDataStores[t]=n,{store:n,unsubscribe:n.registerInternalSubscription()}}}function qe(e){return`/${e.join("/")}`}class He{constructor(e,t,n){this.userId=t,this.alive=!0,this.connection=new We(e,n,this),n.onTokenRefreshFailed((()=>{this.destroy()}))}call(e,t,n){return h(this,arguments,(function*(e,t,n,s={}){return this.alive?this.connection.call(e,t,n,s):A("SESSION_DESTROYED")}))}subscribe(e,t){return this.connection.subscribe(e,t)}internalSubscribe(e){const t=this.connection.getOrCreateStore(e);return{store:t,unsubscribe:t.registerInternalSubscription()}}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}listMessages(e,t){return h(this,null,(function*(){const n=yield this.call("GET",["me","conversations",e,"messages"],t);if(!n.ok)return Le(n,"Listing messages in "+e);const s=n.value.data.data,r=yield Promise.all(s.map((t=>this.hydrateMessageData(t,e)))),i=r.find((e=>!e.ok));return void 0===i||i.ok?C(r.map((({value:e})=>e))):i}))}hydrateMessageData(e,t){return h(this,null,(function*(){const n=null===e.senderId?Promise.resolve(C(null)):this.getUser(e.senderId),s=null===e.referencedMessageId?Promise.resolve(C(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield n;if(!r.ok)return r;const i=yield s;if(!i.ok)return i;var a,o,u;return C((a=e,o=r.value,u=i.value,z({id:a.id,type:a.type,sender:o,referencedMessage:u,custom:z(a.custom),createdAt:a.createdAt,editedAt:a.editedAt,origin:a.origin,content:a.content,reactions:ye(a.reactions),plaintext:me(a.content,{})})))}))}getReferencedMessage(e,t){return h(this,null,(function*(){const n=yield this.call("GET",["me","conversations",e,"messages",t],{});if(!n.ok&&"server"===n.where&&404===n.value.status)return C(null);if(!n.ok&&"server"===n.where&&403===n.value.status&&"NOT_A_PARTICIPANT"===n.value.errorCode)return C(null);if(!n.ok)return Le(n,`Fetching referenced message ${t} in conversation ${e}`);const s=n.value.data,r=yield this.getUser(s.senderId);if(!r.ok)return r;var i,a;return C((i=s,a=r.value,z({id:i.id,type:i.type,sender:a,referencedMessageId:i.referencedMessageId,custom:z(i.custom),createdAt:i.createdAt,editedAt:i.editedAt,origin:i.origin,content:i.content,reactions:ye(i.reactions),plaintext:me(i.content,{})})))}))}getUser(e){return h(this,null,(function*(){const t=yield this.call("GET",["users",e],{includePrivateFields:!1});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?C(ve(t.value.data)):Le(t,"Get user "+e):C(null)}))}}function Le(e,t){return"server"===e.where?E(l(u({},e.value),{operation:t})):e}function Ge(e,t){var n;if(t.ok)return t.value;throw"SESSION_DESTROYED"===t.value?new Error(`${e} failed because the session was destroyed`):new Error(p(null!=(n=t.value.operation)?n:e,t.value))}class ze{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return h(this,null,(function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return Ge("Get user "+this.id,e)}))}set(e){return h(this,null,(function*(){null===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call("PUT",["users",this.brandedId],l(u({},e),{email:t,phone:n}));d("Set user "+this.id,s)}))}createIfNotExists(e){return h(this,null,(function*(){void 0===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call("POST",["users",this.brandedId],l(u({},e),{email:t,phone:n}));(s.ok||"server"!==s.where||409!=s.value.status)&&d(`Create user ${this.id} if not exists`,s)}))}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}subscribeOnline(e){return this._realtimeClient.subscribe(["users",this.brandedId,"online"],e)}}class Je{constructor(e,t,n){this.userId=e,this.conversationId=t,this._realtimeClient=n}get brandedUserId(){return this.userId}get brandedConversationId(){return this.conversationId}get(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],{}),t=yield this._realtimeClient.call("GET",["users",this.brandedUserId],{includePrivateFields:!1}),[n,s]=yield Promise.all([e,t]);return(n.ok||"server"!==n.where||404!==n.value.status)&&(s.ok||"server"!==s.where||404!==s.value.status)?be(d(`Get participant ${this.userId} in conversation ${this.conversationId}`,n),ve(d(`Get user ${this.userId}`,s))):null}))}set(){return h(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);d(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)}))}edit(){return h(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);d(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)}))}createIfNotExists(){return h(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("POST",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);(t.ok||"server"!==t.where||409!==t.value.status)&&d(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)}))}delete(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"participants",this.brandedUserId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&d(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)}))}}function Ye(e){const t="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let n=0;const s=[],r=e===n;n=e;const i=new Array(8);for(let o=7;o>=0;o--)i[o]=t.charAt(e%64),e=Math.floor(e/64);if(0!==e)throw new Error("We should have converted the entire timestamp.");let a=i.join("");if(r){let e;for(e=11;e>=0&&63===s[e];e--)s[e]=0;s[e]++}else for(let o=0;o<12;o++)s[o]=Math.floor(64*Math.random());for(let o=0;o<12;o++)a+=t.charAt(s[o]);if(20!=a.length)throw new Error("Length should be 20.");return a}const Qe=(e,t,n=void 0)=>e.reduce(((e,s,r)=>e.concat((e=>{if("string"==typeof e)return t(e,n);switch(e.type){case"bold":case"italic":case"strikethrough":case"blockquote":case"bulletlist":case"bulletList":case"bulletpoint":case"bulletPoint":return[{type:e.type,children:Qe(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:Qe(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:Qe(e.children,t,e.type)}];case"mention":case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"suppressed":case"emoji":case"customemoji":case"customEmoji":return[e]}})(s))),[]);function Ve(e,t){return n=>{const s=n;let r=0;const i=[];for(const a of oe(n,e)){a.index-r>0&&i.push(s.substring(r,a.index));const e=t(a);Array.isArray(e)?i.push(...e):i.push(e),r=a.index+a[0].length}return r<n.length&&i.push(n.substring(r)),i}}const Ze="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Ke,Xe=((Ke=Xe||{})[Ke.italic=1]="italic",Ke[Ke.strikethrough=2]="strikethrough",Ke[Ke.bold=4]="bold",Ke);const et=[0,1,2,3,4,5,6].map((e=>{const t=[];return 1&e||t.push(/_([^\s_].*?[^\s_])_|_([^\s_])_/),2&e||t.push(/~([^\s~].*?[^\s~])~|~([^\s~])~/),4&e||t.push(/\*([^\s*].*?[^\s*])\*|\*([^\s*])\*/),new RegExp(t.map((e=>e.source)).join("|"),"g")})),tt={_:1,"*":4,"~":2};function nt(e){return st(e,0)}function st(e,t=0){const n=et[t],s=n?function(e){const t=Ve(rt.getOrCompute(e,(()=>new RegExp(`(?:^|[\\s${Ze}])(?:${e.source})(?=[\\s${Ze}]|$)`,"g"))),(e=>{const t=e[0][1],n=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:Xe[tt[t]],children:[n]}]}));return e=>{const[n,...s]=t(" "+e);return n.length>1&&s.unshift(n.substring(1)),s}}(n):()=>[e];return Qe(s(e),((e,n)=>"bold"===n||"italic"===n||"strikethrough"===n?st(e,t|Xe[n]):[e]))}const rt=function(){const e=function(){try{return new WeakMap}catch(e){const t={has:()=>!1,get:()=>{},set:()=>t};return t}}();return{getOrCompute(t,n){if(e.has(t))return e.get(t);const s=n();return e.set(t,s),s}}}();function it(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var n=0,s=e.length;n<s;n++)if(e[n]===t)return n;return-1}function at(e,t){for(var n=e.length-1;n>=0;n--)!0===t(e[n])&&e.splice(n,1)}function ot(e){throw new Error("Unhandled case for value: '"+e+"'")}var ut=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.whitespaceRegex=/\s+/,this.tagName=e.tagName||"",this.attrs=e.attrs||{},this.innerHTML=e.innerHtml||e.innerHTML||""}return e.prototype.setTagName=function(e){return this.tagName=e,this},e.prototype.getTagName=function(){return this.tagName||""},e.prototype.setAttr=function(e,t){return this.getAttrs()[e]=t,this},e.prototype.getAttr=function(e){return this.getAttrs()[e]},e.prototype.setAttrs=function(e){return Object.assign(this.getAttrs(),e),this},e.prototype.getAttrs=function(){return this.attrs||(this.attrs={})},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,n=this.getClass(),s=this.whitespaceRegex,r=n?n.split(s):[],i=e.split(s);t=i.shift();)-1===it(r,t)&&r.push(t);return this.getAttrs().class=r.join(" "),this},e.prototype.removeClass=function(e){for(var t,n=this.getClass(),s=this.whitespaceRegex,r=n?n.split(s):[],i=e.split(s);r.length&&(t=i.shift());){var a=it(r,t);-1!==a&&r.splice(a,1)}return this.getAttrs().class=r.join(" "),this},e.prototype.getClass=function(){return this.getAttrs().class||""},e.prototype.hasClass=function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},e.prototype.setInnerHTML=function(e){return this.innerHTML=e,this},e.prototype.setInnerHtml=function(e){return this.setInnerHTML(e)},e.prototype.getInnerHTML=function(){return this.innerHTML||""},e.prototype.getInnerHtml=function(){return this.getInnerHTML()},e.prototype.toAnchorString=function(){var e=this.getTagName(),t=this.buildAttrsStr();return["<",e,t=t?" "+t:"",">",this.getInnerHtml(),"</",e,">"].join("")},e.prototype.buildAttrsStr=function(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n+'="'+e[n]+'"');return t.join(" ")},e}(),lt=function(){function e(e){void 0===e&&(e={}),this.newWindow=!1,this.truncate={},this.className="",this.newWindow=e.newWindow||!1,this.truncate=e.truncate||{},this.className=e.className||""}return e.prototype.build=function(e){return new ut({tagName:"a",attrs:this.createAttrs(e),innerHtml:this.processAnchorText(e.getAnchorText())})},e.prototype.createAttrs=function(e){var t={href:e.getAnchorHref()},n=this.createCssClass(e);return n&&(t.class=n),this.newWindow&&(t.target="_blank",t.rel="noopener noreferrer"),this.truncate&&this.truncate.length&&this.truncate.length<e.getAnchorText().length&&(t.title=e.getAnchorHref()),t},e.prototype.createCssClass=function(e){var t=this.className;if(t){for(var n=[t],s=e.getCssClassSuffixes(),r=0,i=s.length;r<i;r++)n.push(t+"-"+s[r]);return n.join(" ")}return""},e.prototype.processAnchorText=function(e){return this.doTruncate(e)},e.prototype.doTruncate=function(e){var t=this.truncate;if(!t||!t.length)return e;var n,s,r,i,a=t.length,o=t.location;return"smart"===o?function(e,t,n){var s,r;null==n?(n="…",r=3,s=8):(r=n.length,s=n.length);var i=function(e){var t="";return e.scheme&&e.host&&(t+=e.scheme+"://"),e.host&&(t+=e.host),e.path&&(t+="/"+e.path),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t},a=function(e,t){var s=t/2,r=Math.ceil(s),i=-1*Math.floor(s),a="";return i<0&&(a=e.substr(i)),e.substr(0,r)+n+a};if(e.length<=t)return e;var o,u,l,c=t-r,h=(o={},(l=(u=e).match(/^([a-z]+):\/\//i))&&(o.scheme=l[1],u=u.substr(l[0].length)),(l=u.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(o.host=l[1],u=u.substr(l[0].length)),(l=u.match(/^\/(.*?)(?=(\?|#|$))/i))&&(o.path=l[1],u=u.substr(l[0].length)),(l=u.match(/^\?(.*?)(?=(#|$))/i))&&(o.query=l[1],u=u.substr(l[0].length)),(l=u.match(/^#(.*?)$/i))&&(o.fragment=l[1]),o);if(h.query){var d=h.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);d&&(h.query=h.query.substr(0,d[1].length),e=i(h))}if(e.length<=t)return e;if(h.host&&(h.host=h.host.replace(/^www\./,""),e=i(h)),e.length<=t)return e;var p="";if(h.host&&(p+=h.host),p.length>=c)return h.host.length==t?(h.host.substr(0,t-r)+n).substr(0,c+s):a(p,c).substr(0,c+s);var f="";if(h.path&&(f+="/"+h.path),h.query&&(f+="?"+h.query),f){if((p+f).length>=c)return(p+f).length==t?(p+f).substr(0,t):(p+a(f,c-p.length)).substr(0,c+s);p+=f}if(h.fragment){var m="#"+h.fragment;if((p+m).length>=c)return(p+m).length==t?(p+m).substr(0,t):(p+a(m,c-p.length)).substr(0,c+s);p+=m}if(h.scheme&&h.host){var g=h.scheme+"://";if((p+g).length<c)return(g+p).substr(0,t)}if(p.length<=t)return p;var v="";return c>0&&(v=p.substr(-1*Math.floor(c/2))),(p.substr(0,Math.ceil(c/2))+n+v).substr(0,c+s)}(e,a):"middle"===o?function(e,t,n){if(e.length<=t)return e;var s,r;null==n?(n="…",s=8,r=3):(s=n.length,r=n.length);var i=t-r,a="";return i>0&&(a=e.substr(-1*Math.floor(i/2))),(e.substr(0,Math.ceil(i/2))+n+a).substr(0,i+s)}(e,a):(s=a,r=void 0,(n=e).length>s&&(null==r?(r="…",i=3):i=r.length,n=n.substring(0,s-i)+r),n)},e}(),ct=function(){function e(e){this.__jsduckDummyDocProp=null,this.matchedText="",this.offset=0,this.tagBuilder=e.tagBuilder,this.matchedText=e.matchedText,this.offset=e.offset}return e.prototype.getMatchedText=function(){return this.matchedText},e.prototype.setOffset=function(e){this.offset=e},e.prototype.getOffset=function(){return this.offset},e.prototype.getCssClassSuffixes=function(){return[this.getType()]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}(),ht=function(e,t){return(ht=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function dt(e,t){function n(){this.constructor=e}ht(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var pt,ft=function(){return ft=Object.assign||function(e){for(var t,n=1,s=arguments.length;n<s;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},ft.apply(this,arguments)},mt=function(e){function t(t){var n=e.call(this,t)||this;return n.email="",n.email=t.email,n}return dt(t,e),t.prototype.getType=function(){return"email"},t.prototype.getEmail=function(){return this.email},t.prototype.getAnchorHref=function(){return"mailto:"+this.email},t.prototype.getAnchorText=function(){return this.email},t}(ct),gt=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="",n.hashtag="",n.serviceName=t.serviceName,n.hashtag=t.hashtag,n}return dt(t,e),t.prototype.getType=function(){return"hashtag"},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getHashtag=function(){return this.hashtag},t.prototype.getAnchorHref=function(){var e=this.serviceName,t=this.hashtag;switch(e){case"twitter":return"https://twitter.com/hashtag/"+t;case"facebook":return"https://www.facebook.com/hashtag/"+t;case"instagram":return"https://instagram.com/explore/tags/"+t;default:throw new Error("Unknown service name to point hashtag to: "+e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t}(ct),vt=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.mention="",n.mention=t.mention,n.serviceName=t.serviceName,n}return dt(t,e),t.prototype.getType=function(){return"mention"},t.prototype.getMention=function(){return this.mention},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getAnchorHref=function(){switch(this.serviceName){case"twitter":return"https://twitter.com/"+this.mention;case"instagram":return"https://instagram.com/"+this.mention;case"soundcloud":return"https://soundcloud.com/"+this.mention;default:throw new Error("Unknown service name to point mention to: "+this.serviceName)}},t.prototype.getAnchorText=function(){return"@"+this.mention},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),n=this.getServiceName();return n&&t.push(n),t},t}(ct),bt=function(e){function t(t){var n=e.call(this,t)||this;return n.number="",n.plusSign=!1,n.number=t.number,n.plusSign=t.plusSign,n}return dt(t,e),t.prototype.getType=function(){return"phone"},t.prototype.getPhoneNumber=function(){return this.number},t.prototype.getNumber=function(){return this.getPhoneNumber()},t.prototype.getAnchorHref=function(){return"tel:"+(this.plusSign?"+":"")+this.number},t.prototype.getAnchorText=function(){return this.matchedText},t}(ct),yt=function(e){function t(t){var n=e.call(this,t)||this;return n.url="",n.urlMatchType="scheme",n.protocolUrlMatch=!1,n.protocolRelativeMatch=!1,n.stripPrefix={scheme:!0,www:!0},n.stripTrailingSlash=!0,n.decodePercentEncoding=!0,n.schemePrefixRegex=/^(https?:\/\/)?/i,n.wwwPrefixRegex=/^(https?:\/\/)?(www\.)?/i,n.protocolRelativeRegex=/^\/\//,n.protocolPrepended=!1,n.urlMatchType=t.urlMatchType,n.url=t.url,n.protocolUrlMatch=t.protocolUrlMatch,n.protocolRelativeMatch=t.protocolRelativeMatch,n.stripPrefix=t.stripPrefix,n.stripTrailingSlash=t.stripTrailingSlash,n.decodePercentEncoding=t.decodePercentEncoding,n}return dt(t,e),t.prototype.getType=function(){return"url"},t.prototype.getUrlMatchType=function(){return this.urlMatchType},t.prototype.getUrl=function(){var e=this.url;return this.protocolRelativeMatch||this.protocolUrlMatch||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&/g,"&")},t.prototype.getAnchorText=function(){var e=this.getMatchedText();return this.protocolRelativeMatch&&(e=this.stripProtocolRelativePrefix(e)),this.stripPrefix.scheme&&(e=this.stripSchemePrefix(e)),this.stripPrefix.www&&(e=this.stripWwwPrefix(e)),this.stripTrailingSlash&&(e=this.removeTrailingSlash(e)),this.decodePercentEncoding&&(e=this.removePercentEncoding(e)),e},t.prototype.stripSchemePrefix=function(e){return e.replace(this.schemePrefixRegex,"")},t.prototype.stripWwwPrefix=function(e){return e.replace(this.wwwPrefixRegex,"$1")},t.prototype.stripProtocolRelativePrefix=function(e){return e.replace(this.protocolRelativeRegex,"")},t.prototype.removeTrailingSlash=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e},t.prototype.removePercentEncoding=function(e){var t=e.replace(/%22/gi,""").replace(/%26/gi,"&").replace(/%27/gi,"'").replace(/%3C/gi,"<").replace(/%3E/gi,">");try{return decodeURIComponent(t)}catch(n){return t}},t}(ct),wt=function(e){this.__jsduckDummyDocProp=null,this.tagBuilder=e.tagBuilder},Ct=/[A-Za-z]/,At=/[\d]/,Et=/[\D]/,kt=/\s/,xt=/['"]/,It=/[\x00-\x1F\x7F]/,Tt=/A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/.source,Dt=Tt+/\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/.source+/\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/.source,St=/0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/.source,Mt=Dt+St,Ft=Dt+St,Bt="(?:["+St+"]{1,3}\\.){3}["+St+"]{1,3}",Rt="["+Ft+"](?:["+Ft+"\\-]{0,61}["+Ft+"])?",Nt=function(e){return"(?=("+Rt+"))\\"+e},Ot=function(e){return"(?:"+Nt(e)+"(?:\\."+Nt(e+1)+"){0,126}|"+Bt+")"},_t=new RegExp("["+Ft+"]"),Pt=/(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|spreadbetting|travelchannel|wolterskluwer|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|rightathome|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--estv75g|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--kpu716f|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pbt977c|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nationwide|newholland|nextdirect|onyourside|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|telefonica|university|vistaprint|vlaanderen|volkswagen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|fujixerox|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|honeywell|institute|insurance|kuokgroup|ladbrokes|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|scjohnson|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--tckwe|xn--vhquv|yodobashi|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|chrysler|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|esurance|etisalat|everbank|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|movistar|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|symantec|training|uconnect|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|cartier|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hoteles|hotmail|hyundai|iselect|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lancome|lanxess|lasalle|latrobe|leclerc|liaison|limited|lincoln|markets|metlife|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|shriram|singles|staples|starhub|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|اتصالات|الجزائر|العليان|پاکستان|كاثوليك|موبايلي|இந்தியா|abarth|abbott|abbvie|active|africa|agency|airbus|airtel|alipay|alsace|alstom|anquan|aramco|author|bayern|beauty|berlin|bharti|blanco|bostik|boston|broker|camera|career|caseih|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|mobily|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|piaget|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|vuelos|walter|warman|webcam|xihuan|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|भारतम्|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dabur|dance|deals|delta|dodge|drive|dubai|earth|edeka|email|epost|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|intel|irish|iveco|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|lupin|macys|mango|media|miami|money|mopar|movie|nadex|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|zippo|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|adac|aero|aigo|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|doha|duck|duns|dvag|erni|fage|fail|fans|farm|fast|fiat|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scor|scot|seat|seek|sexy|shaw|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بارت|بيتك|ڀارت|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ভাৰত|ਭਾਰਤ|ભારત|ଭାରତ|ಭಾರತ|ලංකා|グーグル|クラウド|ポイント|大众汽车|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bnl|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceb|ceo|cfa|cfd|com|crs|csc|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jcp|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|srl|srt|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|عرب|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ストア|セール|みんな|中文网|天主教|我爱你|新加坡|淡马锡|诺基亚|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|工行|广东|微博|慈善|手机|手表|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|珠宝|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/,jt=new RegExp("["+Ft+"!#$%&'*+/=?^_`{|}~-]"),Ut=new RegExp("^"+Pt.source+"$"),$t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.localPartCharRegex=jt,t.strictTldRegex=Ut,t}return dt(t,e),t.prototype.parseMatches=function(e){for(var t=this.tagBuilder,n=this.localPartCharRegex,s=this.strictTldRegex,r=[],i=e.length,a=new Wt,o={m:"a",a:"i",i:"l",l:"t",t:"o",o:":"},u=0,l=0,c=a;u<i;){var h=e.charAt(u);switch(l){case 0:"m"===(d=h)?w(1):n.test(d)&&w();break;case 1:p(e.charAt(u-1),h);break;case 2:f(h);break;case 3:m(h);break;case 4:g(h);break;case 5:v(h);break;case 6:b(h);break;case 7:y(h);break;default:ot(l)}u++}var d;return A(),r;function p(e,t){":"===e?n.test(t)?(l=2,c=new Wt(ft(ft({},c),{hasMailtoPrefix:!0}))):C():o[e]===t||(n.test(t)?l=2:"."===t?l=3:"@"===t?l=4:C())}function f(e){"."===e?l=3:"@"===e?l=4:n.test(e)||C()}function m(e){"."===e||"@"===e?C():n.test(e)?l=2:C()}function g(e){_t.test(e)?l=5:C()}function v(e){"."===e?l=7:"-"===e?l=6:_t.test(e)||A()}function b(e){"-"===e||"."===e?A():_t.test(e)?l=5:A()}function y(e){"."===e||"-"===e?A():_t.test(e)?(l=5,c=new Wt(ft(ft({},c),{hasDomainDot:!0}))):A()}function w(e){void 0===e&&(e=2),l=e,c=new Wt({idx:u})}function C(){l=0,c=a}function A(){if(c.hasDomainDot){var n=e.slice(c.idx,u);/[-.]$/.test(n)&&(n=n.slice(0,-1));var i=c.hasMailtoPrefix?n.slice(7):n;(function(e){var t=(e.split(".").pop()||"").toLowerCase();return s.test(t)})(i)&&r.push(new mt({tagBuilder:t,matchedText:n,offset:c.idx,email:i}))}C()}},t}(wt),Wt=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.hasMailtoPrefix=!!e.hasMailtoPrefix,this.hasDomainDot=!!e.hasDomainDot},qt=function(){function e(){}return e.isValid=function(e,t){return!(t&&!this.isValidUriScheme(t)||this.urlMatchDoesNotHaveProtocolOrDot(e,t)||this.urlMatchDoesNotHaveAtLeastOneWordChar(e,t)&&!this.isValidIpAddress(e)||this.containsMultipleDots(e))},e.isValidIpAddress=function(e){var t=new RegExp(this.hasFullProtocolRegex.source+this.ipRegex.source);return null!==e.match(t)},e.containsMultipleDots=function(e){var t=e;return this.hasFullProtocolRegex.test(e)&&(t=e.split("://")[1]),t.split("/")[0].indexOf("..")>-1},e.isValidUriScheme=function(e){var t=e.match(this.uriSchemeRegex),n=t&&t[0].toLowerCase();return"javascript:"!==n&&"vbscript:"!==n},e.urlMatchDoesNotHaveProtocolOrDot=function(e,t){return!(!e||t&&this.hasFullProtocolRegex.test(t)||-1!==e.indexOf("."))},e.urlMatchDoesNotHaveAtLeastOneWordChar=function(e,t){return!(!e||!t||this.hasFullProtocolRegex.test(t)||this.hasWordCharAfterProtocolRegex.test(e))},e.hasFullProtocolRegex=/^[A-Za-z][-.+A-Za-z0-9]*:\/\//,e.uriSchemeRegex=/^[A-Za-z][-.+A-Za-z0-9]*:/,e.hasWordCharAfterProtocolRegex=new RegExp(":[^\\s]*?["+Tt+"]"),e.ipRegex=/[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,e}(),Ht=(pt=new RegExp("[/?#](?:["+Ft+"\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*["+Ft+"\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"),new RegExp(["(?:","(",/(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source,Ot(2),")","|","(","(//)?",/(?:www\.)/.source,Ot(6),")","|","(","(//)?",Ot(10)+"\\.",Pt.source,"(?![-"+Mt+"])",")",")","(?::[0-9]+)?","(?:"+pt.source+")?"].join(""),"gi")),Lt=new RegExp("["+Ft+"]"),Gt=function(e){function t(t){var n=e.call(this,t)||this;return n.stripPrefix={scheme:!0,www:!0},n.stripTrailingSlash=!0,n.decodePercentEncoding=!0,n.matcherRegex=Ht,n.wordCharRegExp=Lt,n.stripPrefix=t.stripPrefix,n.stripTrailingSlash=t.stripTrailingSlash,n.decodePercentEncoding=t.decodePercentEncoding,n}return dt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.stripPrefix,r=this.stripTrailingSlash,i=this.decodePercentEncoding,a=this.tagBuilder,o=[],u=function(){var n=t[0],u=t[1],c=t[4],h=t[5],d=t[9],p=t.index,f=h||d,m=e.charAt(p-1);if(!qt.isValid(n,u))return"continue";if(p>0&&"@"===m)return"continue";if(p>0&&f&&l.wordCharRegExp.test(m))return"continue";if(/\?$/.test(n)&&(n=n.substr(0,n.length-1)),l.matchHasUnbalancedClosingParen(n))n=n.substr(0,n.length-1);else{var g=l.matchHasInvalidCharAfterTld(n,u);g>-1&&(n=n.substr(0,g))}var v=["http://","https://"].find((function(e){return!!u&&-1!==u.indexOf(e)}));if(v){var b=n.indexOf(v);n=n.substr(b),u=u.substr(b),p+=b}var y=u?"scheme":c?"www":"tld",w=!!u;o.push(new yt({tagBuilder:a,matchedText:n,offset:p,urlMatchType:y,url:n,protocolUrlMatch:w,protocolRelativeMatch:!!f,stripPrefix:s,stripTrailingSlash:r,decodePercentEncoding:i}))},l=this;null!==(t=n.exec(e));)u();return o},t.prototype.matchHasUnbalancedClosingParen=function(e){var t,n=e.charAt(e.length-1);if(")"===n)t="(";else if("]"===n)t="[";else{if("}"!==n)return!1;t="{"}for(var s=0,r=0,i=e.length-1;r<i;r++){var a=e.charAt(r);a===t?s++:a===n&&(s=Math.max(s-1,0))}return 0===s},t.prototype.matchHasInvalidCharAfterTld=function(e,t){if(!e)return-1;var n=0;t&&(n=e.indexOf(":"),e=e.slice(n));var s=new RegExp("^((.?//)?[-."+Ft+"]*[-"+Ft+"]\\.[-"+Ft+"]+)").exec(e);return null===s?-1:(n+=s[1].length,e=e.slice(s[1].length),/^[^-.A-Za-z0-9:\/?#]/.test(e)?n:-1)},t}(wt),zt=new RegExp("#[_"+Ft+"]{1,139}(?![_"+Ft+"])","g"),Jt=new RegExp("[^"+Ft+"]"),Yt=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.matcherRegex=zt,n.nonWordCharRegex=Jt,n.serviceName=t.serviceName,n}return dt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.nonWordCharRegex,r=this.serviceName,i=this.tagBuilder,a=[];null!==(t=n.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||s.test(u)){var l=t[0],c=t[0].slice(1);a.push(new gt({tagBuilder:i,matchedText:l,offset:o,serviceName:r,hashtag:c}))}}return a},t}(wt),Qt=new RegExp(/(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/.source+"|"+/(0([1-9]{1}-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/.source,"g"),Vt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.matcherRegex=Qt,t}return dt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.tagBuilder,r=[];null!==(t=n.exec(e));){var i=t[0],a=i.replace(/[^0-9,;#]/g,""),o=!(!t[1]&&!t[2]),u=0==t.index?"":e.substr(t.index-1,1),l=e.substr(t.index+i.length,1),c=!u.match(/\d/)&&!l.match(/\d/);this.testMatch(t[3])&&this.testMatch(i)&&c&&r.push(new bt({tagBuilder:s,matchedText:i,offset:t.index,number:a,plusSign:o}))}return r},t.prototype.testMatch=function(e){return Et.test(e)},t}(wt),Zt=new RegExp("@[_"+Ft+"]{1,50}(?![_"+Ft+"])","g"),Kt=new RegExp("@[_."+Ft+"]{1,30}(?![_"+Ft+"])","g"),Xt=new RegExp("@[-_."+Ft+"]{1,50}(?![-_"+Ft+"])","g"),en=new RegExp("[^"+Ft+"]"),tn=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.matcherRegexes={twitter:Zt,instagram:Kt,soundcloud:Xt},n.nonWordCharRegex=en,n.serviceName=t.serviceName,n}return dt(t,e),t.prototype.parseMatches=function(e){var t,n=this.serviceName,s=this.matcherRegexes[this.serviceName],r=this.nonWordCharRegex,i=this.tagBuilder,a=[];if(!s)return a;for(;null!==(t=s.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||r.test(u)){var l=t[0].replace(/\.+$/g,""),c=l.slice(1);a.push(new vt({tagBuilder:i,matchedText:l,offset:o,serviceName:n,mention:c}))}}return a},t}(wt);var nn=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.type=e.type||"tag",this.name=e.name||"",this.isOpening=!!e.isOpening,this.isClosing=!!e.isClosing},sn=function(){function e(t){void 0===t&&(t={}),this.version=e.version,this.urls={},this.email=!0,this.phone=!0,this.hashtag=!1,this.mention=!1,this.newWindow=!0,this.stripPrefix={scheme:!0,www:!0},this.stripTrailingSlash=!0,this.decodePercentEncoding=!0,this.truncate={length:0,location:"end"},this.className="",this.replaceFn=null,this.context=void 0,this.sanitizeHtml=!1,this.matchers=null,this.tagBuilder=null,this.urls=this.normalizeUrlsCfg(t.urls),this.email="boolean"==typeof t.email?t.email:this.email,this.phone="boolean"==typeof t.phone?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow="boolean"==typeof t.newWindow?t.newWindow:this.newWindow,this.stripPrefix=this.normalizeStripPrefixCfg(t.stripPrefix),this.stripTrailingSlash="boolean"==typeof t.stripTrailingSlash?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding="boolean"==typeof t.decodePercentEncoding?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var n=this.mention;if(!1!==n&&"twitter"!==n&&"instagram"!==n&&"soundcloud"!==n)throw new Error("invalid `mention` cfg - see docs");var s=this.hashtag;if(!1!==s&&"twitter"!==s&&"facebook"!==s&&"instagram"!==s)throw new Error("invalid `hashtag` cfg - see docs");this.truncate=this.normalizeTruncateCfg(t.truncate),this.className=t.className||this.className,this.replaceFn=t.replaceFn||this.replaceFn,this.context=t.context||this}return e.link=function(t,n){return new e(n).link(t)},e.parse=function(t,n){return new e(n).parse(t)},e.prototype.normalizeUrlsCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{schemeMatches:e,wwwMatches:e,tldMatches:e}:{schemeMatches:"boolean"!=typeof e.schemeMatches||e.schemeMatches,wwwMatches:"boolean"!=typeof e.wwwMatches||e.wwwMatches,tldMatches:"boolean"!=typeof e.tldMatches||e.tldMatches}},e.prototype.normalizeStripPrefixCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{scheme:e,www:e}:{scheme:"boolean"!=typeof e.scheme||e.scheme,www:"boolean"!=typeof e.www||e.www}},e.prototype.normalizeTruncateCfg=function(e){return"number"==typeof e?{length:e,location:"end"}:function(e,t){for(var n in t)t.hasOwnProperty(n)&&void 0===e[n]&&(e[n]=t[n]);return e}(e||{},{length:Number.POSITIVE_INFINITY,location:"end"})},e.prototype.parse=function(e){var t=this,n=["a","style","script"],s=0,r=[];return function(e,t){for(var n,s=t.onOpenTag,r=t.onCloseTag,i=t.onText,a=t.onComment,o=t.onDoctype,u=new nn,l=0,c=e.length,h=0,d=0,p=u;l<c;){var f=e.charAt(l);switch(h){case 0:"<"===f&&O();break;case 1:m(f);break;case 2:v(f);break;case 3:g(f);break;case 4:b(f);break;case 5:y(f);break;case 6:w(f);break;case 7:C(f);break;case 8:A(f);break;case 9:E(f);break;case 10:k(f);break;case 11:x(f);break;case 12:I(f);break;case 13:"--"===e.substr(l,2)?(l+=2,p=new nn(ft(ft({},p),{type:"comment"})),h=14):"DOCTYPE"===e.substr(l,7).toUpperCase()?(l+=7,p=new nn(ft(ft({},p),{type:"doctype"})),h=20):N();break;case 14:T(f);break;case 15:D(f);break;case 16:S(f);break;case 17:M(f);break;case 18:F(f);break;case 19:B(f);break;case 20:R(f);break;default:ot(h)}l++}function m(e){"!"===e?h=13:"/"===e?(h=2,p=new nn(ft(ft({},p),{isClosing:!0}))):"<"===e?O():Ct.test(e)?(h=3,p=new nn(ft(ft({},p),{isOpening:!0}))):(h=0,p=u)}function g(e){kt.test(e)?(p=new nn(ft(ft({},p),{name:P()})),h=4):"<"===e?O():"/"===e?(p=new nn(ft(ft({},p),{name:P()})),h=12):">"===e?(p=new nn(ft(ft({},p),{name:P()})),_()):Ct.test(e)||At.test(e)||":"===e||N()}function v(e){">"===e?N():Ct.test(e)?h=3:N()}function b(e){kt.test(e)||("/"===e?h=12:">"===e?_():"<"===e?O():"="===e||xt.test(e)||It.test(e)?N():h=5)}function y(e){kt.test(e)?h=6:"/"===e?h=12:"="===e?h=7:">"===e?_():"<"===e?O():xt.test(e)&&N()}function w(e){kt.test(e)||("/"===e?h=12:"="===e?h=7:">"===e?_():"<"===e?O():xt.test(e)?N():h=5)}function C(e){kt.test(e)||('"'===e?h=8:"'"===e?h=9:/[>=`]/.test(e)?N():"<"===e?O():h=10)}function A(e){'"'===e&&(h=11)}function E(e){"'"===e&&(h=11)}function k(e){kt.test(e)?h=4:">"===e?_():"<"===e&&O()}function x(e){kt.test(e)?h=4:"/"===e?h=12:">"===e?_():"<"===e?O():(h=4,l--)}function I(e){">"===e?(p=new nn(ft(ft({},p),{isClosing:!0})),_()):h=4}function T(e){"-"===e?h=15:">"===e?N():h=16}function D(e){"-"===e?h=18:">"===e?N():h=16}function S(e){"-"===e&&(h=17)}function M(e){h="-"===e?18:16}function F(e){">"===e?_():"!"===e?h=19:"-"===e||(h=16)}function B(e){"-"===e?h=17:">"===e?_():h=16}function R(e){">"===e?_():"<"===e&&O()}function N(){h=0,p=u}function O(){h=1,p=new nn({idx:l})}function _(){var t=e.slice(d,p.idx);t&&i(t,d),"comment"===p.type?a(p.idx):"doctype"===p.type?o(p.idx):(p.isOpening&&s(p.name,p.idx),p.isClosing&&r(p.name,p.idx)),N(),d=l+1}function P(){var t=p.idx+(p.isClosing?2:1);return e.slice(t,l).toLowerCase()}d<l&&(n=e.slice(d,l),i(n,d),d=l+1)}(e,{onOpenTag:function(e){n.indexOf(e)>=0&&s++},onText:function(e,n){if(0===s){var i=function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var n,s=[],r=0;n=t.exec(e);)s.push(e.substring(r,n.index)),s.push(n[0]),r=n.index+n[0].length;return s.push(e.substring(r)),s}(e,/( | |<|<|>|>|"|"|')/gi),a=n;i.forEach((function(e,n){if(n%2==0){var s=t.parseText(e,a);r.push.apply(r,s)}a+=e.length}))}},onCloseTag:function(e){n.indexOf(e)>=0&&(s=Math.max(s-1,0))},onComment:function(e){},onDoctype:function(e){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort((function(e,t){return e.getOffset()-t.getOffset()}));for(var t=0;t<e.length-1;t++){var n=e[t],s=n.getOffset(),r=n.getMatchedText().length,i=s+r;if(t+1<e.length){if(e[t+1].getOffset()===s){var a=e[t+1].getMatchedText().length>r?t:t+1;e.splice(a,1);continue}e[t+1].getOffset()<i&&e.splice(t+1,1)}}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||at(e,(function(e){return"hashtag"===e.getType()})),this.email||at(e,(function(e){return"email"===e.getType()})),this.phone||at(e,(function(e){return"phone"===e.getType()})),this.mention||at(e,(function(e){return"mention"===e.getType()})),this.urls.schemeMatches||at(e,(function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()})),this.urls.wwwMatches||at(e,(function(e){return"url"===e.getType()&&"www"===e.getUrlMatchType()})),this.urls.tldMatches||at(e,(function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()})),e},e.prototype.parseText=function(e,t){void 0===t&&(t=0),t=t||0;for(var n=this.getMatchers(),s=[],r=0,i=n.length;r<i;r++){for(var a=n[r].parseMatches(e),o=0,u=a.length;o<u;o++)a[o].setOffset(t+a[o].getOffset());s.push.apply(s,a)}return s},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"<").replace(/>/g,">"));for(var t=this.parse(e),n=[],s=0,r=0,i=t.length;r<i;r++){var a=t[r];n.push(e.substring(s,a.getOffset())),n.push(this.createMatchReturnVal(a)),s=a.getOffset()+a.getMatchedText().length}return n.push(e.substring(s)),n.join("")},e.prototype.createMatchReturnVal=function(e){var t;return this.replaceFn&&(t=this.replaceFn.call(this.context,e)),"string"==typeof t?t:!1===t?e.getMatchedText():t instanceof ut?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getMatchers=function(){if(this.matchers)return this.matchers;var e=this.getTagBuilder(),t=[new Yt({tagBuilder:e,serviceName:this.hashtag}),new $t({tagBuilder:e}),new Vt({tagBuilder:e}),new tn({tagBuilder:e,serviceName:this.mention}),new Gt({tagBuilder:e,stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding})];return this.matchers=t},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new lt({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="3.14.3",e.AnchorTagBuilder=lt,e.HtmlTag=ut,e.matcher={Email:$t,Hashtag:Yt,Matcher:wt,Mention:tn,Phone:Vt,Url:Gt},e.match={Email:mt,Hashtag:gt,Match:ct,Mention:vt,Phone:bt,Url:yt},e}();function rn(e,t=e){return{type:"autolink",url:e,text:t}}const an=Ve(/<!!mention:([^>\s]*?)\|(.*?)>/gm,(([e,t,n])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),n))),on=Ve(/<!!customemoji:(.*?)>/gm,(([e,t])=>function(e){return{type:"customemoji",text:e}}(t))),un=Ve(/<((?:https?|mailto):.*?)\|(.*?)>/gi,(([e,t,n])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[n]))),ln=Ve(/<actionlink:([^|]+)[|]([^>]*)>/gi,(([e,t,n])=>{const{action:s,params:r}=hn(t);return function(e,t,n=[]){return{type:"actionlink",action:e,params:t,children:n}}(s,r,[n])})),cn=Ve(/<actionbutton:([^|]+)[|]([^>]*)>/gi,(([e,t,n])=>{const{action:s,params:r}=hn(t);return function(e,t,n=[]){return{type:"actionbutton",action:e,params:t,children:n}}(s,r,[n])}));function hn(e){const t=e.indexOf("?");return-1===t?{action:e,params:{}}:{action:e.slice(0,t),params:Object.fromEntries(new URLSearchParams(e.slice(t)))}}const dn=Ve(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,(([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e]))),pn=Ve(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,(([e,t])=>({type:"bulletpoint",children:[t]}))),fn=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g;let n=0;const s=[];for(const r of oe(e,t)){const t=r[0],i=r[1],a=t.startsWith(i)?r.index:r.index+1;a-n>0&&s.push(e.substring(n,a));const o=rn("tel:"+i.replace(/[^0-9+]/g,""),i);s.push(o),n=a+i.length}return n<e.length&&s.push(e.substring(n)),s},mn=e=>un(e).flatMap((e=>"string"==typeof e?gn(e):["<",...gn(e.url),...gn("|"+e.children[0]+">")])),gn=e=>{const t=sn.parse(e,{urls:!0,email:!0,phone:!1,hashtag:!1,mention:!1}),n=[];let s=0;for(const r of t){const t=r.getOffset(),i=r.getMatchedText(),a=i.length;let o=i;r instanceof mt?o="mailto:"+r.getEmail():r instanceof yt&&(o=r.getUrl()),t>s&&n.push(e.substring(s,t)),n.push(rn(o,i)),s=t+a}return s<e.length&&n.push(e.substring(s)),n},vn=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const bn=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function yn(e,t={except:[]}){let n=function(e,t){let n=[e];return n=Cn(n,t.multilineSteps),n=Cn(n,[bn]),n=Cn(n,t.singlelineSteps),n=An(n),n}(e,function(e={except:[]}){var t;const n={multilineSteps:[],singlelineSteps:[]},s=null!=(t=e.except)?t:vn.filter((t=>!e.only.includes(t)));return s.includes("BulletPoint")||n.multilineSteps.push(dn,pn),s.includes("Mention")||n.singlelineSteps.push(an),s.includes("CustomEmoji")||n.singlelineSteps.push(on),s.includes("Codespan")||n.multilineSteps.push(Ve(/```([^]+?)```/g,(([e,t])=>({type:"codespan",text:t.replace(/<!!mention:.*?\|([^>]*)>/gim,"@$1").replace(/<!!customemoji:(.*?)>/gim,"$1")})))),s.includes("FormattedLink")||n.singlelineSteps.push(un),s.includes("Actions")||(n.singlelineSteps.push(ln),n.singlelineSteps.push(cn)),s.includes("Wikitext")||n.singlelineSteps.push(nt),s.includes("Autolink")||n.singlelineSteps.push(mn,fn),n}(t));return n=En(n,!1),n}function wn(e){return yn(e,{except:["FormattedLink","Actions"]})}function Cn(e,t){return t.reduce(((e,t)=>Qe(e,t)),e)}function An(e){const t=[];let n=-1;for(const s of e)"string"==typeof s?"string"==typeof t[n]?t[n]+=s:t[++n]=s:t[++n]="children"in s?l(u({},s),{children:An(s.children)}):s;return t}function En(e,t){const n=[];let s=[];for(let r=0;r<e.length;r++){const i=e[r];if("string"==typeof i)s.push(i);else if("children"in i){s.length>0&&(n.push(s.join("")),s=[]);const e=En(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type);n.push(l(u({},i),{children:e}))}else"autolink"===i.type&&t?s.push(i.text):(s.length>0&&(n.push(s.join("")),s=[]),n.push(i))}return s.length>0&&(n.push(s.join("")),s=[]),n}class kn{constructor(e,t,n,s){this.emoji=e,this.messageId=t,this.conversationId=n,this._realtimeClient=s}get brandedMessageId(){return this.messageId}get brandedConversationId(){return this.conversationId}add(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],{});d(`Add ${this.emoji} reaction on message ${this.messageId} in conversation ${this.conversationId}`,e)}))}remove(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&d(`Remove ${this.emoji} reaction from message ${this.messageId} in conversation ${this.conversationId}`,e)}))}}class xn{constructor(e,t,n){this.id=e,this.conversationId=t,this._realtimeClient=n}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}reaction(e){if("string"!=typeof e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is not a string`);if(""===e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is an empty string`);return new kn(e,this.brandedId,this.brandedConversationId,this._realtimeClient)}get(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"messages",this.brandedId],{});if(!e.ok&&"server"===e.where&&404===e.value.status)return null;if(!e.ok&&"server"===e.where&&403===e.value.status&&"NOT_A_PARTICIPANT"===e.value.errorCode)return null;const t=d("Get message "+this.id,e),n=yield this._realtimeClient.hydrateMessageData(t,this.brandedConversationId);return Ge("Get message "+this.id,n)}))}edit(e){return h(this,null,(function*(){const t={content:In(e),custom:"string"==typeof e?void 0:e.custom},n=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"messages",this.brandedId],t);d(`Edit message ${this.id} in conversation ${this.conversationId}`,n)}))}delete(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&d(`Delete message ${this.id} in conversation ${this.conversationId}`,e)}))}}function In(e){return"string"==typeof e?[{type:"text",children:yn(e)}]:"text"in e&&e.text?[{type:"text",children:yn(e.text)}]:"content"in e&&e.content?e.content:void 0}class Tn{constructor(e,t){this.id=e,this._realtimeClient=t,this.uselessObjForTypeCheck={subject:null,photoUrl:null,welcomeMessages:null,custom:null,access:null,notify:null}}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){if("string"==typeof e){if(""===e)throw new Error(`Creating ParticipantRef failed because ID "${e}" is an empty string`);return new Je(e,this.id,this._realtimeClient)}if("brandedId"in e)return new Je(e.id,this.id,this._realtimeClient);throw new Error(`Creating ParticipantRef failed because user "${e}" is not a string or a UserRef`)}message(e){if("string"!=typeof e)throw new Error(`Creating MessageRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating MessageRef failed because ID "${e}" is an empty string`);return new xn(e,this.brandedId,this._realtimeClient)}get(){return h(this,null,(function*(){const e=this._realtimeClient.listMessages(this.brandedId,{limit:1}),t=yield this._realtimeClient.call("GET",["me","conversations",this.brandedId],{});if(!t.ok&&"server"===t.where&&404===t.value.status)return null;const n=d("Get conversation "+this.id,t),s=Ge("Get last message in conversation "+this.id,yield e);return function(e,t){return z({id:e.id,subject:e.subject,photoUrl:e.photoUrl,welcomeMessages:z(e.welcomeMessages),custom:z(e.custom),createdAt:e.createdAt,joinedAt:e.joinedAt,lastMessageAt:e.lastMessageAt,unreadMessageCount:e.unreadMessageCount,isUnread:e.isUnread,access:e.access,notify:e.notify,lastMessage:t,readUntil:e.readUntil,everyoneReadUntil:e.everyoneReadUntil})}(n,0===s.length?null:s[0])}))}set(e){return h(this,null,(function*(){const t=this._realtimeClient.call("PUT",["conversations",this.brandedId],e),n=this._realtimeClient.call("PUT",["conversations",this.brandedId,"participants",this.brandedUserId],e),s=yield t;!s.ok&&"server"===s.where&&403===s.value.status&&"UNAUTHORIZED_TO_EDIT"===s.value.errorCode&&function(e){return void 0===e.subject&&(void 0===e.photoUrl&&(void 0===e.welcomeMessages&&(null!==e.custom&&(void 0===e.custom||!Object.values(e.custom).some((e=>void 0!==e))))))}(e)||d("Set conversation "+this.id,s);const r=yield n;!r.ok&&"server"===r.where&&403===r.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===r.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||d("Set your participation in conversation "+this.id,r)}))}createIfNotExists(){return h(this,arguments,(function*(e={}){const t=this._realtimeClient.call("POST",["conversations",this.brandedId],e),n=this._realtimeClient.call("POST",["conversations",this.brandedId,"participants",this.brandedUserId],e),s=yield t;(s.ok||"server"!==s.where||409!==s.value.status)&&d("Create conversation "+this.id,yield t);const r=yield n;(r.ok||"server"!==r.where||409!==r.value.status)&&d("Join conversation "+this.id,yield n)}))}markAsRead(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"read"],{});d(`Mark ${this.id} as read`,e)}))}markAsUnread(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"unread"],{});d(`Mark ${this.id} as unread`,e)}))}send(e){return h(this,null,(function*(){const t={content:Dn(e),referencedMessageId:Sn(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:Ye((new Date).getTime())},n=yield this._realtimeClient.call("POST",["conversations",this.brandedId,"messages"],t),s=d("Send message to conversation "+this.id,n);return new xn(s.id,this.brandedId,this._realtimeClient)}))}subscribeMessages(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"messages"],e)}subscribeParticipants(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"participants"],e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}subscribeTyping(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"typing"],e)}markAsTyping(){return h(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"typing"],{});d(`Set user as typing in ${this.id}`,e)}))}}function Dn(e){return"string"==typeof e?[{type:"text",children:wn(e)}]:"text"in e?[{type:"text",children:wn(e.text)}]:e.content}function Sn(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class Mn{constructor(e,t,n){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=t,this.restApiHttpUrl=n}getBokensUrl(e,t,n){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(t)}?signature=${encodeURIComponent(null!=n?n:"")}`}getRealtimeWsUrl(e,t,n,s,r){const i=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${i}?talkjs-client-build=${null!=r?r:"standalone"}&talkjs-core=${n}&talkjs-client-id=${s}`}static fromHost(e){var t;const n=new Mn("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return n;if("@currentHost"===e){if("undefined"==typeof location)throw new Error("You can only use @currentHost in a browser.");e=(null!=(t=window.top)?t:window).location.host}if(e.endsWith("talkjs.com")){const t=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(t){const e=t[1];return["app","cdn","api","realtime"].includes(e)?n:new Mn(`wss://realtime-${e}.talkjs.com/v1`,`https://app-${e}.talkjs.com/api/v0`,`https://api-${e}.talkjs.com/v1`)}return n}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new Mn(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new Mn(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function Fn({method:e,url:t,data:n,options:s,attempts:r,shouldRetry:i,authProvider:a}){var o;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2025-10-28T10:10:39.064Z"};return n instanceof FormData||(u["Content-Type"]=null!=(o=null==s?void 0:s.contentType)?o:"application/json"),b(r,(()=>h(this,null,(function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:n}).then((e=>{if(e.ok)return e;throw e}))}))),{initialDelay:.2,log:void 0,shouldRetry:n=>h(this,null,(function*(){return a&&401===n.status?(Un.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.refreshToken(),!0):i?i(n):!("status"in n&&n.status>=400&&n.status<500)}))}).catch((n=>{if(Math.random()<.1&&!t.toString().startsWith("https://capture.trackjs.com")){const s=`Network Error for ${e} ${t}`;"undefined"!=typeof window&&(n instanceof Response?n.clone().text().then((e=>Un.log(`${s} ${n.status} ${e} (10% logged)`))):Un.log(`${s} ${n} (10% logged)`)),console.error("[TalkJS]",s)}throw n}))}const{cdnHost:Bn,appHost:Rn,restHost:Nn,realtimeHost:On,appProtocol:_n,appWsProtocol:Pn}=function(){if("undefined"==typeof window)return{cdnHost:"test-hostname",appHost:"test-hostname",appProtocol:"http:",appWsProtocol:"ws:"};const e=function(){if(document.currentScript)return document.currentScript.src;try{throw new Error}catch(o){const t=o.stack.match(/https?:\/\/.*\.(js|jsx|ts|tsx)/);return t?t[0]:""}}(),t=document.createElement("a");t.href=e;const n=t.host,s=(o=n).match(/^cdn[.-]/)?o.replace(/^cdn/,"app"):"talkjs.com"===o?"app.talkjs.com":o,r=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"api"):e+"/public_api"}(s),i=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"realtime"):e+"/public_api"}(s),a=t.protocol;var o;return{cdnHost:n,appHost:s,restHost:r,realtimeHost:i,appProtocol:a,appWsProtocol:"https:"===a?"wss:":"ws:"}}(),jn=Rn.startsWith("app.talkjs.com"),Un="undefined"==typeof window?{log:e=>Promise.resolve(),setData:e=>{}}:new class{constructor(e){this._timeCreated=Date.now(),this._enabled=jn,this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2025-10-28T10:10:39.064Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:window.location.href,referrer:document.referrer,userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:window.location.href,stack:"",timestamp:(new Date).toISOString(),version:"dev-2025-10-28T10:10:39.064Z",throttled:0},this._url=`https://capture.trackjs.com/capture?token=${e}`,this._trackJSData.customer.token=e}setData({appId:e,meId:t,sessionId:n}){this._trackJSData.customer.userId=e,this._trackJSData.customer.sessionId=`${e}/${t}`,this._trackJSData.customer.correlationId=n}log(e){return h(this,null,(function*(){try{if(!this._enabled)return Promise.resolve();const t=l(u({},this._trackJSData),{message:e});yield Fn({method:"POST",url:this._url,data:JSON.stringify(t),options:{contentType:"text/plain"}})}catch(t){console.error("[TalkJS] Failed when sending an error report. Error: ",t)}}))}}("970cd0be0fb74630b75c8451051299dc");class $n{constructor(e,t={}){this._onSubscription=t,this._handlers={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(this._handlers[n]=[])}emit(e,t){for(const s of this._handlers[e])try{s(t)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}}emitAsync(e,t){return h(this,null,(function*(){try{const n=this._handlers[e].map((e=>e(t)));yield Promise.all(n)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}}))}supports(e){return e in this._handlers}on(e,t){var n,s;if(!this.supports(e))throw new Error(`Unknown event type '${String(e)}'`);null==(s=(n=this._onSubscription)[e])||s.call(n),this._handlers[e].push(t)}off(e,t){if(!Object.hasOwnProperty.call(this._handlers,e))throw new Error(`Unknown event type '${String(e)}'`);const n=this._handlers[e].indexOf(t);-1!==n&&this._handlers[e].splice(n,1)}removeAllListeners(){for(const e in this._handlers)this._handlers[e]=[]}handles(e){return this._handlers[e].length>0}subscribe(e,t){return this.on(e,t),{unsubscribe:()=>this.off(e,t)}}}class Wn{constructor(e,t,n,s,r,i){if(this.appId=t,this.userId=n,this.tokenFetcher=r,this.usingBokens=!1,this.requestInProgress=!1,this.eventEmitter=new $n({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0,i&&(s||r))throw new Error("[TalkJS] If providing a signature for authentication, you must not provide a token or tokenFetcher.");s?this.fetchToken((()=>s)):(r||(this.usingBokens=!0,this.tokenFetcher=()=>this.sendBokenRequest(e,i)),this.refreshToken())}get canRefreshToken(){return this.usingBokens||!!this.tokenFetcher}getToken(){return this.token}refreshToken(){if(!this.requestInProgress){if(!this.tokenFetcher)throw this.emitTokenRefreshFailed("no `tokenFetcher` provided"),new Error("[TalkJS] Cannot refresh token, no `tokenFetcher` provided.");this.fetchToken(this.tokenFetcher)}}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}emitTokenChanged(e){this.eventEmitter.emit("tokenChanged",e)}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e),console.error(`[TalkJS] Could not authenticate, cannot recover automatically: ${e}`)}onTokenAccepted(e){return this.eventEmitter.on("tokenAccepted",e),()=>{this.eventEmitter.off("tokenAccepted",e)}}emitTokenAccepted(e){this.eventEmitter.emit("tokenAccepted",e)}clearScheduledRefresh(){this.sessionExpiryWarningTimeoutId&&clearTimeout(this.sessionExpiryWarningTimeoutId)}scheduleRefresh(e){if(this.clearScheduledRefresh(),null===e)return;const t=void 0!==this.tokenFetcher;if(e<120&&!t?console.warn(`[TalkJS] TalkJS will stop working in ${e} seconds due to auth token expiry. Token expires in ${e} seconds, and cannot be refreshed because no \`tokenFetcher\` was provided when creating the session. Non-refreshable tokens are recommended to expire at least 24 hours in the future.`):e<120&&t?console.warn(`[TalkJS] TalkJS auth token will expire and need to be refreshed in ${e} seconds. Refreshable JWTs are recommended to expire at least 30 minutes in the future, to improve performance and reduce unnecessary refreshes.`):e<3300&&!t&&console.warn(`[TalkJS debug] TalkJS will stop working in ${Math.round(e/60)} minutes due to auth token expiry. Non-refreshable tokens are recommended to expire at least 24 hours in the future. Alternatively, provide a \`tokenFetcher\` when creating the session, so that tokens can be refreshed when they expire.`),void 0!==this.tokenFetcher){const t=e>600?e-300:e/2,n=Math.min(1728e6,1e3*t);this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.refreshToken()}),n)}else e<2e6&&(this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.emitTokenRefreshFailed("Token has expired and no `tokenFetcher` was provided when creating the session, so it cannot be refreshed.")}),1e3*e))}fetchToken(e){return h(this,null,(function*(){if(this.requestInProgress)return;this.requestInProgress=!0;const t=()=>h(this,null,(function*(){const t=yield e();return this.checkJwt(t),t}));try{const e=void 0!==this.token;this.token=t(),yield this.token.then((t=>{e&&this.emitTokenChanged(t)})).catch((e=>{this.emitTokenRefreshFailed(e)}))}catch(n){this.emitTokenRefreshFailed(n)}finally{this.requestInProgress=!1}}))}checkJwt(e){!function(e){if(!("string"==typeof e||e instanceof String)){if(void 0===e)throw"Token was undefined";throw"Token must be a string, got: "+e}}(e);const t=[];let n,s,r;if("string"==typeof e?n=e:t.push(`Token type is ${typeof e} instead of a string.`),n)try{const e=function(e){const t=e.split(".");if(3!==t.length)throw"Token does not contain exactly two `.`. Check that you generated your JWT correctly. It should be `<header>.<payload>.<signature>`.";return{header:qn(t[0]),payload:qn(t[1])}}(n);s=e.header,r=e.payload}catch(i){t.push(i)}if(s){const e=this.checkJwtHeader(s);t.push(...e)}if(r){const e=this.checkJwtPayload(r);t.push(...e)}if(t.length)if(this.usingBokens)Un.log(`JWT Errors detected by AuthProvider when using bokens: ${t.join("\n")}`);else{console.warn("[TalkJS] Authentication token appears to be generated incorrectly. Will still attempt to authenticate, but TalkJS may not work as expected. See below for a description of any problems and how to fix them.");const n=t.length>1;t.forEach(((e,t)=>{const s=n?`Reason ${t+1}:`:"Reason:";console.warn(`[TalkJS] ${s} ${e}`)})),console.warn(`[TalkJS]: Authentication token: "${e}"`)}}checkJwtHeader(e){const t=[],n=e.alg;return void 0===n?t.push('Token header must contain `"alg": "HS256"`, but no `alg` was specified.'):"string"!=typeof n?t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):"HS256"!==n&&t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was set to "${n}" instead. HS256 is the only supported algorithm.`),t}checkJwtPayload(e){const t=[],n=e.iss;void 0===n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was missing.`):"string"!=typeof n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):n!==this.appId&&t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was set to "${n}" instead.`);const s=e.sub;void 0===s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was missing.`):"string"!=typeof s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was ${typeof s} instead of a string. Make sure you wrap the value in "".`):s!==this.userId&&t.push(`Token payload must contain a \`sub\` claim set to your userId ID (${this.userId}), but \`sub\` was set to "${s}" instead.`);const r=e.tokenType;void 0===r?t.push('Token payload must contain a `"tokenType": "user"` claim, but no `tokenType` was specified.'):"string"!=typeof r?t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was ${typeof r} instead of a string. Make sure you wrap the value in "".`):"user"!==r&&t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was set to "${r}" instead.`);const i=e.exp;void 0===i||("number"!=typeof i?t.push(`Token payload contains an \`exp\` claim, but \`exp\` was ${typeof r} instead of a number. If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Don't wrap the value in "".`):i<1e9?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01.`):i>1e11?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`):i<(new Date).getTime()/1e3&&t.push(`Token payload contains an \`exp\` claim, but \`exp\` (${i}, representing ${new Date(1e3*i).toLocaleDateString()}) appears to be in the past, meaning the token will be rejected. This error can also happen if your device's clock is set incorrectly, in which case the token will still work.`));const a=e.nbf;return void 0===a||("number"!=typeof a?t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` was ${typeof r} instead of a number. If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01.`):a>1e11&&t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` is very large (${a}, representing ${new Date(1e3*a).toLocaleDateString()}). If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`)),t}sendBokenRequest(e,t){return h(this,null,(function*(){let n=0;const s=e.getBokensUrl(this.appId,this.userId,t),r=yield Fn({method:"GET",url:s,attempts:1e4,shouldRetry:e=>{if(e instanceof Error)return!0;if(401===e.status)throw"Check that you provided a valid signature.";if(404===e.status)throw"Check that you specified the correct App ID.";if(429===e.status||502===e.status)return!0;if(e.status>=400&&e.status<500)throw`Unexpected HTTP ${e.status} response when fetching auth token. Check that you configured the session correctly.`;if(n++,n>=5)throw`Unexpected HTTP ${e.status} response when fetching auth token, retrying did not help.`;return!0}});return(yield r.json()).boken}))}}function qn(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(atob(t).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));return JSON.parse(n)}catch(t){throw`Could not base64-decode and JSON-parse token section: ${e}. Check that you base-64 encoded the section correctly.`}}class Hn{constructor(e){this.target=e}deref(){return this.target}}const Ln=new class{constructor(){this.registry={}}getOrCreate(e){var t;const n=this.key(e),s=null==(t=this.registry[n])?void 0:t.deref();if(s)return s;const r=new Gn(e),i=globalThis.WeakRef?new WeakRef(r):new Hn(r);return this.registry[n]=i,r}deregister(e,t){const n=this.key({appId:e,userId:t});delete this.registry[n]}key({appId:e,userId:t}){return`${e}:${t}`}};class Gn{constructor(e){!function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in TalkSession#constructor."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of TalkSession#constructor is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of TalkSession#constructor is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of TalkSession#constructor must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of TalkSession#constructor must be a function.")}(e);const{appId:t,userId:n,token:s,tokenFetcher:r,signature:i}=e;this._appId=t,this._apiUrls=e.apiUrls?new Mn(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):Mn.fromHost(e.host),this._authProvider=new Wn(this._apiUrls,t,n,s,r,i);const a=Math.random().toString().split(".")[1];this._realtimeClient=new He(this._apiUrls.getRealtimeWsUrl(t,n,"1.5.5",a,e.clientBuild),n,this._authProvider),this.currentUser=new ze(this._realtimeClient.userId,this._realtimeClient),this._terminationReason=y(),this._terminationReason.promise.then((e=>{console.error(`[TalkSession] ${e}`)})),function(e,t,n){return h(this,null,(function*(){return Fn({method:"GET",url:`${t}/${e}/app`,authProvider:n}).then((e=>200===e.status||404!==e.status&&(console.warn(`[TalkJS] Received unexpected ${e.status} status code when validating app ID. Assuming that the app ID is valid.`),!0))).catch((e=>{if("string"!=typeof e&&"status"in e){const t=e;return 200===t.status||404!==t.status&&(console.warn(`[TalkJS] Received unexpected ${t.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)}return console.warn("[TalkJS] Encountered network issues when validating app ID. Assuming that the app ID is valid."),!0}))}))}(this._appId,this._apiUrls.internalHttpApiUrl,this._authProvider).then((e=>{e||this.terminate(new Error(`The app ID ${this._appId} does not exist. Make sure you are using the correct app ID as found on the TalkJS dashboard. App IDs are case-sensitive.`))})),this._authProvider.onTokenRefreshFailed((e=>{this.terminate(new Error(`Could not authenticate, cannot recover automatically: ${e}`))}))}onError(e){const t=y();return Promise.race([t.promise,this._terminationReason.promise]).then((t=>{"UNSUBSCRIBED"!==t&&e(t)})),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){if("string"!=typeof e)throw new Error(`Creating UserRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating UserRef failed because ID "${e}" is an empty string`);return new ze(e,this._realtimeClient)}conversation(e){if("string"!=typeof e)throw new Error(`Creating ConversationRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating ConversationRef failed because ID "${e}" is an empty string`);return new Tn(e,this._realtimeClient)}subscribeConversations(e){return this._realtimeClient.subscribe(["me","conversations"],e)}terminate(e){Ln.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return zn(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,t)}uploadImage(e,t){return zn(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"image"},t))}uploadVideo(e,t){return zn(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"video"},t))}uploadAudio(e,t){return zn(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"audio"},t))}uploadVoice(e,t){return zn(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"voice"},t))}}function zn(e,t,n,s){return h(this,arguments,(function*(e,t,n,{subtype:s,filename:r,width:i,height:a,duration:o}){const u=new FormData;return u.set("file",n,r),void 0!==s&&u.set("subtype",s),void 0!==i&&u.set("width",i.toString()),void 0!==a&&u.set("height",a.toString()),void 0!==o&&u.set("duration",o.toString()),Fn({method:"POST",url:e,data:u,authProvider:t}).then((e=>e.json())).then((e=>e.attachmentToken)).catch((e=>h(this,null,(function*(){if(e instanceof Response){const t=yield e.json(),n=`Unexpected response when uploading file, status code ${e.status} ${t.errorCode}, ${t.reasons}`;throw new Error(n)}throw e}))))}))}exports.getTalkSession=function(e){if(!e)throw new Error("[TalkJS] Must provide an options object to `getTalkSession`");return e.forceCreateNew?new Gn(e):Ln.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){x=e};
|
|
1
|
+
"use strict";var e,t,n,s,r=Object.defineProperty,i=Object.defineProperties,a=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable,c=e=>{throw TypeError(e)},h=(e,t,n)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))u.call(t,n)&&h(e,n,t[n]);if(o)for(var n of o(t))l.call(t,n)&&h(e,n,t[n]);return e},p=(e,t)=>i(e,a(t)),f=(e,t)=>{var n={};for(var s in e)u.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&o)for(var s of o(e))t.indexOf(s)<0&&l.call(e,s)&&(n[s]=e[s]);return n},m=(e,t,n)=>t.has(e)||c("Cannot "+n),g=(e,t,n)=>(m(e,t,"read from private field"),n?n.call(e):t.get(e)),v=(e,t,n)=>t.has(e)?c("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,s)=>(m(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),y=(e,t,n)=>new Promise(((s,r)=>{var i=e=>{try{o(n.next(e))}catch(at){r(at)}},a=e=>{try{o(n.throw(e))}catch(at){r(at)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(i,a);o((n=n.apply(e,t)).next())}));function w(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(C(e,t.value));throw"unreachable"}function C(e,t){let n;return n=Array.isArray(t.reasons)?t.reasons.join():JSON.stringify(t.reasons),`${e} failed, got status ${t.status} ${t.errorCode}, reasons: ${n}`}function A(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if("*"!==t[n]&&e[n]!==t[n])return!1;return!0}function E(e){return e<=0?Promise.resolve():new Promise((t=>setTimeout(t,e)))}function k(e,t){return e*(1-t+2*Math.random()*t)}Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=()=>!0;function I(e,t,n){return y(this,arguments,(function*(e,t,{initialDelay:n,maxDelay:s,log:r,shouldRetry:i=x}){return t().catch((a=>y(this,null,(function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*n*1.2,u=k(s?Math.min(1e3*s,o):o,.05);return E(u).then((()=>I(e-1,t,{initialDelay:u/1e3,maxDelay:s,log:r,shouldRetry:i})))}))))}))}function T(){const e={},t=new Promise((function(t,n){e.resolve=t,e.reject=n}));return e.promise=t,e}class D{constructor(e,t,n){this.layer=e,this.states=t,this.transitions=n,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 n=this.state;this._state=t.to,t.afterTransition({from:n,to:this.state})}canTransition(e){const t=this.transitions[e];return!!t&&("ANY"===t.from||t.from.includes(this.state))}}function S(e){return{ok:!0,value:e}}function M(e){return{ok:!1,where:"client",value:e}}function F(e){return{ok:!1,where:"server",value:e}}function B(){const e={},t=new Promise((t=>{e.ok=e=>y(this,null,(function*(){return t(S(e))})),e.clientErr=e=>t(M(e)),e.serverErr=e=>t(F(e)),e.resolve=e=>t(e)}));return e.promise=t,e}let R=null;class N{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new D("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(R)return R;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=>y(this,[e],(function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=k(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),S(void 0)):M("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 O{constructor(e,t){this.handlers=t,this.socket=new N(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t,n,s){const r=`/${n.map((e=>encodeURIComponent(e))).join("/")}`,i=JSON.stringify([e,t,r,s]);return this.socket.send(i)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){if("Auth token expired"!==e.data)try{const t=JSON.parse(e.data);if("PUBLISH"===t[1]){const e=t[0],n=JSON.stringify([e,"ACK"]);this.socket.send(n);const s=t.slice(2),r=[];s.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],n=t[1],s=t[2];this.handlers.onResponse(e,n,s)}}catch(t){}else this.handlers.onAuthExpired()}}class P{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)}}class _{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class j{constructor(e,t){this.handlers=t,this.seqCounter=new _,this.responseHandlers={},this.heartbeats=new U(this),this.socket=new O(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,n)=>{this.heartbeats.serverActive(),this.onResponse(e,t,n)},onPublish:(e,t)=>{this.heartbeats.serverActive(),this.handlers.onPublish(e,t),this.heartbeats.clientActive()},onAuthExpired:()=>{this.heartbeats.serverActive(),this.handlers.onAuthExpired()}})}call(e,t,n){const s=this.seqCounter.next(),r=B();this.responseHandlers[s]=r;const i=this.socket.call(s,e,t,n);return i.ok||r.resolve(i),this.heartbeats.clientActive(),r.promise}onResponse(e,t,n){return y(this,null,(function*(){const s=this.responseHandlers[e];s&&(200===t?s.ok({status:t,data:n}):s.serverErr({status:t,errorCode:n.errorCode,reasons:n.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 U{constructor(e){this.connection=e,this.clientInactivityTimer=new P(25e3),this.serverInactivityTimer=new P(1e4),this.serverTimeoutTimer=new P(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("GET",["ping"],{}).catch((()=>{}))}}class ${constructor(e,t,n){this.authProvider=t,this.handlers=n,this.stateMachine=new D("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>y(this,null,(function*(){yield this.renewSession()}))},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>y(this,null,(function*(){this.authProvider.refreshToken(),yield this.renewSession()}))},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>y(this,null,(function*(){yield this.renewSession()}))},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>y(this,null,(function*(){this.authProvider.refreshToken(),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:()=>y(this,null,(function*(){this.handlers.onNotReady(),this.authProvider.refreshToken(),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 j(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")}))}call(e,t,n){const s=this.connection.call(e,t,n);return s.then((e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")})),s}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs()}destroy(){this.stateMachine.transition("destroy")}renewSession(){return y(this,null,(function*(){const e=yield this.authProvider.getToken(),t=yield this.connection.call("POST",["session","renew"],{token:e});if(!t.ok&&"client"===t.where)return;const n=t.value;if(n.status,200===n.status){const t=n.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===n.status)return void("LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed"));if(400===n.status)return void this.authProvider.emitTokenRefreshFailed(C("Authentication",n));if(402===n.status)return void this.authProvider.emitTokenRefreshFailed(C("Authentication",n));const s=5e3*Math.random()+5e3;setTimeout((()=>{this.call("POST",["session","renew"],{token:e}).catch((()=>{}))}),s)}))}}class W{constructor(e,t,n){this.handlers=n,this.stateMachine=new D("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 P(3e3),this.connection=new $(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}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e,t,n){return y(this,null,(function*(){this.inactivityTimer.stop(),this.pendingCalls++,this.logTrace("Called",t,n);const s=yield this.connection.call(e,t,n);return this.pendingCalls--,this.logTrace("Received",t,n),"SUBSCRIBE"===e&&s.ok?(this.activeSubscriptions++,this.logTrace("Subscribed",t,n)):"UNSUBSCRIBE"===e&&s.ok&&(this.activeSubscriptions--,this.logTrace("Unsubscribed",t,n)),this.inactive&&this.inactivityTimer.schedule((()=>{this.stateMachine.transition("stop")})),s}))}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}logTrace(e,t,n){}}class q{constructor(e,t,n){this.handlers=n,this.stateMachine=new D("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 W(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}call(e,t,n){return"READY"===this.stateMachine.state?this.connection.call(e,t,n):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e||"UNSUBSCRIBE"===e?this._subscribe(e,t,n):this._call(e,t,n))}_subscribe(e,t,n){const s=t.join("/"),r=this.subscribeQueue[s];if(r&&r.method===e)return r.deferred.promise;r&&r.method!==e&&(r.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[s]);const i={deferred:B(),method:e,path:t,data:n};return this.subscribeQueue[s]=i,i.deferred.promise}_call(e,t,n){const s={deferred:B(),method:e,path:t,data:n};return this.callQueue.push(s),s.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 y(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.method,t.path,t.data).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}}const H="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class L{constructor(e,t){this.clearPendingBatch=e,this.sendCalls=t,this.sent=!1,H((()=>this.send()))}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class G extends L{constructor(e,t){super(t,(()=>{this.sendSubscribe(),this.sendGet()})),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e,t){return G.isCorrectBatchTypeFor(e,t)}static isCorrectBatchTypeFor(e,t){return A(t,["users","*"])&&("GET"===e||"SUBSCRIBE"===e)}push(e,t,n){const s=t[1],r=B();return"GET"===e?this.getCalls.push({userId:s,deferred:r}):this.subscribeCalls.push({userId:s,deferred:r}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),r.promise}sendGet(){return y(this,null,(function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map((e=>e.userId)))],t=yield this.connection.call("GET",["users"],{ids:e,includePrivateFields:!1});if(t.ok)for(const n of this.getCalls){const e=t.value.data[n.userId];e?n.deferred.ok({status:200,data:e}):n.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("SUBSCRIBE",["users"],{ids:e}).then((e=>this.subscribeCalls.forEach((t=>t.deferred.resolve(e)))))}}class z extends L{constructor(e,t,n){super(n,(()=>this.sendMutate())),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e,t){return!!z.isCorrectBatchTypeFor(e,t)&&t[1]===this.conversationId}static isCorrectBatchTypeFor(e,t){return A(t,["conversations","*","participants","*"])&&("PUT"===e||"POST"===e||"PATCH"===e)}push(e,t,n){const s=t[3],r=B();return this.calls.push({action:{id:s,method:e,params:n},deferred:r}),100===this.calls.length&&this.send(),r.promise}sendMutate(){return y(this,null,(function*(){const e=this.calls.map((e=>e.action)),t=yield this.connection.call("POST",["conversations",this.conversationId,"participants"],{actions:e});if(!t.ok)return void this.calls.forEach((e=>e.deferred.resolve(t)));const n=t.value.data.responses;for(let s=0;s<n.length;s++){const e=this.calls[s].deferred,t=n[s];200===t.status?e.ok(p(d({},t),{data:{}})):e.serverErr(t)}}))}}class J{constructor(e,t,n){this.pendingBatch=null,this.connection=new q(e,t,n)}call(e,t,n){return y(this,null,(function*(){var s;if(null==(s=this.pendingBatch)?void 0:s.canPush(e,t))return this.pendingBatch.push(e,t,n);this.pendingBatch&&this.pendingBatch.send();const r=this.createEmptyBatchFor(e,t);return r?(this.pendingBatch=r,r.push(e,t,n)):this.connection.call(e,t,n)}))}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e,t){if(G.isCorrectBatchTypeFor(e,t))return new G(this.connection,(()=>this.pendingBatch=null));if(z.isCorrectBatchTypeFor(e,t)){const e=t[1];return new z(e,this.connection,(()=>this.pendingBatch=null))}return null}}const Y={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class Q{constructor(e,t,n){this.throttler=new V,this.alive=!0,this.connection=new J(e,t,n)}call(e,t,n){return y(this,null,(function*(){let s=0;for(;this.alive;){const r=yield this.connection.call(e,t,n);if((r.ok||"client"!==r.where||"SOCKET_NOT_READY"!==r.value)&&(r.ok||"server"!==r.where||500!==r.value.status)||s++,10===s)return r;if(r.ok||"client"!==r.where){const e=r.value,t=e.status,n=Y[t];if("RESOLVE"===n)return this.throttler.resetDelay(),r;if("RETRY"===n)continue;if("DELAY"===n){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===r.value)return M("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==r.value&&("SOCKET_NOT_READY"!==r.value?r.value:yield this.throttler.wait())}return M("SESSION_DESTROYED")}))}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class V{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=k(this.currentDelayMs,.05),n=this.lastCall+t,s=Math.max(0,n-e);return this.lastCall=e+s,this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs),E(s)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function Z(e){return e.map((e=>encodeURIComponent(e))).join()}class K{constructor(){this.paths={}}add(e){this.paths[Z(e)]=e}delete(e){delete this.paths[Z(e)]}has(e){return Object.hasOwnProperty.call(this.paths,Z(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach((t=>e(t)))}}class X{constructor(e,t,n){this.handlers=n,this.targetSubscriptions=new K,this.connection=new Q(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)}})}call(e,t,n){return this.connection.call(e,t,n)}subscribe(e){return y(this,null,(function*(){return this.targetSubscriptions.add(e),this.connection.call("SUBSCRIBE",e,{})}))}unsubscribe(e){return y(this,null,(function*(){return this.targetSubscriptions.delete(e),this.connection.call("UNSUBSCRIBE",e,{})}))}resubscribe(e){return y(this,null,(function*(){const t=yield this.connection.call("SUBSCRIBE",e,{});t.ok||this.handlers.onResubscribeError(e,t)}))}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}function ee(e){return Object.freeze(e)}function te(e){return ee(e.map((e=>function(e){switch(e.type){case"text":return Object.freeze({type:"text",children:ne(e.children)});case"file":case"location":return Object.freeze(e)}}(e))))}function ne(e){return ee(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:ne(e.children)}));case"mention":case"autoLink":case"codeSpan":case"customEmoji":return Object.freeze(e)}}(e))))}function se(e,t){return void 0===t?e:t}function re(e,t){return void 0===t?e:ee(t)}function ie(e,t){if(void 0===t)return e;if(null===t)return ee({});const n=d({},e);for(const s in t){const e=t[s];null===e?delete n[s]:n[s]=e}return ee(n)}function ae(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 n=0;n<e.length;n++)if(!ae(e[n],t[n]))return!1}else{const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const s of n){if(!Object.hasOwnProperty.call(t,s))return!1;if(!ae(e[s],t[s]))return!1}}return!0}class oe{constructor(){this.prev=Promise.resolve()}runExclusive(e){return y(this,null,(function*(){const t=this.prev.then((()=>e()));return this.prev=t,t}))}}class ue{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,n;const s=null==(t=this.getPointer)?void 0:t.seq;if(void 0!==s&&e<=s)return!1;const r=null==(n=this.pendingPointer)?void 0:n.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 n=this.mostRecentState.resultPromise.then((e=>e.ok?t(e):e));this.pendingStates.push({seq:e,resultPromise:n})}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 le extends ue{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 ce extends le{constructor(e,t){const n=new Promise((e=>setTimeout(e))).then((()=>this.fetchInitial(e)));super({seq:e,resultPromise:n},t.onTeardown),this.initialSeq=e,this.getDeepMutex=new oe,this.lastDeep=void 0}refetchInitial(e){return y(this,null,(function*(){const t=this.mostRecentState.resultPromise,n=this.fetchInitial(e),[s,r]=yield Promise.all([t,n]);return void 0!==s&&s.ok&&r.ok&&this.equal(s.value,r.value)?s:r}))}refetch(e){if(null!==this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.set(t)}changedBetween(e,t){return y(this,null,(function*(){if(e>=t)return!1;const n=this.get(t),s=yield n.resultPromise;return!!s.ok&&(s.value.lastChanged>Math.max(this.initialSeq,e)&&s.value.lastChanged<=t||(yield this.anyChildChanged(e,t,s.value)))}))}getDeep(e){return y(this,null,(function*(){return this.getDeepMutex.runExclusive((()=>y(this,null,(function*(){var t;if(null!==this.error)return this.error;const n=null==(t=this.lastDeep)?void 0:t.seq;if(e===n)return this.lastDeep.deep;if(void 0!==n){if(e<n)throw`Trying to load seq ${e} when we have previously loaded seq ${n}`;if(!(yield this.changedBetween(n,e)))return this.lastDeep.seq=e,this.lastDeep.deep}const s=this.get(e).resultPromise,r=s.then((t=>t.ok?this.loadNested(e,t.value):t));this.lastDeep={seq:e,shallow:s,deep:r};const i=yield r;return i.ok||this.setError(i),i}))))}))}}class he extends ce{constructor(e,t,n){super(e,n),this.emitMutex=t,this.unsubscribeTimer=new de,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive((()=>y(this,null,(function*(){yield this.emit(e)}))))}registerInternalSubscription(){this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,this.startUnsubscribeTimerIfOrphan())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){return this.unsubscribeTimer.stop(),this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult),()=>{this.listeners=this.listeners.filter((t=>t!==e)),this.startUnsubscribeTimerIfOrphan()}}startUnsubscribeTimerIfOrphan(){0===this.referencedByOtherStores&&0===this.listeners.length&&this.unsubscribeTimer.restart((()=>{this.setError(M("UNSUBSCRIBED"))}),this.unsubscribeDebounceMs)}emit(e){return y(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 n=yield this.getDeep(e);n!==this.lastEmitResult&&(this.lastEmitResult=n,this.listeners.forEach((e=>e(n))))}))}}class de{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 pe,fe={};function me(e,t){const n=t.lastIndex;let s;const r=[];for(;null!==(s=t.exec(e));)r.push(s);return t.lastIndex=n,r}function ge(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function ve(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(pe)return fe;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}pe=1,Object.defineProperty(fe,"__esModule",{value:!0}),fe.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},fe.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,n){t(e,Array),e&&e.length>0&&t(e[0],n)},e.optional=function(e,n){void 0!==e&&t(e,n)},e.falsy=function(e){},e.never=function(e){}})(ve||(ve={}));const be=ve,ye=/^\/.*[^\\]\/[im]*$/;function we(e){return!!ye.test(e)&&!Ce(e).test("")}function Ce(e){const t=e.match(/^\/(.*[^\\])\/(.*)$/);if(!t)throw new Error(`Expected ${e} to be a (non-empty) regex`);let n=t[2]||"";return n=n.replace(/[^im]/g,"")+"g",new RegExp(t[1],n)}class Ae{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:n,allowedMatches:s,forbiddenMatches:r,suppressLinks:i,suppressEmailAddresses:a,suppressPhoneNumbers:o,replacement:u}){be.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==i,this.suppressEmailAddresses=!1!==a,this.suppressPhoneNumbers=!1!==o,this.allowedHostnames=t||[],this.allowedPhoneNrs=(n||[]).filter((e=>e)).map((e=>e.replace(/[^0-9]/g,""))),this.allowedMatches=(s||[]).filter(we).map((e=>Ce(e))),this.forbiddenMatches=(r||[]).filter(we).map((e=>Ce(e))),be((()=>this.allowedMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),be((()=>this.forbiddenMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),u=null==u?void 0:u.trim(),this.replacement=u&&u.length>0?u:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function Ee(e,t){return e.map((e=>function(e,t){if("text"===e.type)return ke(e.children,function(e){var t,n,s,r,i,a,o,u,l,c,h,d,p;let f="";return e.t&&(f=`(${e.t("CONTACT_INFORMATION_HIDDEN")})`),{formattedLinks:null!=(t=e.formattedLinks)?t:"plaintext",markup:null!=(n=e.markup)&&n,useFallbackMentions:null!=(s=e.useFallbackMentions)&&s,sameTabLinkRules:null!=(r=e.sameTabLinkRules)?r:[],enableEmojiImageFallback:null!=(i=e.enableEmojiImageFallback)&&i,highlight:null!=(a=e.highlight)?a:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(u=e.suppression)?u:new Ae({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(c=e.contactInfoHiddenText)?c:null==(l=e.suppression)?void 0:l.replacement)?h:f,customEmojiUrls:null!=(d=e.customEmojiUrls)?d:{},enableActions:null==(p=e.enableActions)||p}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${ge(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${ge(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${ge(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,`📎 ${ge(e.url)}`):"location"===e.type?"📍":""}(e,t))).join("\n\n")}function ke(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 ke(e.children,t);case"bulletlist":case"bulletList":return"\n"+ke(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+ke(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 xe(e){return ee({id:e.id,name:e.name,custom:ee(e.custom),locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage})}function Ie(e,t){return ee({user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt})}function Te(e){const t=Object.entries(e).map((([e,t])=>ee({emoji:e,count:t.count,currentUserReacted:t.currentUserReacted})));return t.sort(((e,t)=>e.emoji.localeCompare(t.emoji))),ee(t)}class De extends he{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return y(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["users",this.userId],{includePrivateFields:!1},{bypassCache:!0});return t.ok?S({snapshot:xe(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?S({snapshot:null,lastChanged:e}):t}))}equal(e,t){return ae(e.snapshot,t.snapshot)}loadNested(e,t){return y(this,null,(function*(){return S(t)}))}userCreated(e,t){this.mutate(e,(n=>null!==n.value.snapshot?n:S({snapshot:xe(t.state),lastChanged:e})))}userEdited(e,t){this.mutate(e,(n=>{const s=n.value.snapshot;return null===s?(console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."),n):S({snapshot:{id:s.id,name:se(s.name,t.diff.name),custom:ie(s.custom,t.diff.custom),locale:se(s.locale,t.diff.locale),photoUrl:se(s.photoUrl,t.diff.photoUrl),role:se(s.role,t.diff.role),welcomeMessage:se(s.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})}))}getFromCache(){return y(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?F({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):S({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}}):M("NOT_IN_CACHE")}))}teardownNested(e){}anyChildChanged(e,t,n){return y(this,null,(function*(){return!1}))}}class Se extends ce{constructor(e,t,n,s){super(e,{}),this.conversationId=t,this.message=n,this.realtimeClient=s}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return y(this,null,(function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"messages",this.message],{},{bypassCache:!0});if(!e.ok)return e;t=e.value.data}return S({lastChanged:e,sender:null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),data:{id:t.id,type:t.type,custom:ee(t.custom),createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:Ee(t.content,{}),content:te(t.content),reactions:Te(t.reactions)}})}))}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 ae(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,(function*(){var s;const r=null==(s=n.sender)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))}))}loadNested(e,t){return y(this,null,(function*(){var n,s,r;const i=yield null==(s=null==(n=t.sender)?void 0:n.store)?void 0:s.getDeep(e);if(!1===(null==i?void 0:i.ok))return i;if(null===t.data)return S({snapshot:null});const a=null==i?void 0:i.value;return S({snapshot:ee({sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:ee(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,(n=>{if(null===n.value.data)return n;const s=n.value.data.content,r=(i=s,void 0===(a=t.diff.content)?i:te(a));var i,a;const o=s===r?n.value.data.plaintext:Ee(r,{});return S({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:n.value.data.referencedMessageId,editedAt:se(n.value.data.editedAt,t.diff.editedAt),custom:ie(n.value.data.custom,t.diff.custom),plaintext:o,content:r,reactions:Me(n.value.data.reactions,t.diff.reactions)}})}))}messageDeleted(e,t){this.mutate(e,(n=>null===n.value.data?n:this.messageId===t.messageId?(this.teardownNested(n.value),S({lastChanged:e,sender:null,data:null})):n.value.data.referencedMessageId===t.messageId?S({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:null,editedAt:n.value.data.editedAt,custom:n.value.data.custom,plaintext:n.value.data.plaintext,content:n.value.data.content,reactions:n.value.data.reactions}}):n))}getFromCache(){return y(this,null,(function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.data)return F({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const n=t.value,{sender:s}=n,r=f(n,["sender"]),i={};return r.data.reactions.forEach((e=>{i[e.emoji]={count:e.count,currentUserReacted:e.currentUserReacted}})),S({status:200,data:p(d({},r.data),{senderId:null!=(e=null==s?void 0:s.store.userId)?e:null,reactions:i})})}))}}function Me(e,t){if(void 0===t)return e;const n=e.map((e=>{const n=t[e.emoji];return void 0===n?e:ee(null===n?p(d({},e),{count:0}):{emoji:e.emoji,count:se(e.count,n.count),currentUserReacted:se(e.currentUserReacted,n.currentUserReacted)})})).filter((e=>e.count>0)),s=new Set(n.map((e=>e.emoji)));for(const r in t){const e=t[r];e&&!s.has(r)&&n.push(ee({emoji:r,count:e.count,currentUserReacted:e.currentUserReacted}))}return n.sort(((e,t)=>e.emoji.localeCompare(t.emoji))),ee(n)}class Fe extends ce{constructor(e,t,n,s){super(e,{}),this.createdAt=t,this.dataStore=n,this.referencedDataStore=s}get messageId(){return this.dataStore.messageId}fetchInitial(e){return y(this,null,(function*(){return S({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,n){return y(this,arguments,(function*(e,t,{dataStore:n,referencedDataStore:s}){return!0===(yield n.changedBetween(e,t))||!0===(yield null==s?void 0:s.changedBetween(e,t))}))}loadNested(e,t){return y(this,null,(function*(){var n,s,r;const i=yield t.dataStore.getDeep(e);if(!i.ok)return i;const a=i.value;if(null===a.snapshot)return S({snapshot:null});const o=yield null==(n=t.referencedDataStore)?void 0:n.getDeep(e);if(o&&!o.ok)return o;const u=null!=(s=null==o?void 0:o.value)?s:null,l=null!=(r=null==u?void 0:u.snapshot)?r:null;return S({snapshot:ee({id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:ee(a.snapshot.custom),createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:l,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content,reactions:a.snapshot.reactions})})}))}}class Be extends he{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,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._loadMoreMessages(t)}})),super.listen(e)}fetchInitial(e){return y(this,null,(function*(){const t=this.onlyUsedInternally?1:30,n=yield Re({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return n.ok?null===n.value.messages?S({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):Ne({seq:e,messages:n.value.messages,cursor:n.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):n}))}teardownNested(e){if(e.stores){const t=M("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t))),e.inWindow.forEach((e=>e.setError(t)))}}anyChildChanged(e,t,n){return y(this,null,(function*(){for(const s in n.stores){const r=n.stores[s];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1}))}lastMessageChangedBetween(e,t){return y(this,null,(function*(){if(e>=t)return!1;const n=yield this.get(t).resultPromise;if(!n.ok)return!1;if(n.value.lastMessageChanged>e)return!0;if(null===n.value.stores)return!1;const s=n.value.inWindow[0];return void 0!==s&&!0===(yield s.changedBetween(e,t))}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!ae(Object.keys(e.stores),Object.keys(t.stores))&&!!ae(e.inWindow.map((e=>e.messageId)),t.inWindow.map((e=>e.messageId)))&&ae(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,(function*(){if(null===t.stores)return S({snapshot:null,loadedAll:!0});const n=yield Promise.all(t.inWindow.map((t=>t.getDeep(e)))),s=n.find((e=>!e.ok));return s||S({snapshot:ee(n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot))),loadedAll:null===t.windowEnd})}))}loadMore(e){return y(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=T();this.pendingLoadMore=t.promise,yield this._loadMoreMessages(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreMessages(e=30){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield Re({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.messages.loadedmore",conversationId:this.conversationId,data:s})}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n: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."),n):Ne({seq:e,prevState:n.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,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.created' event for a nonexistent conversation."),n;if(n.value.windowEnd&&t.state.createdAt<n.value.windowEnd.oldestMessageTs)return n;if(Object.hasOwnProperty.call(n.value.stores,t.state.id))return n;const s=d({},n.value.stores),r=new Se(e,this.conversationId,t.state,this.realtimeClient);s[t.state.id]=r;const i=t.state.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Se(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Fe(e,t.state.createdAt,r,a),u=[...n.value.inWindow,o];u.sort(((e,t)=>t.createdAt-e.createdAt));const l=u[0].messageId===t.messageId?e:n.value.lastMessageChanged;return S({lastChanged:e,lastMessageChanged:l,stores:s,inWindow:u,windowEnd:n.value.windowEnd})}))}messageEdited(e,t){this.mutate(e,(n=>{var s;return null===n.value.stores?(console.warn("[TalkJS] Received a 'message.edited' event for a nonexistent conversation."),n):(null==(s=n.value.stores[t.messageId])||s.messageEdited(e,t),n)}))}messageDeleted(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.deleted' event for a conversation that we thought didn't exist."),n;if(Object.values(n.value.stores).forEach((n=>n.messageDeleted(e,t))),void 0===n.value.stores[t.messageId])return n;const s=d({},n.value.stores);delete s[t.messageId];const r=n.value.inWindow.filter((e=>e.messageId!==t.messageId));if(t.newLastMessage&&0===r.length){const n=new Se(e,this.conversationId,t.newLastMessage,this.realtimeClient);s[n.messageId]=n;const i=t.newLastMessage.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Se(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Fe(e,t.newLastMessage.createdAt,n,a);r.push(o)}const i=void 0!==t.newLastMessage?e:n.value.lastMessageChanged;return S({lastChanged:e,lastMessageChanged:i,stores:s,inWindow:r,windowEnd:n.value.windowEnd})}))}conversationCleared(e,t){this.mutate(e,(t=>{var n;return 0===(null==(n=t.value.inWindow)?void 0:n.length)&&null===t.value.windowEnd?t:(this.teardownNested(t.value),S({lastChanged:e,lastMessageChanged:e,stores:{},inWindow:[],windowEnd:null}))}))}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.stores?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.stores?t:(this.teardownNested(t.value),S({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getMessageFromCache(e){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.stores)return M("NOT_IN_CACHE");const n=t.value.stores[e];return void 0===n?M("NOT_IN_CACHE"):n.getFromCache()}))}}function Re(e){return y(this,arguments,(function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call("GET",["me","conversations",n,"messages"],r,{bypassCache:!0});if(i.ok){const{data:e,cursor:t}=i.value.data;return S({messages:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?S({messages:null,nextCursor:null}):i}))}function Ne({seq:e,prevState:t,messages:n,cursor:s,conversationId:r,realtimeClient:i}){var a,o,u,l;const c=t?d({},t.stores):{};for(const d of n)if(void 0===c[d.id]){const t=new Se(e,r,d,i);c[t.messageId]=t}for(const d of n){const t=d.referencedMessageId;if(t&&void 0===c[t]){const n=new Se(e,r,t,i);c[n.messageId]=n}}const h=t?[...t.inWindow]:[];for(const d of n)h.push(new Fe(e,d.createdAt,c[d.id],d.referencedMessageId?c[d.referencedMessageId]:null));h.sort(((e,t)=>t.createdAt-e.createdAt));const p=(null==(o=null==(a=null==t?void 0:t.inWindow)?void 0:a[0])?void 0:o.messageId)===(null==(u=null==h?void 0:h[0])?void 0:u.messageId)&&null!=(l=null==t?void 0:t.lastMessageChanged)?l:e;return S(null===s?{lastChanged:e,lastMessageChanged:p,stores:c,inWindow:h,windowEnd:null}:{lastChanged:e,lastMessageChanged:p,stores:c,inWindow:h,windowEnd:{cursor:s,oldestMessageTs:n[n.length-1].createdAt}})}class Oe extends he{constructor(e,t,n,s,r){super(e,s,r),this.convData=t,this.realtimeClient=n,this.unsubscribeDebounceMs=0}fetchInitial(e){return y(this,null,(function*(){return S({lastChanged:e,convData:this.convData})}))}teardownNested(e){e.convData.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,(function*(){return n.convData.store.changedBetween(e,t)}))}equal(e,t){return!0}loadNested(e,t){return y(this,null,(function*(){return t.convData.store.getDeep(e)}))}getFromCache(){return y(this,null,(function*(){return this.convData.store.getFromCache()}))}}function Pe(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(e[n],n)}function _e(e,t){return function(e){let n={};return Pe(e,((e,s)=>{const[r,i]=(([e,n])=>[e,t(n,e)])([s,e],0);n[r]=i})),n}(e)}class je extends he{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return y(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"typing"],{},{bypassCache:!0});if(!t.ok&&"server"===t.where&&404===t.value.status)return S({data:null,lastChanged:e});if(!t.ok&&"server"===t.where&&403===t.value.status&&"NOT_A_PARTICIPANT"===t.value.errorCode)return S({data:null,lastChanged:e});if(!t.ok)return t;const n=t.value.data;return n.many?S({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e}):S({data:n,userSubscriptions:_e(n.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t]))),lastChanged:e})}))}equal(e,t){return ae(e.data,t.data)}loadNested(e,t){return y(this,null,(function*(){if(null===t.data)return S({snapshot:null,lastChanged:t.lastChanged});if(t.data.many)return S({snapshot:ee({many:!0}),lastChanged:t.lastChanged});const n=Object.entries(t.data.usersTyping).sort((([e,t],[n,s])=>t-s)).map((([e,t])=>e)).map((n=>t.userSubscriptions[n].store.getDeep(e))),s=yield Promise.all(n),r=s.find((e=>!e.ok));if(r)return r;const i=s.map((e=>e.value)),a=i.map((e=>e.snapshot)),o=i.map((e=>e.lastChanged)),u=Math.max(t.lastChanged,...o);return S({snapshot:ee({users:ee(a),many:!1}),lastChanged:u})}))}typingAvailable(e,t){this.mutate(e,(()=>S({data:t.state,userSubscriptions:t.state.many?{}:_e(t.state.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t]))),lastChanged:e})))}typingChanged(e,t){this.mutate(e,(n=>{if(null===n.value.data)return n;if(void 0===t.diff.many){if(!0===n.value.data.many)return n;const s=d({},n.value.data.usersTyping),r=d({},n.value.userSubscriptions);return Pe(t.diff.usersTyping,((e,t)=>{var n;"number"==typeof e?(s[t]=e,r[t]=this.realtimeClient.internalSubscribe(["users",t])):null===e&&(delete s[t],null==(n=r[t])||n.unsubscribe(),delete r[t])})),S({data:{usersTyping:s,many:!1},userSubscriptions:r,lastChanged:e})}if(!0===t.diff.many)return n.value.data.many?n:S({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e});if(!1===t.diff.many){if(!1===n.value.data.many)return n;const s=_e(t.diff.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t])));return S({data:t.diff,userSubscriptions:s,lastChanged:e})}throw t.diff,"Unreachable"}))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:S({data:null,lastChanged:e})))}teardownNested(e){e.data&&Pe(e.userSubscriptions,(e=>e.unsubscribe()))}anyChildChanged(e,t,n){return y(this,null,(function*(){var s;if(null===n.data)return!1;for(const r in n.userSubscriptions){const i=n.userSubscriptions[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1}))}}class Ue extends ce{constructor(e,t,n,s){super(e,{}),this.conversationId=t,this.participantData=n,this.realtimeClient=s}fetchInitial(e){return y(this,null,(function*(){return S({lastChanged:e,user:this.realtimeClient.internalSubscribe(["users",this.participantData.id]),data:this.participantData})}))}refetch(e){throw"Do not call refetch on participant data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){var n,s,r,i;return(null==(s=null==(n=e.user)?void 0:n.store)?void 0:s.userId)===(null==(i=null==(r=t.user)?void 0:r.store)?void 0:i.userId)&&ae(e.data,t.data)}teardownNested(e){var t;null==(t=e.user)||t.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,(function*(){var s;const r=null==(s=n.user)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))}))}loadNested(e,t){return y(this,null,(function*(){if(null===t.data)return S({snapshot:null});const n=yield t.user.store.getDeep(e);if(!1===n.ok)return n;const s=n.value.snapshot;return S({snapshot:Ie(t.data,s)})}))}participantEdited(e,t){this.mutate(e,(n=>null===n.value.data?n:S({lastChanged:e,user:n.value.user,data:{id:n.value.data.id,access:se(n.value.data.access,t.diff.access),notify:se(n.value.data.notify,t.diff.notify),joinedAt:n.value.data.joinedAt}})))}participantDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:(this.teardownNested(t.value),S({lastChanged:e,user:null,data:null}))))}getFromCache(){return y(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.data?F({status:404,errorCode:"PARTICIPANT_NOT_FOUND",reasons:["No participant with that ID exists"]}):S({status:200,data:e.value.data}):M("NOT_IN_CACHE")}))}}class $e extends he{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}fetchInitial(e){return y(this,null,(function*(){const t=yield We({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:10});return t.ok?null===t.value.participants?S({lastChanged:e,stores:null,inWindow:null,windowEnd:null}):qe({seq:e,participants:t.value.participants,cursor:t.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t}))}teardownNested(e){if(e.stores){const t=M("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t)))}}anyChildChanged(e,t,n){return y(this,null,(function*(){for(const s in n.stores){const r=n.stores[s];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!ae(Object.keys(e.stores),Object.keys(t.stores))&&ae(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,(function*(){if(null===t.stores)return S({snapshot:null,loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map((t=>t.getDeep(e)))),s=n.find((e=>!e.ok));if(s)return s;const r=n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot));return r.sort(((e,t)=>t.joinedAt-e.joinedAt)),S({snapshot:ee(r),loadedAll:null===t.windowEnd})}))}loadMore(e){return y(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=T();this.pendingLoadMore=t.promise,yield this._loadMoreParticipants(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreParticipants(e=10){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield We({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.participants.loadedmore",conversationId:this.conversationId,data:s})}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.participants?(console.warn("[TalkJS] When loading more participants, the conversation no longer existed. We should have been told about this."),n):qe({seq:e,prevStores:n.value.stores,participants:t.data.value.participants,cursor:t.data.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t.data))}participantCreated(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'participant.created' event for a nonexistent conversation."),n;if(n.value.windowEnd&&t.state.joinedAt<n.value.windowEnd.oldestParticipantTs)return n;if(Object.hasOwnProperty.call(n.value.stores,t.state.id))return n;const s=d({},n.value.stores),r=new Ue(e,this.conversationId,t.state,this.realtimeClient);return s[t.state.id]=r,S({lastChanged:e,stores:s,windowEnd:n.value.windowEnd})}))}participantEdited(e,t){this.mutate(e,(n=>{var s;return null===n.value.stores?(console.warn("[TalkJS] Received a 'participant.edited' event for a nonexistent conversation."),n):(null==(s=n.value.stores[t.userId])||s.participantEdited(e,t),n)}))}participantDeleted(e,t){this.mutate(e,(n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'participant.deleted' event for a conversation that we thought didn't exist."),n;const s=n.value.stores[t.userId];if(void 0===s)return n;s.participantDeleted(e,t);const r=d({},n.value.stores);return delete r[t.userId],S({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})}))}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.stores?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.stores?t:(this.teardownNested(t.value),S({lastChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getParticipantFromCache(e){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.stores)return M("NOT_IN_CACHE");const n=t.value.stores[e];return void 0===n?M("NOT_IN_CACHE"):n.getFromCache()}))}}function We(e){return y(this,arguments,(function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call("GET",["me","conversations",n,"participants"],r,{bypassCache:!0});if(i.ok){const{data:e,cursor:t}=i.value.data;return S({participants:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?S({participants:null,nextCursor:null}):i}))}function qe({seq:e,prevStores:t,participants:n,cursor:s,conversationId:r,realtimeClient:i}){const a=t?d({},t):{};for(const o of n)if(void 0===a[o.id]){const t=new Ue(e,r,o,i);a[o.id]=t}return S(null===s?{lastChanged:e,stores:a,windowEnd:null}:{lastChanged:e,stores:a,windowEnd:{cursor:s,oldestParticipantTs:n[n.length-1].joinedAt}})}class He extends he{constructor(e,t,n,s,r){super(e,s,r),this.getConvDataStore=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}fetchInitial(e){return y(this,null,(function*(){const t=yield Le({realtimeClient:this.realtimeClient,count:20});return t.ok?null===t.value.conversations?S({lastChanged:e,stores:null,windowEnd:null}):Ge({seq:e,conversations:t.value.conversations,cursor:t.value.nextCursor,getConvDataStore:this.getConvDataStore}):t}))}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach((e=>e.unsubscribe()))}anyChildChanged(e,t,n){return y(this,null,(function*(){var s;for(const r in n.stores){const i=n.stores[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1}))}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!ae(Object.keys(e.stores),Object.keys(t.stores))&&ae(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,(function*(){if(null===t.stores)return S({snapshot:ee([]),loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map((t=>t.store.getDeep(e)))),s=n.find((e=>!e.ok));if(s)return s;const r=n.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot));return r.sort(((e,t)=>{var n,s,r,i;const a=null!=(s=null==(n=e.lastMessage)?void 0:n.createdAt)?s:e.joinedAt;return(null!=(i=null==(r=t.lastMessage)?void 0:r.createdAt)?i:t.joinedAt)-a})),S({snapshot:ee(r),loadedAll:null===t.windowEnd})}))}loadMore(e){return y(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=T();this.pendingLoadMore=t.promise,yield this._loadMoreConversations(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreConversations(e=20){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const n=t.value.windowEnd.cursor,s=yield Le({count:e,cursor:n,realtimeClient:this.realtimeClient});yield this.handlers.onLoadedMore({type:"virtual.conversations.loadedmore",data:s})}))}getConvFromCache(e){return y(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.stores)return F({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const n=t.value.stores[e];return void 0===n?M("NOT_IN_CACHE"):n.store.getFromCache()}))}loadedMore(e,t){this.mutate(e,(n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.conversations?(console.warn("[TalkJS] When loading more conversations, the user stopped existing, which should be impossible."),n):Ge({seq:e,prevStores:n.value.stores,conversations:t.data.value.conversations,cursor:t.data.value.nextCursor,getConvDataStore:this.getConvDataStore}):t.data))}userCreated(e,t){this.mutate(e,(e=>null!==e.value.stores?e:S({lastChanged:e.value.lastChanged,stores:{},windowEnd:null})))}sideCreated(e,t){const n=this.getConvDataStore(t.state);this.mutate(e,(s=>{let r=s.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'side.created' event when we thought your user didn't exist."),r={}),Object.hasOwnProperty.call(r,t.conversationId)?(n.unsubscribe(),s):S({lastChanged:e,stores:p(d({},r),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})}))}sideDeleted(e,t){this.mutate(e,(n=>{var s;if(!Object.hasOwnProperty.call(n.value.stores,t.conversationId))return n;const r=d({},n.value.stores);return null==(s=r[t.conversationId])||s.unsubscribe(),delete r[t.conversationId],S({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})}))}sideEdited(e,t){const n=t.diff.lastMessageAt;void 0!==n&&this.mutate(e,(s=>{var r;if(null===s.value.stores)return console.warn("[TalkJS] Received a 'side.edited' event when we thought your user didn't exist."),s;if(null===s.value.windowEnd)return s;const i=Object.hasOwnProperty.call(s.value.stores,t.conversationId);if(i&&n<s.value.windowEnd.oldestMessageTs){const n=d({},s.value.stores);return null==(r=n[t.conversationId])||r.unsubscribe(),delete n[t.conversationId],S({lastChanged:e,stores:n,windowEnd:s.value.windowEnd})}if(!i&&n>=s.value.windowEnd.oldestMessageTs){const n=this.getConvDataStore(t.conversationId);return S({lastChanged:e,stores:p(d({},s.value.stores),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})}return s}))}}function Le(e){return y(this,arguments,(function*({cursor:e,realtimeClient:t,count:n}){const s={limit:n,cursor:e},r=yield t.call("GET",["me","conversations"],s,{bypassCache:!0});if(r.ok){const{data:e,cursor:t}=r.value.data;return S({conversations:e,nextCursor:t})}return r.ok||"server"!==r.where||404!==r.value.status||"USER_NOT_FOUND"!==r.value.errorCode?r:S({conversations:null,nextCursor:null})}))}function Ge({seq:e,prevStores:t,conversations:n,cursor:s,getConvDataStore:r}){const i=t?d({},t):{};for(const a of n)void 0===i[a.id]&&(i[a.id]=r(a));return S(null===s?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:s,oldestMessageTs:Math.min(...n.map((e=>e.lastMessageAt)))}})}class ze extends he{constructor(e,t,n,s,r){super(e,s,r),this.conversation=t,this.realtimeClient=n,this.unsubscribeDebounceMs=5e3}get conversationId(){return"string"==typeof this.conversation?this.conversation:this.conversation.id}fetchInitial(e){return y(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]);if("object"==typeof this.conversation)return S({lastChanged:e,snapshot:this.conversation,messageWindow:t});const n=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId],{},{bypassCache:!0});let s;if(n.ok)s=n.value.data;else if("server"===n.where&&404===n.value.status)s=null;else{if("server"!==n.where||403!==n.value.status||"NOT_A_PARTICIPANT"!==n.value.errorCode)return t.unsubscribe(),n;s=null}return S({lastChanged:e,snapshot:s,messageWindow:t})}))}teardownNested(e){var t;null==(t=e.messageWindow)||t.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,(function*(){return!0===(yield n.messageWindow.store.lastMessageChangedBetween(e,t))}))}equal(e,t){return ae(e.snapshot,t.snapshot)}loadNested(e,t){return y(this,null,(function*(){var n;if(!t.snapshot)return S({snapshot:null,loadedAll:!0});const s=yield t.messageWindow.store.getDeep(e);if(!s.ok)return s;const r=s.value.snapshot,i=null!=(n=null==r?void 0:r[0])?n:null;return S({snapshot:ee(p(d({},t.snapshot),{custom:ee(t.snapshot.custom),welcomeMessages:ee(t.snapshot.welcomeMessages),lastMessage:i}))})}))}participantEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'participant.edited' event for a conversation that we thought didn't exist."),n):S({lastChanged:e,snapshot:Je(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}conversationEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'conversation.edited' event for a conversation that we thought didn't exist."),n):S({lastChanged:e,snapshot:Je(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}sideEdited(e,t){this.mutate(e,(n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'side.edited' event for a conversation that we thought didn't exist."),n):S({lastChanged:e,snapshot:Je(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow})))}sideCreated(e,t){this.mutate(e,(n=>n.value.snapshot?n:S({lastChanged:e,snapshot:t.state,messageWindow:n.value.messageWindow})))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.snapshot?t:S({lastChanged:e,snapshot:null,messageWindow:t.value.messageWindow})))}getFromCache(){return y(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok&&e.value.snapshot?S({status:200,data:e.value.snapshot}):M("NOT_IN_CACHE")}))}}function Je(e,t){const n=t;return{id:e.id,createdAt:e.createdAt,subject:se(e.subject,n.subject),photoUrl:se(e.photoUrl,n.photoUrl),welcomeMessages:re(e.welcomeMessages,n.welcomeMessages),custom:ie(e.custom,n.custom),lastMessageAt:se(e.lastMessageAt,n.lastMessageAt),unreadMessageCount:se(e.unreadMessageCount,n.unreadMessageCount),isUnread:se(e.isUnread,n.isUnread),access:se(e.access,n.access),notify:se(e.notify,n.notify),readUntil:se(e.readUntil,n.readUntil),everyoneReadUntil:se(e.everyoneReadUntil,n.everyoneReadUntil),joinedAt:e.joinedAt}}class Ye extends he{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e3}fetchInitial(e){return y(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]),n=yield this.realtimeClient.call("GET",["users",this.userId,"online"],{},{bypassCache:!0});return n.ok||"server"!==n.where||404!==n.value.status||"USER_NOT_FOUND"!==n.value.errorCode?n.ok?S({lastChanged:e,user:t,data:n.value.data}):n:S({lastChanged:e,user:t,data:null})}))}equal(e,t){return ae(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,(function*(){return n.user.store.changedBetween(e,t)}))}loadNested(e,t){return y(this,null,(function*(){const n=yield t.user.store.getDeep(e);if(!n.ok)return n;const s=n.value.snapshot;return null===t.data||null===s?S({snapshot:null}):S({snapshot:ee(p(d({},t.data),{user:s}))})}))}userCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,(e=>null!==e.value.data?(n.then((e=>{e.ok&&this.teardownNested(e.value)})),e):n))}userOnlineChanged(e,t){this.mutate(e,(n=>null===n.value.data?n:S({lastChanged:e,user:n.value.user,data:t.diff})))}getFromCache(){return y(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;if(!e.ok)return M("NOT_IN_CACHE");if(null===e.value.data)return F({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const t=e.value,{user:n}=t,s=f(t,["user"]);return S({status:200,data:d({},s.data)})}))}}class Qe{constructor(e,t,n){this.realtimeClient=n,this.convDataStores={},this.storeMap={},this.emitMutex=new oe,this.virtualSeqOffset=0,this.realPublishSeq=0,this.refetchOnNextNetworkLoss=!0,this.connection=new X(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.virtualSeqOffset+=this.realPublishSeq,this.realPublishSeq=0,this.refetchOnNextNetworkLoss){this.virtualSeqOffset++;const e=this.virtualSeq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var n;null==(n=this.storeMap[Ve(e)])||n.setError(t)},onPublish:(e,t)=>{this.realPublishSeq=e;const n=this.virtualSeq;for(const s of t)this.handlePublish(n,s);this.emitAll(n)}})}get virtualSeq(){return this.realPublishSeq+this.virtualSeqOffset}refetchAll(e){Object.values(this.storeMap).forEach((t=>null==t?void 0:t.refetch(e)))}emitAll(e){return this.emitMutex.runExclusive((()=>y(this,null,(function*(){const t=Object.values(this.storeMap).map((t=>null==t?void 0:t.emit(e)));yield Promise.all(t)}))))}handlePublish(e,t){var n,s,r,i,a,o,u,l,c,h,d,p,f,m,g,v,b,y,w,C,A,E,k,x,I,T,D,S,M,F;switch(t.type){case"user.created":return null==(n=this.storeMap[`/users/${t.userId}`])||n.userCreated(e,t),null==(s=this.storeMap["/me/conversations"])||s.userCreated(e,t),void(null==(r=this.storeMap[`/users/${t.userId}/online`])||r.userCreated(e,t));case"user.edited":return void(null==(i=this.storeMap[`/users/${t.userId}`])||i.userEdited(e,t));case"side.created":return null==(a=this.convDataStores[t.conversationId])||a.sideCreated(e,t),null==(o=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||o.sideCreated(e,t),null==(u=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||u.sideCreated(e,t),void(null==(l=this.storeMap["/me/conversations"])||l.sideCreated(e,t));case"side.edited":return null==(c=this.convDataStores[t.conversationId])||c.sideEdited(e,t),void(null==(h=this.storeMap["/me/conversations"])||h.sideEdited(e,t));case"side.deleted":return null==(d=this.convDataStores[t.conversationId])||d.sideDeleted(e,t),null==(p=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||p.sideDeleted(e,t),null==(f=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||f.sideDeleted(e,t),null==(m=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||m.sideDeleted(e,t),void(null==(g=this.storeMap["/me/conversations"])||g.sideDeleted(e,t));case"conversation.edited":return void(null==(v=this.convDataStores[t.conversationId])||v.conversationEdited(e,t));case"message.created":return void(null==(b=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||b.messageCreated(e,t));case"message.edited":return void(null==(y=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||y.messageEdited(e,t));case"message.deleted":return void(null==(w=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||w.messageDeleted(e,t));case"typing.available":return void(null==(C=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||C.typingAvailable(e,t));case"typing.changed":return void(null==(A=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||A.typingChanged(e,t));case"conversation.cleared":return void(null==(E=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||E.conversationCleared(e,t));case"participant.edited":return null==(k=this.convDataStores[t.conversationId])||k.participantEdited(e,t),void(null==(x=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||x.participantEdited(e,t));case"participant.created":return void(null==(I=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||I.participantCreated(e,t));case"participant.deleted":return void(null==(T=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||T.participantDeleted(e,t));case"user.online.changed":return void(null==(D=this.storeMap[`/users/${t.userId}/online`])||D.userOnlineChanged(e,t));case"virtual.conversations.loadedmore":return void(null==(S=this.storeMap["/me/conversations"])||S.loadedMore(e,t));case"virtual.messages.loadedmore":return void(null==(M=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||M.loadedMore(e,t));case"virtual.participants.loadedmore":return void(null==(F=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||F.loadedMore(e,t))}}call(e,t,n,s){return y(this,null,(function*(){if(!s.bypassCache&&"GET"===e){const e=Ve(t);if(e in this.storeMap){const t=e,n=this.storeMap[t];if(n&&"getFromCache"in n){const e=yield n.getFromCache();if("NOT_IN_CACHE"!==e.value)return e}}else if(A(t,["me","conversations","*","messages","*"])){const e=this.storeMap[`/me/conversations/${t[2]}/messages`];if(e){const n=yield e.getMessageFromCache(t[4]);if("NOT_IN_CACHE"!==n.value)return n}}else if(A(t,["me","conversations","*","participants","*"])){const e=this.storeMap[`/me/conversations/${t[2]}/participants`];if(e){const n=yield e.getParticipantFromCache(t[4]);if("NOT_IN_CACHE"!==n.value)return n}}else if(A(t,["me","conversations","*"])){const e=this.storeMap["/me/conversations"];if(e){const n=yield e.getConvFromCache(t[2]);if("NOT_IN_CACHE"!==n.value)return n}}}return this.connection.call(e,t,n)}))}subscribe(e,t){const n=this.getOrCreateStore(e),s=T(),r=T();s.promise.catch((()=>{})),r.promise.catch((()=>{}));const i={state:{type:"pending",latestSnapshot:void 0},connected:s.promise,terminated:r.promise,loadMore:e=>y(this,null,(function*(){"loadMore"in n&&(yield n.loadMore(e))})),unsubscribe:()=>{}},a=n.listen((n=>{if(n.ok){const e=!("loadedAll"in n.value)||n.value.loadedAll,r={type:"active",latestSnapshot:n.value.snapshot,loadedAll:e};i.state=r,null==t||t(n.value.snapshot,e),s.resolve(r)}else if("pending"===i.state.type||"active"===i.state.type){if("server"===n.where){const t={type:"error",error:new Error(C(`Subscribe to ${e.join("/")}`,n.value))};return i.state=t,r.resolve(t),void s.reject("Subscription encountered an error during initial connection")}if("SESSION_DESTROYED"===n.value){const e={type:"error",error:new Error("Session was destroyed causing all subscriptions to be terminated")};return i.state=e,r.resolve(e),void s.reject("Subscription encountered an error during initial connection")}if("UNSUBSCRIBED"===n.value)return;if("TERMINATED"===n.value)return;n.value}}));return i.unsubscribe=()=>{if("pending"===i.state.type||"active"===i.state.type){a();const e={type:"unsubscribed"};i.state=e,r.resolve(e),s.reject("Subscription was unsubscribed before connecting")}},i}onVirtualPublish(e){return y(this,null,(function*(){this.virtualSeqOffset++;const t=this.virtualSeq;this.handlePublish(t,e),yield this.emitAll(t)}))}getOrCreateStore(e){const t=Ve(e);if(t in this.storeMap)return this.storeMap[t];this.connection.subscribe(e).then((e=>{e.ok||n.setError(e)}));const n=this.instantiateStore(e,(()=>{delete this.storeMap[t],this.connection.unsubscribe(e)}));return this.storeMap[t]=n,n}destroy(){this.storeMap={},this.convDataStores={},this.connection.destroy()}isConnected(){return this.connection.isConnected()}instantiateStore(e,t){if(A(e,["users","*"]))return new De(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});if(A(e,["me","conversations","*"]))return new Oe(this.virtualSeq,this.subscribeConvData(e[2]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(A(e,["me","conversations","*","messages"]))return new Be(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(A(e,["me","conversations","*","participants"]))return new $e(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(A(e,["me","conversations","*","typing"]))return new je(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t});if(A(e,["me","conversations"]))return new He(this.virtualSeq,(e=>this.subscribeConvData(e)),this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(A(e,["users","*","online"]))return new Ye(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});throw"Unreachable"}subscribeConvData(e){const t="string"==typeof e?e:e.id;if(Object.hasOwnProperty.call(this.convDataStores,t)){const e=this.convDataStores[t];return{store:e,unsubscribe:e.registerInternalSubscription()}}const n=new ze(this.virtualSeq,e,this.realtimeClient,this.emitMutex,{onTeardown:()=>{delete this.convDataStores[t]}});return this.convDataStores[t]=n,{store:n,unsubscribe:n.registerInternalSubscription()}}}function Ve(e){return`/${e.join("/")}`}class Ze{constructor(e,t,n){this.userId=t,this.alive=!0,this.connection=new Qe(e,n,this),n.onTokenRefreshFailed((()=>{this.destroy()}))}call(e,t,n){return y(this,arguments,(function*(e,t,n,s={}){return this.alive?this.connection.call(e,t,n,s):M("SESSION_DESTROYED")}))}subscribe(e,t){return this.connection.subscribe(e,t)}internalSubscribe(e){const t=this.connection.getOrCreateStore(e);return{store:t,unsubscribe:t.registerInternalSubscription()}}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}listMessages(e,t){return y(this,null,(function*(){const n=yield this.call("GET",["me","conversations",e,"messages"],t);if(!n.ok)return Ke(n,"Listing messages in "+e);const s=n.value.data.data,r=yield Promise.all(s.map((t=>this.hydrateMessageData(t,e)))),i=r.find((e=>!e.ok));return void 0===i||i.ok?S(r.map((({value:e})=>e))):i}))}hydrateMessageData(e,t){return y(this,null,(function*(){const n=null===e.senderId?Promise.resolve(S(null)):this.getUser(e.senderId),s=null===e.referencedMessageId?Promise.resolve(S(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield n;if(!r.ok)return r;const i=yield s;if(!i.ok)return i;var a,o,u;return S((a=e,o=r.value,u=i.value,ee({id:a.id,type:a.type,sender:o,referencedMessage:u,custom:ee(a.custom),createdAt:a.createdAt,editedAt:a.editedAt,origin:a.origin,content:a.content,reactions:Te(a.reactions),plaintext:Ee(a.content,{})})))}))}getReferencedMessage(e,t){return y(this,null,(function*(){const n=yield this.call("GET",["me","conversations",e,"messages",t],{});if(!n.ok&&"server"===n.where&&404===n.value.status)return S(null);if(!n.ok&&"server"===n.where&&403===n.value.status&&"NOT_A_PARTICIPANT"===n.value.errorCode)return S(null);if(!n.ok)return Ke(n,`Fetching referenced message ${t} in conversation ${e}`);const s=n.value.data,r=yield this.getUser(s.senderId);if(!r.ok)return r;var i,a;return S((i=s,a=r.value,ee({id:i.id,type:i.type,sender:a,referencedMessageId:i.referencedMessageId,custom:ee(i.custom),createdAt:i.createdAt,editedAt:i.editedAt,origin:i.origin,content:i.content,reactions:Te(i.reactions),plaintext:Ee(i.content,{})})))}))}getUser(e){return y(this,null,(function*(){const t=yield this.call("GET",["users",e],{includePrivateFields:!1});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?S(xe(t.value.data)):Ke(t,"Get user "+e):S(null)}))}}function Ke(e,t){return"server"===e.where?F(p(d({},e.value),{operation:t})):e}function Xe(e,t){var n;if(t.ok)return t.value;throw"SESSION_DESTROYED"===t.value?new Error(`${e} failed because the session was destroyed`):new Error(C(null!=(n=t.value.operation)?n:e,t.value))}class et{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return y(this,null,(function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return Xe("Get user "+this.id,e)}))}set(e){return y(this,null,(function*(){null===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call("PUT",["users",this.brandedId],p(d({},e),{email:t,phone:n}));w("Set user "+this.id,s)}))}createIfNotExists(e){return y(this,null,(function*(){void 0===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call("POST",["users",this.brandedId],p(d({},e),{email:t,phone:n}));(s.ok||"server"!==s.where||409!=s.value.status)&&w(`Create user ${this.id} if not exists`,s)}))}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}subscribeOnline(e){return this._realtimeClient.subscribe(["users",this.brandedId,"online"],e)}}class tt{constructor(e,t,n){this.userId=e,this.conversationId=t,this._realtimeClient=n}get brandedUserId(){return this.userId}get brandedConversationId(){return this.conversationId}get(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],{}),t=yield this._realtimeClient.call("GET",["users",this.brandedUserId],{includePrivateFields:!1}),[n,s]=yield Promise.all([e,t]);return(n.ok||"server"!==n.where||404!==n.value.status)&&(s.ok||"server"!==s.where||404!==s.value.status)?Ie(w(`Get participant ${this.userId} in conversation ${this.conversationId}`,n),xe(w(`Get user ${this.userId}`,s))):null}))}set(){return y(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);w(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)}))}edit(){return y(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);w(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)}))}createIfNotExists(){return y(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("POST",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);(t.ok||"server"!==t.where||409!==t.value.status)&&w(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)}))}delete(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"participants",this.brandedUserId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&w(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)}))}}function nt(e){const t="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let n=0;const s=[],r=e===n;n=e;const i=new Array(8);for(let o=7;o>=0;o--)i[o]=t.charAt(e%64),e=Math.floor(e/64);if(0!==e)throw new Error("We should have converted the entire timestamp.");let a=i.join("");if(r){let e;for(e=11;e>=0&&63===s[e];e--)s[e]=0;s[e]++}else for(let o=0;o<12;o++)s[o]=Math.floor(64*Math.random());for(let o=0;o<12;o++)a+=t.charAt(s[o]);if(20!=a.length)throw new Error("Length should be 20.");return a}const st=(e,t,n=void 0)=>e.reduce(((e,s,r)=>e.concat((e=>{if("string"==typeof e)return t(e,n);switch(e.type){case"bold":case"italic":case"strikethrough":case"blockquote":case"bulletlist":case"bulletList":case"bulletpoint":case"bulletPoint":return[{type:e.type,children:st(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:st(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:st(e.children,t,e.type)}];case"mention":case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"suppressed":case"emoji":case"customemoji":case"customEmoji":return[e]}})(s))),[]);function rt(e,t){return n=>{const s=n;let r=0;const i=[];for(const a of me(n,e)){a.index-r>0&&i.push(s.substring(r,a.index));const e=t(a);Array.isArray(e)?i.push(...e):i.push(e),r=a.index+a[0].length}return r<n.length&&i.push(n.substring(r)),i}}const it="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var at,ot=((at=ot||{})[at.italic=1]="italic",at[at.strikethrough=2]="strikethrough",at[at.bold=4]="bold",at);const ut=[0,1,2,3,4,5,6].map((e=>{const t=[];return 1&e||t.push(/_([^\s_].*?[^\s_])_|_([^\s_])_/),2&e||t.push(/~([^\s~].*?[^\s~])~|~([^\s~])~/),4&e||t.push(/\*([^\s*].*?[^\s*])\*|\*([^\s*])\*/),new RegExp(t.map((e=>e.source)).join("|"),"g")})),lt={_:1,"*":4,"~":2};function ct(e){return ht(e,0)}function ht(e,t=0){const n=ut[t],s=n?function(e){const t=rt(dt.getOrCompute(e,(()=>new RegExp(`(?:^|[\\s${it}])(?:${e.source})(?=[\\s${it}]|$)`,"g"))),(e=>{const t=e[0][1],n=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:ot[lt[t]],children:[n]}]}));return e=>{const[n,...s]=t(" "+e);return n.length>1&&s.unshift(n.substring(1)),s}}(n):()=>[e];return st(s(e),((e,n)=>"bold"===n||"italic"===n||"strikethrough"===n?ht(e,t|ot[n]):[e]))}const dt=function(){const e=function(){try{return new WeakMap}catch(e){const t={has:()=>!1,get:()=>{},set:()=>t};return t}}();return{getOrCompute(t,n){if(e.has(t))return e.get(t);const s=n();return e.set(t,s),s}}}();function pt(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var n=0,s=e.length;n<s;n++)if(e[n]===t)return n;return-1}function ft(e,t){for(var n=e.length-1;n>=0;n--)!0===t(e[n])&&e.splice(n,1)}function mt(e){throw new Error("Unhandled case for value: '"+e+"'")}var gt=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.whitespaceRegex=/\s+/,this.tagName=e.tagName||"",this.attrs=e.attrs||{},this.innerHTML=e.innerHtml||e.innerHTML||""}return e.prototype.setTagName=function(e){return this.tagName=e,this},e.prototype.getTagName=function(){return this.tagName||""},e.prototype.setAttr=function(e,t){return this.getAttrs()[e]=t,this},e.prototype.getAttr=function(e){return this.getAttrs()[e]},e.prototype.setAttrs=function(e){return Object.assign(this.getAttrs(),e),this},e.prototype.getAttrs=function(){return this.attrs||(this.attrs={})},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,n=this.getClass(),s=this.whitespaceRegex,r=n?n.split(s):[],i=e.split(s);t=i.shift();)-1===pt(r,t)&&r.push(t);return this.getAttrs().class=r.join(" "),this},e.prototype.removeClass=function(e){for(var t,n=this.getClass(),s=this.whitespaceRegex,r=n?n.split(s):[],i=e.split(s);r.length&&(t=i.shift());){var a=pt(r,t);-1!==a&&r.splice(a,1)}return this.getAttrs().class=r.join(" "),this},e.prototype.getClass=function(){return this.getAttrs().class||""},e.prototype.hasClass=function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},e.prototype.setInnerHTML=function(e){return this.innerHTML=e,this},e.prototype.setInnerHtml=function(e){return this.setInnerHTML(e)},e.prototype.getInnerHTML=function(){return this.innerHTML||""},e.prototype.getInnerHtml=function(){return this.getInnerHTML()},e.prototype.toAnchorString=function(){var e=this.getTagName(),t=this.buildAttrsStr();return["<",e,t=t?" "+t:"",">",this.getInnerHtml(),"</",e,">"].join("")},e.prototype.buildAttrsStr=function(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n+'="'+e[n]+'"');return t.join(" ")},e}(),vt=function(){function e(e){void 0===e&&(e={}),this.newWindow=!1,this.truncate={},this.className="",this.newWindow=e.newWindow||!1,this.truncate=e.truncate||{},this.className=e.className||""}return e.prototype.build=function(e){return new gt({tagName:"a",attrs:this.createAttrs(e),innerHtml:this.processAnchorText(e.getAnchorText())})},e.prototype.createAttrs=function(e){var t={href:e.getAnchorHref()},n=this.createCssClass(e);return n&&(t.class=n),this.newWindow&&(t.target="_blank",t.rel="noopener noreferrer"),this.truncate&&this.truncate.length&&this.truncate.length<e.getAnchorText().length&&(t.title=e.getAnchorHref()),t},e.prototype.createCssClass=function(e){var t=this.className;if(t){for(var n=[t],s=e.getCssClassSuffixes(),r=0,i=s.length;r<i;r++)n.push(t+"-"+s[r]);return n.join(" ")}return""},e.prototype.processAnchorText=function(e){return this.doTruncate(e)},e.prototype.doTruncate=function(e){var t=this.truncate;if(!t||!t.length)return e;var n,s,r,i,a=t.length,o=t.location;return"smart"===o?function(e,t,n){var s,r;null==n?(n="…",r=3,s=8):(r=n.length,s=n.length);var i=function(e){var t="";return e.scheme&&e.host&&(t+=e.scheme+"://"),e.host&&(t+=e.host),e.path&&(t+="/"+e.path),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t},a=function(e,t){var s=t/2,r=Math.ceil(s),i=-1*Math.floor(s),a="";return i<0&&(a=e.substr(i)),e.substr(0,r)+n+a};if(e.length<=t)return e;var o,u,l,c=t-r,h=(o={},(l=(u=e).match(/^([a-z]+):\/\//i))&&(o.scheme=l[1],u=u.substr(l[0].length)),(l=u.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(o.host=l[1],u=u.substr(l[0].length)),(l=u.match(/^\/(.*?)(?=(\?|#|$))/i))&&(o.path=l[1],u=u.substr(l[0].length)),(l=u.match(/^\?(.*?)(?=(#|$))/i))&&(o.query=l[1],u=u.substr(l[0].length)),(l=u.match(/^#(.*?)$/i))&&(o.fragment=l[1]),o);if(h.query){var d=h.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);d&&(h.query=h.query.substr(0,d[1].length),e=i(h))}if(e.length<=t)return e;if(h.host&&(h.host=h.host.replace(/^www\./,""),e=i(h)),e.length<=t)return e;var p="";if(h.host&&(p+=h.host),p.length>=c)return h.host.length==t?(h.host.substr(0,t-r)+n).substr(0,c+s):a(p,c).substr(0,c+s);var f="";if(h.path&&(f+="/"+h.path),h.query&&(f+="?"+h.query),f){if((p+f).length>=c)return(p+f).length==t?(p+f).substr(0,t):(p+a(f,c-p.length)).substr(0,c+s);p+=f}if(h.fragment){var m="#"+h.fragment;if((p+m).length>=c)return(p+m).length==t?(p+m).substr(0,t):(p+a(m,c-p.length)).substr(0,c+s);p+=m}if(h.scheme&&h.host){var g=h.scheme+"://";if((p+g).length<c)return(g+p).substr(0,t)}if(p.length<=t)return p;var v="";return c>0&&(v=p.substr(-1*Math.floor(c/2))),(p.substr(0,Math.ceil(c/2))+n+v).substr(0,c+s)}(e,a):"middle"===o?function(e,t,n){if(e.length<=t)return e;var s,r;null==n?(n="…",s=8,r=3):(s=n.length,r=n.length);var i=t-r,a="";return i>0&&(a=e.substr(-1*Math.floor(i/2))),(e.substr(0,Math.ceil(i/2))+n+a).substr(0,i+s)}(e,a):(s=a,r=void 0,(n=e).length>s&&(null==r?(r="…",i=3):i=r.length,n=n.substring(0,s-i)+r),n)},e}(),bt=function(){function e(e){this.__jsduckDummyDocProp=null,this.matchedText="",this.offset=0,this.tagBuilder=e.tagBuilder,this.matchedText=e.matchedText,this.offset=e.offset}return e.prototype.getMatchedText=function(){return this.matchedText},e.prototype.setOffset=function(e){this.offset=e},e.prototype.getOffset=function(){return this.offset},e.prototype.getCssClassSuffixes=function(){return[this.getType()]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}(),yt=function(e,t){return(yt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function wt(e,t){function n(){this.constructor=e}yt(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var Ct,At=function(){return At=Object.assign||function(e){for(var t,n=1,s=arguments.length;n<s;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},At.apply(this,arguments)},Et=function(e){function t(t){var n=e.call(this,t)||this;return n.email="",n.email=t.email,n}return wt(t,e),t.prototype.getType=function(){return"email"},t.prototype.getEmail=function(){return this.email},t.prototype.getAnchorHref=function(){return"mailto:"+this.email},t.prototype.getAnchorText=function(){return this.email},t}(bt),kt=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="",n.hashtag="",n.serviceName=t.serviceName,n.hashtag=t.hashtag,n}return wt(t,e),t.prototype.getType=function(){return"hashtag"},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getHashtag=function(){return this.hashtag},t.prototype.getAnchorHref=function(){var e=this.serviceName,t=this.hashtag;switch(e){case"twitter":return"https://twitter.com/hashtag/"+t;case"facebook":return"https://www.facebook.com/hashtag/"+t;case"instagram":return"https://instagram.com/explore/tags/"+t;default:throw new Error("Unknown service name to point hashtag to: "+e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t}(bt),xt=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.mention="",n.mention=t.mention,n.serviceName=t.serviceName,n}return wt(t,e),t.prototype.getType=function(){return"mention"},t.prototype.getMention=function(){return this.mention},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getAnchorHref=function(){switch(this.serviceName){case"twitter":return"https://twitter.com/"+this.mention;case"instagram":return"https://instagram.com/"+this.mention;case"soundcloud":return"https://soundcloud.com/"+this.mention;default:throw new Error("Unknown service name to point mention to: "+this.serviceName)}},t.prototype.getAnchorText=function(){return"@"+this.mention},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),n=this.getServiceName();return n&&t.push(n),t},t}(bt),It=function(e){function t(t){var n=e.call(this,t)||this;return n.number="",n.plusSign=!1,n.number=t.number,n.plusSign=t.plusSign,n}return wt(t,e),t.prototype.getType=function(){return"phone"},t.prototype.getPhoneNumber=function(){return this.number},t.prototype.getNumber=function(){return this.getPhoneNumber()},t.prototype.getAnchorHref=function(){return"tel:"+(this.plusSign?"+":"")+this.number},t.prototype.getAnchorText=function(){return this.matchedText},t}(bt),Tt=function(e){function t(t){var n=e.call(this,t)||this;return n.url="",n.urlMatchType="scheme",n.protocolUrlMatch=!1,n.protocolRelativeMatch=!1,n.stripPrefix={scheme:!0,www:!0},n.stripTrailingSlash=!0,n.decodePercentEncoding=!0,n.schemePrefixRegex=/^(https?:\/\/)?/i,n.wwwPrefixRegex=/^(https?:\/\/)?(www\.)?/i,n.protocolRelativeRegex=/^\/\//,n.protocolPrepended=!1,n.urlMatchType=t.urlMatchType,n.url=t.url,n.protocolUrlMatch=t.protocolUrlMatch,n.protocolRelativeMatch=t.protocolRelativeMatch,n.stripPrefix=t.stripPrefix,n.stripTrailingSlash=t.stripTrailingSlash,n.decodePercentEncoding=t.decodePercentEncoding,n}return wt(t,e),t.prototype.getType=function(){return"url"},t.prototype.getUrlMatchType=function(){return this.urlMatchType},t.prototype.getUrl=function(){var e=this.url;return this.protocolRelativeMatch||this.protocolUrlMatch||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&/g,"&")},t.prototype.getAnchorText=function(){var e=this.getMatchedText();return this.protocolRelativeMatch&&(e=this.stripProtocolRelativePrefix(e)),this.stripPrefix.scheme&&(e=this.stripSchemePrefix(e)),this.stripPrefix.www&&(e=this.stripWwwPrefix(e)),this.stripTrailingSlash&&(e=this.removeTrailingSlash(e)),this.decodePercentEncoding&&(e=this.removePercentEncoding(e)),e},t.prototype.stripSchemePrefix=function(e){return e.replace(this.schemePrefixRegex,"")},t.prototype.stripWwwPrefix=function(e){return e.replace(this.wwwPrefixRegex,"$1")},t.prototype.stripProtocolRelativePrefix=function(e){return e.replace(this.protocolRelativeRegex,"")},t.prototype.removeTrailingSlash=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e},t.prototype.removePercentEncoding=function(e){var t=e.replace(/%22/gi,""").replace(/%26/gi,"&").replace(/%27/gi,"'").replace(/%3C/gi,"<").replace(/%3E/gi,">");try{return decodeURIComponent(t)}catch(n){return t}},t}(bt),Dt=function(e){this.__jsduckDummyDocProp=null,this.tagBuilder=e.tagBuilder},St=/[A-Za-z]/,Mt=/[\d]/,Ft=/[\D]/,Bt=/\s/,Rt=/['"]/,Nt=/[\x00-\x1F\x7F]/,Ot=/A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/.source,Pt=Ot+/\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/.source+/\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/.source,_t=/0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/.source,jt=Pt+_t,Ut=Pt+_t,$t="(?:["+_t+"]{1,3}\\.){3}["+_t+"]{1,3}",Wt="["+Ut+"](?:["+Ut+"\\-]{0,61}["+Ut+"])?",qt=function(e){return"(?=("+Wt+"))\\"+e},Ht=function(e){return"(?:"+qt(e)+"(?:\\."+qt(e+1)+"){0,126}|"+$t+")"},Lt=new RegExp("["+Ut+"]"),Gt=/(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|spreadbetting|travelchannel|wolterskluwer|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|rightathome|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--estv75g|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--kpu716f|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pbt977c|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nationwide|newholland|nextdirect|onyourside|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|telefonica|university|vistaprint|vlaanderen|volkswagen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|fujixerox|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|honeywell|institute|insurance|kuokgroup|ladbrokes|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|scjohnson|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--tckwe|xn--vhquv|yodobashi|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|chrysler|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|esurance|etisalat|everbank|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|movistar|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|symantec|training|uconnect|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|cartier|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hoteles|hotmail|hyundai|iselect|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lancome|lanxess|lasalle|latrobe|leclerc|liaison|limited|lincoln|markets|metlife|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|shriram|singles|staples|starhub|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|اتصالات|الجزائر|العليان|پاکستان|كاثوليك|موبايلي|இந்தியா|abarth|abbott|abbvie|active|africa|agency|airbus|airtel|alipay|alsace|alstom|anquan|aramco|author|bayern|beauty|berlin|bharti|blanco|bostik|boston|broker|camera|career|caseih|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|mobily|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|piaget|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|vuelos|walter|warman|webcam|xihuan|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|भारतम्|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dabur|dance|deals|delta|dodge|drive|dubai|earth|edeka|email|epost|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|intel|irish|iveco|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|lupin|macys|mango|media|miami|money|mopar|movie|nadex|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|zippo|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|adac|aero|aigo|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|doha|duck|duns|dvag|erni|fage|fail|fans|farm|fast|fiat|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scor|scot|seat|seek|sexy|shaw|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بارت|بيتك|ڀارت|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ভাৰত|ਭਾਰਤ|ભારત|ଭାରତ|ಭಾರತ|ලංකා|グーグル|クラウド|ポイント|大众汽车|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bnl|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceb|ceo|cfa|cfd|com|crs|csc|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jcp|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|srl|srt|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|عرب|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ストア|セール|みんな|中文网|天主教|我爱你|新加坡|淡马锡|诺基亚|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|工行|广东|微博|慈善|手机|手表|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|珠宝|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/,zt=new RegExp("["+Ut+"!#$%&'*+/=?^_`{|}~-]"),Jt=new RegExp("^"+Gt.source+"$"),Yt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.localPartCharRegex=zt,t.strictTldRegex=Jt,t}return wt(t,e),t.prototype.parseMatches=function(e){for(var t=this.tagBuilder,n=this.localPartCharRegex,s=this.strictTldRegex,r=[],i=e.length,a=new Qt,o={m:"a",a:"i",i:"l",l:"t",t:"o",o:":"},u=0,l=0,c=a;u<i;){var h=e.charAt(u);switch(l){case 0:"m"===(d=h)?w(1):n.test(d)&&w();break;case 1:p(e.charAt(u-1),h);break;case 2:f(h);break;case 3:m(h);break;case 4:g(h);break;case 5:v(h);break;case 6:b(h);break;case 7:y(h);break;default:mt(l)}u++}var d;return A(),r;function p(e,t){":"===e?n.test(t)?(l=2,c=new Qt(At(At({},c),{hasMailtoPrefix:!0}))):C():o[e]===t||(n.test(t)?l=2:"."===t?l=3:"@"===t?l=4:C())}function f(e){"."===e?l=3:"@"===e?l=4:n.test(e)||C()}function m(e){"."===e||"@"===e?C():n.test(e)?l=2:C()}function g(e){Lt.test(e)?l=5:C()}function v(e){"."===e?l=7:"-"===e?l=6:Lt.test(e)||A()}function b(e){"-"===e||"."===e?A():Lt.test(e)?l=5:A()}function y(e){"."===e||"-"===e?A():Lt.test(e)?(l=5,c=new Qt(At(At({},c),{hasDomainDot:!0}))):A()}function w(e){void 0===e&&(e=2),l=e,c=new Qt({idx:u})}function C(){l=0,c=a}function A(){if(c.hasDomainDot){var n=e.slice(c.idx,u);/[-.]$/.test(n)&&(n=n.slice(0,-1));var i=c.hasMailtoPrefix?n.slice(7):n;(function(e){var t=(e.split(".").pop()||"").toLowerCase();return s.test(t)})(i)&&r.push(new Et({tagBuilder:t,matchedText:n,offset:c.idx,email:i}))}C()}},t}(Dt),Qt=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.hasMailtoPrefix=!!e.hasMailtoPrefix,this.hasDomainDot=!!e.hasDomainDot},Vt=function(){function e(){}return e.isValid=function(e,t){return!(t&&!this.isValidUriScheme(t)||this.urlMatchDoesNotHaveProtocolOrDot(e,t)||this.urlMatchDoesNotHaveAtLeastOneWordChar(e,t)&&!this.isValidIpAddress(e)||this.containsMultipleDots(e))},e.isValidIpAddress=function(e){var t=new RegExp(this.hasFullProtocolRegex.source+this.ipRegex.source);return null!==e.match(t)},e.containsMultipleDots=function(e){var t=e;return this.hasFullProtocolRegex.test(e)&&(t=e.split("://")[1]),t.split("/")[0].indexOf("..")>-1},e.isValidUriScheme=function(e){var t=e.match(this.uriSchemeRegex),n=t&&t[0].toLowerCase();return"javascript:"!==n&&"vbscript:"!==n},e.urlMatchDoesNotHaveProtocolOrDot=function(e,t){return!(!e||t&&this.hasFullProtocolRegex.test(t)||-1!==e.indexOf("."))},e.urlMatchDoesNotHaveAtLeastOneWordChar=function(e,t){return!(!e||!t||this.hasFullProtocolRegex.test(t)||this.hasWordCharAfterProtocolRegex.test(e))},e.hasFullProtocolRegex=/^[A-Za-z][-.+A-Za-z0-9]*:\/\//,e.uriSchemeRegex=/^[A-Za-z][-.+A-Za-z0-9]*:/,e.hasWordCharAfterProtocolRegex=new RegExp(":[^\\s]*?["+Ot+"]"),e.ipRegex=/[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,e}(),Zt=(Ct=new RegExp("[/?#](?:["+Ut+"\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*["+Ut+"\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"),new RegExp(["(?:","(",/(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source,Ht(2),")","|","(","(//)?",/(?:www\.)/.source,Ht(6),")","|","(","(//)?",Ht(10)+"\\.",Gt.source,"(?![-"+jt+"])",")",")","(?::[0-9]+)?","(?:"+Ct.source+")?"].join(""),"gi")),Kt=new RegExp("["+Ut+"]"),Xt=function(e){function t(t){var n=e.call(this,t)||this;return n.stripPrefix={scheme:!0,www:!0},n.stripTrailingSlash=!0,n.decodePercentEncoding=!0,n.matcherRegex=Zt,n.wordCharRegExp=Kt,n.stripPrefix=t.stripPrefix,n.stripTrailingSlash=t.stripTrailingSlash,n.decodePercentEncoding=t.decodePercentEncoding,n}return wt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.stripPrefix,r=this.stripTrailingSlash,i=this.decodePercentEncoding,a=this.tagBuilder,o=[],u=function(){var n=t[0],u=t[1],c=t[4],h=t[5],d=t[9],p=t.index,f=h||d,m=e.charAt(p-1);if(!Vt.isValid(n,u))return"continue";if(p>0&&"@"===m)return"continue";if(p>0&&f&&l.wordCharRegExp.test(m))return"continue";if(/\?$/.test(n)&&(n=n.substr(0,n.length-1)),l.matchHasUnbalancedClosingParen(n))n=n.substr(0,n.length-1);else{var g=l.matchHasInvalidCharAfterTld(n,u);g>-1&&(n=n.substr(0,g))}var v=["http://","https://"].find((function(e){return!!u&&-1!==u.indexOf(e)}));if(v){var b=n.indexOf(v);n=n.substr(b),u=u.substr(b),p+=b}var y=u?"scheme":c?"www":"tld",w=!!u;o.push(new Tt({tagBuilder:a,matchedText:n,offset:p,urlMatchType:y,url:n,protocolUrlMatch:w,protocolRelativeMatch:!!f,stripPrefix:s,stripTrailingSlash:r,decodePercentEncoding:i}))},l=this;null!==(t=n.exec(e));)u();return o},t.prototype.matchHasUnbalancedClosingParen=function(e){var t,n=e.charAt(e.length-1);if(")"===n)t="(";else if("]"===n)t="[";else{if("}"!==n)return!1;t="{"}for(var s=0,r=0,i=e.length-1;r<i;r++){var a=e.charAt(r);a===t?s++:a===n&&(s=Math.max(s-1,0))}return 0===s},t.prototype.matchHasInvalidCharAfterTld=function(e,t){if(!e)return-1;var n=0;t&&(n=e.indexOf(":"),e=e.slice(n));var s=new RegExp("^((.?//)?[-."+Ut+"]*[-"+Ut+"]\\.[-"+Ut+"]+)").exec(e);return null===s?-1:(n+=s[1].length,e=e.slice(s[1].length),/^[^-.A-Za-z0-9:\/?#]/.test(e)?n:-1)},t}(Dt),en=new RegExp("#[_"+Ut+"]{1,139}(?![_"+Ut+"])","g"),tn=new RegExp("[^"+Ut+"]"),nn=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.matcherRegex=en,n.nonWordCharRegex=tn,n.serviceName=t.serviceName,n}return wt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.nonWordCharRegex,r=this.serviceName,i=this.tagBuilder,a=[];null!==(t=n.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||s.test(u)){var l=t[0],c=t[0].slice(1);a.push(new kt({tagBuilder:i,matchedText:l,offset:o,serviceName:r,hashtag:c}))}}return a},t}(Dt),sn=new RegExp(/(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/.source+"|"+/(0([1-9]{1}-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/.source,"g"),rn=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.matcherRegex=sn,t}return wt(t,e),t.prototype.parseMatches=function(e){for(var t,n=this.matcherRegex,s=this.tagBuilder,r=[];null!==(t=n.exec(e));){var i=t[0],a=i.replace(/[^0-9,;#]/g,""),o=!(!t[1]&&!t[2]),u=0==t.index?"":e.substr(t.index-1,1),l=e.substr(t.index+i.length,1),c=!u.match(/\d/)&&!l.match(/\d/);this.testMatch(t[3])&&this.testMatch(i)&&c&&r.push(new It({tagBuilder:s,matchedText:i,offset:t.index,number:a,plusSign:o}))}return r},t.prototype.testMatch=function(e){return Ft.test(e)},t}(Dt),an=new RegExp("@[_"+Ut+"]{1,50}(?![_"+Ut+"])","g"),on=new RegExp("@[_."+Ut+"]{1,30}(?![_"+Ut+"])","g"),un=new RegExp("@[-_."+Ut+"]{1,50}(?![-_"+Ut+"])","g"),ln=new RegExp("[^"+Ut+"]"),cn=function(e){function t(t){var n=e.call(this,t)||this;return n.serviceName="twitter",n.matcherRegexes={twitter:an,instagram:on,soundcloud:un},n.nonWordCharRegex=ln,n.serviceName=t.serviceName,n}return wt(t,e),t.prototype.parseMatches=function(e){var t,n=this.serviceName,s=this.matcherRegexes[this.serviceName],r=this.nonWordCharRegex,i=this.tagBuilder,a=[];if(!s)return a;for(;null!==(t=s.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||r.test(u)){var l=t[0].replace(/\.+$/g,""),c=l.slice(1);a.push(new xt({tagBuilder:i,matchedText:l,offset:o,serviceName:n,mention:c}))}}return a},t}(Dt);var hn=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.type=e.type||"tag",this.name=e.name||"",this.isOpening=!!e.isOpening,this.isClosing=!!e.isClosing},dn=function(){function e(t){void 0===t&&(t={}),this.version=e.version,this.urls={},this.email=!0,this.phone=!0,this.hashtag=!1,this.mention=!1,this.newWindow=!0,this.stripPrefix={scheme:!0,www:!0},this.stripTrailingSlash=!0,this.decodePercentEncoding=!0,this.truncate={length:0,location:"end"},this.className="",this.replaceFn=null,this.context=void 0,this.sanitizeHtml=!1,this.matchers=null,this.tagBuilder=null,this.urls=this.normalizeUrlsCfg(t.urls),this.email="boolean"==typeof t.email?t.email:this.email,this.phone="boolean"==typeof t.phone?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow="boolean"==typeof t.newWindow?t.newWindow:this.newWindow,this.stripPrefix=this.normalizeStripPrefixCfg(t.stripPrefix),this.stripTrailingSlash="boolean"==typeof t.stripTrailingSlash?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding="boolean"==typeof t.decodePercentEncoding?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var n=this.mention;if(!1!==n&&"twitter"!==n&&"instagram"!==n&&"soundcloud"!==n)throw new Error("invalid `mention` cfg - see docs");var s=this.hashtag;if(!1!==s&&"twitter"!==s&&"facebook"!==s&&"instagram"!==s)throw new Error("invalid `hashtag` cfg - see docs");this.truncate=this.normalizeTruncateCfg(t.truncate),this.className=t.className||this.className,this.replaceFn=t.replaceFn||this.replaceFn,this.context=t.context||this}return e.link=function(t,n){return new e(n).link(t)},e.parse=function(t,n){return new e(n).parse(t)},e.prototype.normalizeUrlsCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{schemeMatches:e,wwwMatches:e,tldMatches:e}:{schemeMatches:"boolean"!=typeof e.schemeMatches||e.schemeMatches,wwwMatches:"boolean"!=typeof e.wwwMatches||e.wwwMatches,tldMatches:"boolean"!=typeof e.tldMatches||e.tldMatches}},e.prototype.normalizeStripPrefixCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{scheme:e,www:e}:{scheme:"boolean"!=typeof e.scheme||e.scheme,www:"boolean"!=typeof e.www||e.www}},e.prototype.normalizeTruncateCfg=function(e){return"number"==typeof e?{length:e,location:"end"}:function(e,t){for(var n in t)t.hasOwnProperty(n)&&void 0===e[n]&&(e[n]=t[n]);return e}(e||{},{length:Number.POSITIVE_INFINITY,location:"end"})},e.prototype.parse=function(e){var t=this,n=["a","style","script"],s=0,r=[];return function(e,t){for(var n,s=t.onOpenTag,r=t.onCloseTag,i=t.onText,a=t.onComment,o=t.onDoctype,u=new hn,l=0,c=e.length,h=0,d=0,p=u;l<c;){var f=e.charAt(l);switch(h){case 0:"<"===f&&O();break;case 1:m(f);break;case 2:v(f);break;case 3:g(f);break;case 4:b(f);break;case 5:y(f);break;case 6:w(f);break;case 7:C(f);break;case 8:A(f);break;case 9:E(f);break;case 10:k(f);break;case 11:x(f);break;case 12:I(f);break;case 13:"--"===e.substr(l,2)?(l+=2,p=new hn(At(At({},p),{type:"comment"})),h=14):"DOCTYPE"===e.substr(l,7).toUpperCase()?(l+=7,p=new hn(At(At({},p),{type:"doctype"})),h=20):N();break;case 14:T(f);break;case 15:D(f);break;case 16:S(f);break;case 17:M(f);break;case 18:F(f);break;case 19:B(f);break;case 20:R(f);break;default:mt(h)}l++}function m(e){"!"===e?h=13:"/"===e?(h=2,p=new hn(At(At({},p),{isClosing:!0}))):"<"===e?O():St.test(e)?(h=3,p=new hn(At(At({},p),{isOpening:!0}))):(h=0,p=u)}function g(e){Bt.test(e)?(p=new hn(At(At({},p),{name:_()})),h=4):"<"===e?O():"/"===e?(p=new hn(At(At({},p),{name:_()})),h=12):">"===e?(p=new hn(At(At({},p),{name:_()})),P()):St.test(e)||Mt.test(e)||":"===e||N()}function v(e){">"===e?N():St.test(e)?h=3:N()}function b(e){Bt.test(e)||("/"===e?h=12:">"===e?P():"<"===e?O():"="===e||Rt.test(e)||Nt.test(e)?N():h=5)}function y(e){Bt.test(e)?h=6:"/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():Rt.test(e)&&N()}function w(e){Bt.test(e)||("/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():Rt.test(e)?N():h=5)}function C(e){Bt.test(e)||('"'===e?h=8:"'"===e?h=9:/[>=`]/.test(e)?N():"<"===e?O():h=10)}function A(e){'"'===e&&(h=11)}function E(e){"'"===e&&(h=11)}function k(e){Bt.test(e)?h=4:">"===e?P():"<"===e&&O()}function x(e){Bt.test(e)?h=4:"/"===e?h=12:">"===e?P():"<"===e?O():(h=4,l--)}function I(e){">"===e?(p=new hn(At(At({},p),{isClosing:!0})),P()):h=4}function T(e){"-"===e?h=15:">"===e?N():h=16}function D(e){"-"===e?h=18:">"===e?N():h=16}function S(e){"-"===e&&(h=17)}function M(e){h="-"===e?18:16}function F(e){">"===e?P():"!"===e?h=19:"-"===e||(h=16)}function B(e){"-"===e?h=17:">"===e?P():h=16}function R(e){">"===e?P():"<"===e&&O()}function N(){h=0,p=u}function O(){h=1,p=new hn({idx:l})}function P(){var t=e.slice(d,p.idx);t&&i(t,d),"comment"===p.type?a(p.idx):"doctype"===p.type?o(p.idx):(p.isOpening&&s(p.name,p.idx),p.isClosing&&r(p.name,p.idx)),N(),d=l+1}function _(){var t=p.idx+(p.isClosing?2:1);return e.slice(t,l).toLowerCase()}d<l&&(n=e.slice(d,l),i(n,d),d=l+1)}(e,{onOpenTag:function(e){n.indexOf(e)>=0&&s++},onText:function(e,n){if(0===s){var i=function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var n,s=[],r=0;n=t.exec(e);)s.push(e.substring(r,n.index)),s.push(n[0]),r=n.index+n[0].length;return s.push(e.substring(r)),s}(e,/( | |<|<|>|>|"|"|')/gi),a=n;i.forEach((function(e,n){if(n%2==0){var s=t.parseText(e,a);r.push.apply(r,s)}a+=e.length}))}},onCloseTag:function(e){n.indexOf(e)>=0&&(s=Math.max(s-1,0))},onComment:function(e){},onDoctype:function(e){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort((function(e,t){return e.getOffset()-t.getOffset()}));for(var t=0;t<e.length-1;t++){var n=e[t],s=n.getOffset(),r=n.getMatchedText().length,i=s+r;if(t+1<e.length){if(e[t+1].getOffset()===s){var a=e[t+1].getMatchedText().length>r?t:t+1;e.splice(a,1);continue}e[t+1].getOffset()<i&&e.splice(t+1,1)}}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||ft(e,(function(e){return"hashtag"===e.getType()})),this.email||ft(e,(function(e){return"email"===e.getType()})),this.phone||ft(e,(function(e){return"phone"===e.getType()})),this.mention||ft(e,(function(e){return"mention"===e.getType()})),this.urls.schemeMatches||ft(e,(function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()})),this.urls.wwwMatches||ft(e,(function(e){return"url"===e.getType()&&"www"===e.getUrlMatchType()})),this.urls.tldMatches||ft(e,(function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()})),e},e.prototype.parseText=function(e,t){void 0===t&&(t=0),t=t||0;for(var n=this.getMatchers(),s=[],r=0,i=n.length;r<i;r++){for(var a=n[r].parseMatches(e),o=0,u=a.length;o<u;o++)a[o].setOffset(t+a[o].getOffset());s.push.apply(s,a)}return s},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"<").replace(/>/g,">"));for(var t=this.parse(e),n=[],s=0,r=0,i=t.length;r<i;r++){var a=t[r];n.push(e.substring(s,a.getOffset())),n.push(this.createMatchReturnVal(a)),s=a.getOffset()+a.getMatchedText().length}return n.push(e.substring(s)),n.join("")},e.prototype.createMatchReturnVal=function(e){var t;return this.replaceFn&&(t=this.replaceFn.call(this.context,e)),"string"==typeof t?t:!1===t?e.getMatchedText():t instanceof gt?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getMatchers=function(){if(this.matchers)return this.matchers;var e=this.getTagBuilder(),t=[new nn({tagBuilder:e,serviceName:this.hashtag}),new Yt({tagBuilder:e}),new rn({tagBuilder:e}),new cn({tagBuilder:e,serviceName:this.mention}),new Xt({tagBuilder:e,stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding})];return this.matchers=t},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new vt({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="3.14.3",e.AnchorTagBuilder=vt,e.HtmlTag=gt,e.matcher={Email:Yt,Hashtag:nn,Matcher:Dt,Mention:cn,Phone:rn,Url:Xt},e.match={Email:Et,Hashtag:kt,Match:bt,Mention:xt,Phone:It,Url:Tt},e}();function pn(e,t=e){return{type:"autolink",url:e,text:t}}const fn=rt(/<!!mention:([^>\s]*?)\|(.*?)>/gm,(([e,t,n])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),n))),mn=rt(/<!!customemoji:(.*?)>/gm,(([e,t])=>function(e){return{type:"customemoji",text:e}}(t))),gn=rt(/<((?:https?|mailto):.*?)\|(.*?)>/gi,(([e,t,n])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[n]))),vn=rt(/<actionlink:([^|]+)[|]([^>]*)>/gi,(([e,t,n])=>{const{action:s,params:r}=yn(t);return function(e,t,n=[]){return{type:"actionlink",action:e,params:t,children:n}}(s,r,[n])})),bn=rt(/<actionbutton:([^|]+)[|]([^>]*)>/gi,(([e,t,n])=>{const{action:s,params:r}=yn(t);return function(e,t,n=[]){return{type:"actionbutton",action:e,params:t,children:n}}(s,r,[n])}));function yn(e){const t=e.indexOf("?");return-1===t?{action:e,params:{}}:{action:e.slice(0,t),params:Object.fromEntries(new URLSearchParams(e.slice(t)))}}const wn=rt(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,(([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e]))),Cn=rt(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,(([e,t])=>({type:"bulletpoint",children:[t]}))),An=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g;let n=0;const s=[];for(const r of me(e,t)){const t=r[0],i=r[1],a=t.startsWith(i)?r.index:r.index+1;a-n>0&&s.push(e.substring(n,a));const o=pn("tel:"+i.replace(/[^0-9+]/g,""),i);s.push(o),n=a+i.length}return n<e.length&&s.push(e.substring(n)),s},En=e=>gn(e).flatMap((e=>"string"==typeof e?kn(e):["<",...kn(e.url),...kn("|"+e.children[0]+">")])),kn=e=>{const t=dn.parse(e,{urls:!0,email:!0,phone:!1,hashtag:!1,mention:!1}),n=[];let s=0;for(const r of t){const t=r.getOffset(),i=r.getMatchedText(),a=i.length;let o=i;r instanceof Et?o="mailto:"+r.getEmail():r instanceof Tt&&(o=r.getUrl()),t>s&&n.push(e.substring(s,t)),n.push(pn(o,i)),s=t+a}return s<e.length&&n.push(e.substring(s)),n},xn=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const In=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function Tn(e,t={except:[]}){let n=function(e,t){let n=[e];return n=Sn(n,t.multilineSteps),n=Sn(n,[In]),n=Sn(n,t.singlelineSteps),n=Mn(n),n}(e,function(e={except:[]}){var t;const n={multilineSteps:[],singlelineSteps:[]},s=null!=(t=e.except)?t:xn.filter((t=>!e.only.includes(t)));return s.includes("BulletPoint")||n.multilineSteps.push(wn,Cn),s.includes("Mention")||n.singlelineSteps.push(fn),s.includes("CustomEmoji")||n.singlelineSteps.push(mn),s.includes("Codespan")||n.multilineSteps.push(rt(/```([^]+?)```/g,(([e,t])=>({type:"codespan",text:t.replace(/<!!mention:.*?\|([^>]*)>/gim,"@$1").replace(/<!!customemoji:(.*?)>/gim,"$1")})))),s.includes("FormattedLink")||n.singlelineSteps.push(gn),s.includes("Actions")||(n.singlelineSteps.push(vn),n.singlelineSteps.push(bn)),s.includes("Wikitext")||n.singlelineSteps.push(ct),s.includes("Autolink")||n.singlelineSteps.push(En,An),n}(t));return n=Fn(n,!1),n}function Dn(e){return Tn(e,{except:["FormattedLink","Actions"]})}function Sn(e,t){return t.reduce(((e,t)=>st(e,t)),e)}function Mn(e){const t=[];let n=-1;for(const s of e)"string"==typeof s?"string"==typeof t[n]?t[n]+=s:t[++n]=s:t[++n]="children"in s?p(d({},s),{children:Mn(s.children)}):s;return t}function Fn(e,t){const n=[];let s=[];for(let r=0;r<e.length;r++){const i=e[r];if("string"==typeof i)s.push(i);else if("children"in i){s.length>0&&(n.push(s.join("")),s=[]);const e=Fn(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type);n.push(p(d({},i),{children:e}))}else"autolink"===i.type&&t?s.push(i.text):(s.length>0&&(n.push(s.join("")),s=[]),n.push(i))}return s.length>0&&(n.push(s.join("")),s=[]),n}class Bn{constructor(e,t,n,s){this.emoji=e,this.messageId=t,this.conversationId=n,this._realtimeClient=s}get brandedMessageId(){return this.messageId}get brandedConversationId(){return this.conversationId}add(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],{});w(`Add ${this.emoji} reaction on message ${this.messageId} in conversation ${this.conversationId}`,e)}))}remove(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&w(`Remove ${this.emoji} reaction from message ${this.messageId} in conversation ${this.conversationId}`,e)}))}}class Rn{constructor(e,t,n){this.id=e,this.conversationId=t,this._realtimeClient=n}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}reaction(e){if("string"!=typeof e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is not a string`);if(""===e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is an empty string`);return new Bn(e,this.brandedId,this.brandedConversationId,this._realtimeClient)}get(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"messages",this.brandedId],{});if(!e.ok&&"server"===e.where&&404===e.value.status)return null;if(!e.ok&&"server"===e.where&&403===e.value.status&&"NOT_A_PARTICIPANT"===e.value.errorCode)return null;const t=w("Get message "+this.id,e),n=yield this._realtimeClient.hydrateMessageData(t,this.brandedConversationId);return Xe("Get message "+this.id,n)}))}edit(e){return y(this,null,(function*(){const t={content:Nn(e),custom:"string"==typeof e?void 0:e.custom},n=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"messages",this.brandedId],t);w(`Edit message ${this.id} in conversation ${this.conversationId}`,n)}))}delete(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&w(`Delete message ${this.id} in conversation ${this.conversationId}`,e)}))}}function Nn(e){return"string"==typeof e?[{type:"text",children:Tn(e)}]:"text"in e&&e.text?[{type:"text",children:Tn(e.text)}]:"content"in e&&e.content?e.content:void 0}class On{constructor(e,t){this.id=e,this._realtimeClient=t,this.uselessObjForTypeCheck={subject:null,photoUrl:null,welcomeMessages:null,custom:null,access:null,notify:null}}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){if("string"==typeof e){if(""===e)throw new Error(`Creating ParticipantRef failed because ID "${e}" is an empty string`);return new tt(e,this.id,this._realtimeClient)}if("brandedId"in e)return new tt(e.id,this.id,this._realtimeClient);throw new Error(`Creating ParticipantRef failed because user "${e}" is not a string or a UserRef`)}message(e){if("string"!=typeof e)throw new Error(`Creating MessageRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating MessageRef failed because ID "${e}" is an empty string`);return new Rn(e,this.brandedId,this._realtimeClient)}get(){return y(this,null,(function*(){const e=this._realtimeClient.listMessages(this.brandedId,{limit:1}),t=yield this._realtimeClient.call("GET",["me","conversations",this.brandedId],{});if(!t.ok&&"server"===t.where&&404===t.value.status)return null;const n=w("Get conversation "+this.id,t),s=Xe("Get last message in conversation "+this.id,yield e);return function(e,t){return ee({id:e.id,subject:e.subject,photoUrl:e.photoUrl,welcomeMessages:ee(e.welcomeMessages),custom:ee(e.custom),createdAt:e.createdAt,joinedAt:e.joinedAt,lastMessageAt:e.lastMessageAt,unreadMessageCount:e.unreadMessageCount,isUnread:e.isUnread,access:e.access,notify:e.notify,lastMessage:t,readUntil:e.readUntil,everyoneReadUntil:e.everyoneReadUntil})}(n,0===s.length?null:s[0])}))}set(e){return y(this,null,(function*(){const t=this._realtimeClient.call("PUT",["conversations",this.brandedId],e),n=this._realtimeClient.call("PUT",["conversations",this.brandedId,"participants",this.brandedUserId],e),s=yield t;!s.ok&&"server"===s.where&&403===s.value.status&&"UNAUTHORIZED_TO_EDIT"===s.value.errorCode&&function(e){return void 0===e.subject&&(void 0===e.photoUrl&&(void 0===e.welcomeMessages&&(null!==e.custom&&(void 0===e.custom||!Object.values(e.custom).some((e=>void 0!==e))))))}(e)||w("Set conversation "+this.id,s);const r=yield n;!r.ok&&"server"===r.where&&403===r.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===r.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||w("Set your participation in conversation "+this.id,r)}))}createIfNotExists(){return y(this,arguments,(function*(e={}){const t=this._realtimeClient.call("POST",["conversations",this.brandedId],e),n=this._realtimeClient.call("POST",["conversations",this.brandedId,"participants",this.brandedUserId],e),s=yield t;(s.ok||"server"!==s.where||409!==s.value.status)&&w("Create conversation "+this.id,yield t);const r=yield n;(r.ok||"server"!==r.where||409!==r.value.status)&&w("Join conversation "+this.id,yield n)}))}markAsRead(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"read"],{});w(`Mark ${this.id} as read`,e)}))}markAsUnread(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"unread"],{});w(`Mark ${this.id} as unread`,e)}))}send(e){return y(this,null,(function*(){const t={content:Pn(e),referencedMessageId:_n(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:nt((new Date).getTime())},n=yield this._realtimeClient.call("POST",["conversations",this.brandedId,"messages"],t),s=w("Send message to conversation "+this.id,n);return new Rn(s.id,this.brandedId,this._realtimeClient)}))}subscribeMessages(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"messages"],e)}subscribeParticipants(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"participants"],e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}subscribeTyping(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"typing"],e)}markAsTyping(){return y(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"typing"],{});w(`Set user as typing in ${this.id}`,e)}))}}function Pn(e){return"string"==typeof e?[{type:"text",children:Dn(e)}]:"text"in e?[{type:"text",children:Dn(e.text)}]:e.content}function _n(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class jn{constructor(e,t,n){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=t,this.restApiHttpUrl=n}getBokensUrl(e,t,n){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(t)}?signature=${encodeURIComponent(null!=n?n:"")}`}getRealtimeWsUrl(e,t,n,s,r){const i=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${i}?talkjs-client-build=${null!=r?r:"standalone"}&talkjs-core=${n}&talkjs-client-id=${s}`}static fromHost(e){var t;const n=new jn("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return n;if("@currentHost"===e){if("undefined"==typeof location)throw new Error("You can only use @currentHost in a browser.");e=(null!=(t=window.top)?t:window).location.host}if(e.endsWith("talkjs.com")){const t=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(t){const e=t[1];return["app","cdn","api","realtime"].includes(e)?n:new jn(`wss://realtime-${e}.talkjs.com/v1`,`https://app-${e}.talkjs.com/api/v0`,`https://api-${e}.talkjs.com/v1`)}return n}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new jn(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new jn(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function Un({method:e,url:t,data:n,options:s,attempts:r,shouldRetry:i,authProvider:a}){var o;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2025-10-30T09:02:16.772Z"};return n instanceof FormData||(u["Content-Type"]=null!=(o=null==s?void 0:s.contentType)?o:"application/json"),I(r,(()=>y(this,null,(function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:n}).then((e=>{if(e.ok)return e;throw e}))}))),{initialDelay:.2,log:void 0,shouldRetry:n=>y(this,null,(function*(){return a&&401===n.status?(Jn.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.refreshToken(),!0):i?i(n):!("status"in n&&n.status>=400&&n.status<500)}))}).catch((n=>{if(Math.random()<.1&&!t.toString().startsWith("https://capture.trackjs.com")){const s=`Network Error for ${e} ${t}`;"undefined"!=typeof window&&(n instanceof Response?n.clone().text().then((e=>Jn.log(`${s} ${n.status} ${e} (10% logged)`))):Jn.log(`${s} ${n} (10% logged)`)),console.error("[TalkJS]",s)}throw n}))}const{cdnHost:$n,appHost:Wn,restHost:qn,realtimeHost:Hn,appProtocol:Ln,appWsProtocol:Gn}=function(){if("undefined"==typeof window)return{cdnHost:"test-hostname",appHost:"test-hostname",appProtocol:"http:",appWsProtocol:"ws:"};if(!globalThis.document)return{appHost:"app.talkjs.com",appProtocol:"http:",appWsProtocol:"ws:"};const e=function(){if(document.currentScript)return document.currentScript.src;try{throw new Error}catch(o){const t=o.stack.match(/https?:\/\/.*\.(js|jsx|ts|tsx)/);return t?t[0]:""}}(),t=new URL(e),n=t.host,s=(o=n).match(/^cdn[.-]/)?o.replace(/^cdn/,"app"):"talkjs.com"===o?"app.talkjs.com":o,r=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"api"):e+"/public_api"}(s),i=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"realtime"):e+"/public_api"}(s),a=t.protocol;var o;return{cdnHost:n,appHost:s,restHost:r,realtimeHost:i,appProtocol:a,appWsProtocol:"https:"===a?"wss:":"ws:"}}(),zn=Wn.startsWith("app.talkjs.com"),Jn="undefined"==typeof window?{log:e=>Promise.resolve(),setData:e=>{}}:new(s=class{constructor(e){var s,r,i,a;v(this,t),v(this,n),this._timeCreated=Date.now(),this._enabled=zn,b(this,t,null!=(r=null==(s=globalThis.document)?void 0:s.referrer)?r:""),b(this,n,(null!=(a=null==(i=globalThis.location)?void 0:i.href)?a:globalThis.HermesInternal)?"React Native Hermes":""),this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2025-10-30T09:02:16.772Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:g(this,n),referrer:g(this,t),userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:g(this,n),stack:"",timestamp:(new Date).toISOString(),version:"dev-2025-10-30T09:02:16.772Z",throttled:0},this._url=`https://capture.trackjs.com/capture?token=${e}`,this._trackJSData.customer.token=e}setData({appId:e,meId:t,sessionId:n}){this._trackJSData.customer.userId=e,this._trackJSData.customer.sessionId=`${e}/${t}`,this._trackJSData.customer.correlationId=n}log(e){return y(this,null,(function*(){try{if(!this._enabled)return Promise.resolve();const t=p(d({},this._trackJSData),{message:e});yield Un({method:"POST",url:this._url,data:JSON.stringify(t),options:{contentType:"text/plain"}})}catch(t){console.error("[TalkJS] Failed when sending an error report. Error: ",t)}}))}},t=new WeakMap,n=new WeakMap,s)("970cd0be0fb74630b75c8451051299dc");class Yn{constructor(e,t={}){this._onSubscription=t,this._handlers={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(this._handlers[n]=[])}emit(e,t){for(const s of this._handlers[e])try{s(t)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}}emitAsync(e,t){return y(this,null,(function*(){try{const n=this._handlers[e].map((e=>e(t)));yield Promise.all(n)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}}))}supports(e){return e in this._handlers}on(e,t){var n,s;if(!this.supports(e))throw new Error(`Unknown event type '${String(e)}'`);null==(s=(n=this._onSubscription)[e])||s.call(n),this._handlers[e].push(t)}off(e,t){if(!Object.hasOwnProperty.call(this._handlers,e))throw new Error(`Unknown event type '${String(e)}'`);const n=this._handlers[e].indexOf(t);-1!==n&&this._handlers[e].splice(n,1)}removeAllListeners(){for(const e in this._handlers)this._handlers[e]=[]}handles(e){return this._handlers[e].length>0}subscribe(e,t){return this.on(e,t),{unsubscribe:()=>this.off(e,t)}}}class Qn{constructor(e,t,n,s,r,i){if(this.appId=t,this.userId=n,this.tokenFetcher=r,this.usingBokens=!1,this.requestInProgress=!1,this.eventEmitter=new Yn({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0,i&&(s||r))throw new Error("[TalkJS] If providing a signature for authentication, you must not provide a token or tokenFetcher.");s?this.fetchToken((()=>s)):(r||(this.usingBokens=!0,this.tokenFetcher=()=>this.sendBokenRequest(e,i)),this.refreshToken())}get canRefreshToken(){return this.usingBokens||!!this.tokenFetcher}getToken(){return this.token}refreshToken(){if(!this.requestInProgress){if(!this.tokenFetcher)throw this.emitTokenRefreshFailed("no `tokenFetcher` provided"),new Error("[TalkJS] Cannot refresh token, no `tokenFetcher` provided.");this.fetchToken(this.tokenFetcher)}}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}emitTokenChanged(e){this.eventEmitter.emit("tokenChanged",e)}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e),console.error(`[TalkJS] Could not authenticate, cannot recover automatically: ${e}`)}onTokenAccepted(e){return this.eventEmitter.on("tokenAccepted",e),()=>{this.eventEmitter.off("tokenAccepted",e)}}emitTokenAccepted(e){this.eventEmitter.emit("tokenAccepted",e)}clearScheduledRefresh(){this.sessionExpiryWarningTimeoutId&&clearTimeout(this.sessionExpiryWarningTimeoutId)}scheduleRefresh(e){if(this.clearScheduledRefresh(),null===e)return;const t=void 0!==this.tokenFetcher;if(e<120&&!t?console.warn(`[TalkJS] TalkJS will stop working in ${e} seconds due to auth token expiry. Token expires in ${e} seconds, and cannot be refreshed because no \`tokenFetcher\` was provided when creating the session. Non-refreshable tokens are recommended to expire at least 24 hours in the future.`):e<120&&t?console.warn(`[TalkJS] TalkJS auth token will expire and need to be refreshed in ${e} seconds. Refreshable JWTs are recommended to expire at least 30 minutes in the future, to improve performance and reduce unnecessary refreshes.`):e<3300&&!t&&console.warn(`[TalkJS debug] TalkJS will stop working in ${Math.round(e/60)} minutes due to auth token expiry. Non-refreshable tokens are recommended to expire at least 24 hours in the future. Alternatively, provide a \`tokenFetcher\` when creating the session, so that tokens can be refreshed when they expire.`),void 0!==this.tokenFetcher){const t=e>600?e-300:e/2,n=Math.min(1728e6,1e3*t);this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.refreshToken()}),n)}else e<2e6&&(this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.emitTokenRefreshFailed("Token has expired and no `tokenFetcher` was provided when creating the session, so it cannot be refreshed.")}),1e3*e))}fetchToken(e){return y(this,null,(function*(){if(this.requestInProgress)return;this.requestInProgress=!0;const t=()=>y(this,null,(function*(){const t=yield e();return this.checkJwt(t),t}));try{const e=void 0!==this.token;this.token=t(),yield this.token.then((t=>{e&&this.emitTokenChanged(t)})).catch((e=>{this.emitTokenRefreshFailed(e)}))}catch(n){this.emitTokenRefreshFailed(n)}finally{this.requestInProgress=!1}}))}checkJwt(e){!function(e){if(!("string"==typeof e||e instanceof String)){if(void 0===e)throw"Token was undefined";throw"Token must be a string, got: "+e}}(e);const t=[];let n,s,r;if("string"==typeof e?n=e:t.push(`Token type is ${typeof e} instead of a string.`),n)try{const e=function(e){const t=e.split(".");if(3!==t.length)throw"Token does not contain exactly two `.`. Check that you generated your JWT correctly. It should be `<header>.<payload>.<signature>`.";return{header:Vn(t[0]),payload:Vn(t[1])}}(n);s=e.header,r=e.payload}catch(i){t.push(i)}if(s){const e=this.checkJwtHeader(s);t.push(...e)}if(r){const e=this.checkJwtPayload(r);t.push(...e)}if(t.length)if(this.usingBokens)Jn.log(`JWT Errors detected by AuthProvider when using bokens: ${t.join("\n")}`);else{console.warn("[TalkJS] Authentication token appears to be generated incorrectly. Will still attempt to authenticate, but TalkJS may not work as expected. See below for a description of any problems and how to fix them.");const n=t.length>1;t.forEach(((e,t)=>{const s=n?`Reason ${t+1}:`:"Reason:";console.warn(`[TalkJS] ${s} ${e}`)})),console.warn(`[TalkJS]: Authentication token: "${e}"`)}}checkJwtHeader(e){const t=[],n=e.alg;return void 0===n?t.push('Token header must contain `"alg": "HS256"`, but no `alg` was specified.'):"string"!=typeof n?t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):"HS256"!==n&&t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was set to "${n}" instead. HS256 is the only supported algorithm.`),t}checkJwtPayload(e){const t=[],n=e.iss;void 0===n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was missing.`):"string"!=typeof n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):n!==this.appId&&t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was set to "${n}" instead.`);const s=e.sub;void 0===s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was missing.`):"string"!=typeof s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was ${typeof s} instead of a string. Make sure you wrap the value in "".`):s!==this.userId&&t.push(`Token payload must contain a \`sub\` claim set to your userId ID (${this.userId}), but \`sub\` was set to "${s}" instead.`);const r=e.tokenType;void 0===r?t.push('Token payload must contain a `"tokenType": "user"` claim, but no `tokenType` was specified.'):"string"!=typeof r?t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was ${typeof r} instead of a string. Make sure you wrap the value in "".`):"user"!==r&&t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was set to "${r}" instead.`);const i=e.exp;void 0===i||("number"!=typeof i?t.push(`Token payload contains an \`exp\` claim, but \`exp\` was ${typeof r} instead of a number. If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Don't wrap the value in "".`):i<1e9?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01.`):i>1e11?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`):i<(new Date).getTime()/1e3&&t.push(`Token payload contains an \`exp\` claim, but \`exp\` (${i}, representing ${new Date(1e3*i).toLocaleDateString()}) appears to be in the past, meaning the token will be rejected. This error can also happen if your device's clock is set incorrectly, in which case the token will still work.`));const a=e.nbf;return void 0===a||("number"!=typeof a?t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` was ${typeof r} instead of a number. If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01.`):a>1e11&&t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` is very large (${a}, representing ${new Date(1e3*a).toLocaleDateString()}). If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`)),t}sendBokenRequest(e,t){return y(this,null,(function*(){let n=0;const s=e.getBokensUrl(this.appId,this.userId,t),r=yield Un({method:"GET",url:s,attempts:1e4,shouldRetry:e=>{if(e instanceof Error)return!0;if(401===e.status)throw"Check that you provided a valid signature.";if(404===e.status)throw"Check that you specified the correct App ID.";if(429===e.status||502===e.status)return!0;if(e.status>=400&&e.status<500)throw`Unexpected HTTP ${e.status} response when fetching auth token. Check that you configured the session correctly.`;if(n++,n>=5)throw`Unexpected HTTP ${e.status} response when fetching auth token, retrying did not help.`;return!0}});return(yield r.json()).boken}))}}function Vn(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(atob(t).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));return JSON.parse(n)}catch(t){throw`Could not base64-decode and JSON-parse token section: ${e}. Check that you base-64 encoded the section correctly.`}}class Zn{constructor(e){this.target=e}deref(){return this.target}}const Kn=new class{constructor(){this.registry={}}getOrCreate(e){var t;const n=this.key(e),s=null==(t=this.registry[n])?void 0:t.deref();if(s)return s;const r=new Xn(e),i=globalThis.WeakRef?new WeakRef(r):new Zn(r);return this.registry[n]=i,r}deregister(e,t){const n=this.key({appId:e,userId:t});delete this.registry[n]}key({appId:e,userId:t}){return`${e}:${t}`}};class Xn{constructor(e){!function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in TalkSession#constructor."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of TalkSession#constructor is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of TalkSession#constructor is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of TalkSession#constructor must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of TalkSession#constructor must be a function.")}(e);const{appId:t,userId:n,token:s,tokenFetcher:r,signature:i}=e;this._appId=t,this._apiUrls=e.apiUrls?new jn(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):jn.fromHost(e.host),this._authProvider=new Qn(this._apiUrls,t,n,s,r,i);const a=Math.random().toString().split(".")[1];this._realtimeClient=new Ze(this._apiUrls.getRealtimeWsUrl(t,n,"1.5.7",a,e.clientBuild),n,this._authProvider),this.currentUser=new et(this._realtimeClient.userId,this._realtimeClient),this._terminationReason=T(),this._terminationReason.promise.then((e=>{console.error(`[TalkSession] ${e}`)})),function(e,t,n){return y(this,null,(function*(){return Un({method:"GET",url:`${t}/${e}/app`,authProvider:n}).then((e=>200===e.status||404!==e.status&&(console.warn(`[TalkJS] Received unexpected ${e.status} status code when validating app ID. Assuming that the app ID is valid.`),!0))).catch((e=>{if("string"!=typeof e&&"status"in e){const t=e;return 200===t.status||404!==t.status&&(console.warn(`[TalkJS] Received unexpected ${t.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)}return console.warn("[TalkJS] Encountered network issues when validating app ID. Assuming that the app ID is valid."),!0}))}))}(this._appId,this._apiUrls.internalHttpApiUrl,this._authProvider).then((e=>{e||this.terminate(new Error(`The app ID ${this._appId} does not exist. Make sure you are using the correct app ID as found on the TalkJS dashboard. App IDs are case-sensitive.`))})),this._authProvider.onTokenRefreshFailed((e=>{this.terminate(new Error(`Could not authenticate, cannot recover automatically: ${e}`))}))}onError(e){const t=T();return Promise.race([t.promise,this._terminationReason.promise]).then((t=>{"UNSUBSCRIBED"!==t&&e(t)})),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){if("string"!=typeof e)throw new Error(`Creating UserRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating UserRef failed because ID "${e}" is an empty string`);return new et(e,this._realtimeClient)}conversation(e){if("string"!=typeof e)throw new Error(`Creating ConversationRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating ConversationRef failed because ID "${e}" is an empty string`);return new On(e,this._realtimeClient)}subscribeConversations(e){return this._realtimeClient.subscribe(["me","conversations"],e)}terminate(e){Kn.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return es(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,t)}uploadImage(e,t){return es(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,d({subtype:"image"},t))}uploadVideo(e,t){return es(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,d({subtype:"video"},t))}uploadAudio(e,t){return es(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,d({subtype:"audio"},t))}uploadVoice(e,t){return es(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,d({subtype:"voice"},t))}}function es(e,t,n,s){return y(this,arguments,(function*(e,t,n,{subtype:s,filename:r,width:i,height:a,duration:o}){const u=new FormData;return u.set("file",n,r),void 0!==s&&u.set("subtype",s),void 0!==i&&u.set("width",i.toString()),void 0!==a&&u.set("height",a.toString()),void 0!==o&&u.set("duration",o.toString()),Un({method:"POST",url:e,data:u,authProvider:t}).then((e=>e.json())).then((e=>e.attachmentToken)).catch((e=>y(this,null,(function*(){if(e instanceof Response){const t=yield e.json(),n=`Unexpected response when uploading file, status code ${e.status} ${t.errorCode}, ${t.reasons}`;throw new Error(n)}throw e}))))}))}exports.getTalkSession=function(e){if(!e)throw new Error("[TalkJS] Must provide an options object to `getTalkSession`");return e.forceCreateNew?new Xn(e):Kn.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){R=e};
|
|
2
2
|
//# sourceMappingURL=talkSession.cjs.map
|
package/dist/talkSession.js
CHANGED
|
@@ -4,6 +4,9 @@ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
|
4
4
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
6
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __typeError = (msg) => {
|
|
8
|
+
throw TypeError(msg);
|
|
9
|
+
};
|
|
7
10
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
11
|
var __spreadValues = (a2, b2) => {
|
|
9
12
|
for (var prop in b2 || (b2 = {}))
|
|
@@ -29,6 +32,10 @@ var __objRest = (source, exclude) => {
|
|
|
29
32
|
}
|
|
30
33
|
return target;
|
|
31
34
|
};
|
|
35
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
36
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
37
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
38
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
32
39
|
var __async = (__this, __arguments, generator) => {
|
|
33
40
|
return new Promise((resolve, reject) => {
|
|
34
41
|
var fulfilled = (value) => {
|
|
@@ -49,7 +56,7 @@ var __async = (__this, __arguments, generator) => {
|
|
|
49
56
|
step((generator = generator.apply(__this, __arguments)).next());
|
|
50
57
|
});
|
|
51
58
|
};
|
|
52
|
-
var _a;
|
|
59
|
+
var _a, _e2, _t2, _b;
|
|
53
60
|
function e(e2, s2) {
|
|
54
61
|
if (s2.ok) return s2.value.data;
|
|
55
62
|
if ("SESSION_DESTROYED" === s2.value) throw new Error(`${e2} failed because the session was destroyed`);
|
|
@@ -786,10 +793,10 @@ class H {
|
|
|
786
793
|
return (_a2 = this.pendingPointer) != null ? _a2 : this.getPointer;
|
|
787
794
|
}
|
|
788
795
|
canAppendState(e2) {
|
|
789
|
-
var _a2,
|
|
796
|
+
var _a2, _b2;
|
|
790
797
|
const t2 = (_a2 = this.getPointer) == null ? void 0 : _a2.seq;
|
|
791
798
|
if (void 0 !== t2 && e2 <= t2) return false;
|
|
792
|
-
const s2 = (
|
|
799
|
+
const s2 = (_b2 = this.pendingPointer) == null ? void 0 : _b2.seq;
|
|
793
800
|
return !(void 0 !== s2 && e2 < s2);
|
|
794
801
|
}
|
|
795
802
|
set(e2) {
|
|
@@ -931,6 +938,20 @@ class J {
|
|
|
931
938
|
}
|
|
932
939
|
}
|
|
933
940
|
var Y, Q = {};
|
|
941
|
+
!function() {
|
|
942
|
+
if (Y) return Q;
|
|
943
|
+
function e2(e3) {
|
|
944
|
+
return String.fromCharCode(parseInt(e3.slice(1), 16));
|
|
945
|
+
}
|
|
946
|
+
function t2(e3) {
|
|
947
|
+
return `%${`00${e3.charCodeAt(0).toString(16)}`.slice(-2)}`;
|
|
948
|
+
}
|
|
949
|
+
Y = 1, Object.defineProperty(Q, "__esModule", { value: true }), Q.encode = function(t3) {
|
|
950
|
+
return btoa(encodeURIComponent(t3).replace(/%[0-9A-F]{2}/g, e2));
|
|
951
|
+
}, Q.decode = function(e3) {
|
|
952
|
+
return decodeURIComponent(Array.from(atob(e3), t2).join(""));
|
|
953
|
+
};
|
|
954
|
+
}();
|
|
934
955
|
function V(e2, t2) {
|
|
935
956
|
const s2 = t2.lastIndex;
|
|
936
957
|
let n2;
|
|
@@ -947,20 +968,7 @@ function K(e2, t2) {
|
|
|
947
968
|
t2 = e2.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/, "`$1`") + " was not true";
|
|
948
969
|
}
|
|
949
970
|
}
|
|
950
|
-
|
|
951
|
-
if (Y) return Q;
|
|
952
|
-
function e2(e3) {
|
|
953
|
-
return String.fromCharCode(parseInt(e3.slice(1), 16));
|
|
954
|
-
}
|
|
955
|
-
function t2(e3) {
|
|
956
|
-
return `%${`00${e3.charCodeAt(0).toString(16)}`.slice(-2)}`;
|
|
957
|
-
}
|
|
958
|
-
Y = 1, Object.defineProperty(Q, "__esModule", { value: true }), Q.encode = function(t3) {
|
|
959
|
-
return btoa(encodeURIComponent(t3).replace(/%[0-9A-F]{2}/g, e2));
|
|
960
|
-
}, Q.decode = function(e3) {
|
|
961
|
-
return decodeURIComponent(Array.from(atob(e3), t2).join(""));
|
|
962
|
-
};
|
|
963
|
-
}(), ((e2) => {
|
|
971
|
+
((e2) => {
|
|
964
972
|
function t2(e3) {
|
|
965
973
|
}
|
|
966
974
|
function s2(e3, t3) {
|
|
@@ -1015,9 +1023,9 @@ function re(e2, t2) {
|
|
|
1015
1023
|
const s2 = e2.map((e3) => function(e4, t3) {
|
|
1016
1024
|
if ("text" === e4.type) return function(e5, t4) {
|
|
1017
1025
|
const s3 = function(e6) {
|
|
1018
|
-
var _a2,
|
|
1026
|
+
var _a2, _b2, _c, _d, _e3, _f, _g, _h, _i, _j, _k, _l, _m;
|
|
1019
1027
|
let t5 = "";
|
|
1020
|
-
return e6.t && (t5 = `(${e6.t("CONTACT_INFORMATION_HIDDEN")})`), { formattedLinks: (_a2 = e6.formattedLinks) != null ? _a2 : "plaintext", markup: (
|
|
1028
|
+
return e6.t && (t5 = `(${e6.t("CONTACT_INFORMATION_HIDDEN")})`), { formattedLinks: (_a2 = e6.formattedLinks) != null ? _a2 : "plaintext", markup: (_b2 = e6.markup) != null ? _b2 : false, useFallbackMentions: (_c = e6.useFallbackMentions) != null ? _c : false, sameTabLinkRules: (_d = e6.sameTabLinkRules) != null ? _d : [], enableEmojiImageFallback: (_e3 = e6.enableEmojiImageFallback) != null ? _e3 : false, highlight: (_f = e6.highlight) != null ? _f : [], contactInfo: (_g = e6.contactInfo) != null ? _g : false, suppression: (_h = e6.suppression) != null ? _h : new ne({ mode: "off" }), contactInfoHiddenText: (_k = (_j = e6.contactInfoHiddenText) != null ? _j : (_i = e6.suppression) == null ? void 0 : _i.replacement) != null ? _k : t5, customEmojiUrls: (_l = e6.customEmojiUrls) != null ? _l : {}, enableActions: (_m = e6.enableActions) != null ? _m : true };
|
|
1021
1029
|
}(t4);
|
|
1022
1030
|
return ie(e5, s3);
|
|
1023
1031
|
}(e4.children, t3);
|
|
@@ -1162,8 +1170,8 @@ class le extends G {
|
|
|
1162
1170
|
}
|
|
1163
1171
|
loadNested(e2, t2) {
|
|
1164
1172
|
return __async(this, null, function* () {
|
|
1165
|
-
var _a2,
|
|
1166
|
-
const s2 = yield (
|
|
1173
|
+
var _a2, _b2, _c;
|
|
1174
|
+
const s2 = yield (_b2 = (_a2 = t2.sender) == null ? void 0 : _a2.store) == null ? void 0 : _b2.getDeep(e2);
|
|
1167
1175
|
if (false === (s2 == null ? void 0 : s2.ok)) return s2;
|
|
1168
1176
|
if (null === t2.data) return c({ snapshot: null });
|
|
1169
1177
|
const n2 = s2 == null ? void 0 : s2.value;
|
|
@@ -1184,7 +1192,7 @@ class le extends G {
|
|
|
1184
1192
|
}
|
|
1185
1193
|
getFromCache() {
|
|
1186
1194
|
return __async(this, null, function* () {
|
|
1187
|
-
var
|
|
1195
|
+
var _b2;
|
|
1188
1196
|
const e2 = yield this.mostRecentState.resultPromise;
|
|
1189
1197
|
if (!e2.ok) return l("NOT_IN_CACHE");
|
|
1190
1198
|
if (null === e2.value.data) {
|
|
@@ -1193,7 +1201,7 @@ class le extends G {
|
|
|
1193
1201
|
const _a2 = e2.value, { sender: t2 } = _a2, s2 = __objRest(_a2, ["sender"]), n2 = {};
|
|
1194
1202
|
return s2.data.reactions.forEach((e3) => {
|
|
1195
1203
|
n2[e3.emoji] = { count: e3.count, currentUserReacted: e3.currentUserReacted };
|
|
1196
|
-
}), c({ status: 200, data: __spreadProps(__spreadValues({}, s2.data), { senderId: (
|
|
1204
|
+
}), c({ status: 200, data: __spreadProps(__spreadValues({}, s2.data), { senderId: (_b2 = t2 == null ? void 0 : t2.store.userId) != null ? _b2 : null, reactions: n2 }) });
|
|
1197
1205
|
});
|
|
1198
1206
|
}
|
|
1199
1207
|
}
|
|
@@ -1237,14 +1245,14 @@ class de extends G {
|
|
|
1237
1245
|
}
|
|
1238
1246
|
loadNested(e2, t2) {
|
|
1239
1247
|
return __async(this, null, function* () {
|
|
1240
|
-
var _a2,
|
|
1248
|
+
var _a2, _b2, _c;
|
|
1241
1249
|
const s2 = yield t2.dataStore.getDeep(e2);
|
|
1242
1250
|
if (!s2.ok) return s2;
|
|
1243
1251
|
const n2 = s2.value;
|
|
1244
1252
|
if (null === n2.snapshot) return c({ snapshot: null });
|
|
1245
1253
|
const r2 = yield (_a2 = t2.referencedDataStore) == null ? void 0 : _a2.getDeep(e2);
|
|
1246
1254
|
if (r2 && !r2.ok) return r2;
|
|
1247
|
-
const i2 = (
|
|
1255
|
+
const i2 = (_b2 = r2 == null ? void 0 : r2.value) != null ? _b2 : null, a2 = (_c = i2 == null ? void 0 : i2.snapshot) != null ? _c : null;
|
|
1248
1256
|
return c({ snapshot: _({ id: n2.snapshot.id, type: n2.snapshot.type, sender: n2.snapshot.sender, custom: _(n2.snapshot.custom), createdAt: n2.snapshot.createdAt, editedAt: n2.snapshot.editedAt, referencedMessage: a2, origin: n2.snapshot.origin, plaintext: n2.snapshot.plaintext, content: n2.snapshot.content, reactions: n2.snapshot.reactions }) });
|
|
1249
1257
|
});
|
|
1250
1258
|
}
|
|
@@ -1402,7 +1410,7 @@ function fe(_0) {
|
|
|
1402
1410
|
});
|
|
1403
1411
|
}
|
|
1404
1412
|
function me({ seq: e2, prevState: t2, messages: s2, cursor: n2, conversationId: r2, realtimeClient: i2 }) {
|
|
1405
|
-
var _a2,
|
|
1413
|
+
var _a2, _b2, _c, _d;
|
|
1406
1414
|
const a2 = t2 ? __spreadValues({}, t2.stores) : {};
|
|
1407
1415
|
for (const t3 of s2) if (void 0 === a2[t3.id]) {
|
|
1408
1416
|
const s3 = new le(e2, r2, t3, i2);
|
|
@@ -1418,7 +1426,7 @@ function me({ seq: e2, prevState: t2, messages: s2, cursor: n2, conversationId:
|
|
|
1418
1426
|
const o2 = t2 ? [...t2.inWindow] : [];
|
|
1419
1427
|
for (const t3 of s2) o2.push(new de(e2, t3.createdAt, a2[t3.id], t3.referencedMessageId ? a2[t3.referencedMessageId] : null));
|
|
1420
1428
|
o2.sort((e3, t3) => t3.createdAt - e3.createdAt);
|
|
1421
|
-
const u2 = (
|
|
1429
|
+
const u2 = (_b2 = (_a2 = t2 == null ? void 0 : t2.inWindow) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.messageId, l2 = (_c = o2 == null ? void 0 : o2[0]) == null ? void 0 : _c.messageId, h2 = u2 === l2 ? (_d = t2 == null ? void 0 : t2.lastMessageChanged) != null ? _d : e2 : e2;
|
|
1422
1430
|
if (null === n2) return c({ lastChanged: e2, lastMessageChanged: h2, stores: a2, inWindow: o2, windowEnd: null });
|
|
1423
1431
|
return c({ lastChanged: e2, lastMessageChanged: h2, stores: a2, inWindow: o2, windowEnd: { cursor: n2, oldestMessageTs: s2[s2.length - 1].createdAt } });
|
|
1424
1432
|
}
|
|
@@ -1547,8 +1555,8 @@ class ye extends G {
|
|
|
1547
1555
|
throw "Do not call refetch on participant data stores, it can return outdated data. Destroy and remake them instead";
|
|
1548
1556
|
}
|
|
1549
1557
|
equal(e2, t2) {
|
|
1550
|
-
var _a2,
|
|
1551
|
-
return ((
|
|
1558
|
+
var _a2, _b2, _c, _d;
|
|
1559
|
+
return ((_b2 = (_a2 = e2.user) == null ? void 0 : _a2.store) == null ? void 0 : _b2.userId) === ((_d = (_c = t2.user) == null ? void 0 : _c.store) == null ? void 0 : _d.userId) && W(e2.data, t2.data);
|
|
1552
1560
|
}
|
|
1553
1561
|
teardownNested(e2) {
|
|
1554
1562
|
var _a2;
|
|
@@ -1743,8 +1751,8 @@ class ke extends z {
|
|
|
1743
1751
|
if (n2) return n2;
|
|
1744
1752
|
const r2 = s2.filter((e3) => null !== e3.value.snapshot).map((e3) => e3.value.snapshot);
|
|
1745
1753
|
return r2.sort((e3, t3) => {
|
|
1746
|
-
var _a2,
|
|
1747
|
-
const s3 = (
|
|
1754
|
+
var _a2, _b2, _c, _d;
|
|
1755
|
+
const s3 = (_b2 = (_a2 = e3.lastMessage) == null ? void 0 : _a2.createdAt) != null ? _b2 : e3.joinedAt;
|
|
1748
1756
|
return ((_d = (_c = t3.lastMessage) == null ? void 0 : _c.createdAt) != null ? _d : t3.joinedAt) - s3;
|
|
1749
1757
|
}), c({ snapshot: _(r2), loadedAll: null === t2.windowEnd });
|
|
1750
1758
|
});
|
|
@@ -1985,14 +1993,14 @@ class Me {
|
|
|
1985
1993
|
}));
|
|
1986
1994
|
}
|
|
1987
1995
|
handlePublish(e2, t2) {
|
|
1988
|
-
var _a2,
|
|
1996
|
+
var _a2, _b2, _c, _d, _e3, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s2, _t3, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D;
|
|
1989
1997
|
switch (t2.type) {
|
|
1990
1998
|
case "user.created":
|
|
1991
|
-
return (_a2 = this.storeMap[`/users/${t2.userId}`]) == null ? void 0 : _a2.userCreated(e2, t2), (
|
|
1999
|
+
return (_a2 = this.storeMap[`/users/${t2.userId}`]) == null ? void 0 : _a2.userCreated(e2, t2), (_b2 = this.storeMap["/me/conversations"]) == null ? void 0 : _b2.userCreated(e2, t2), void ((_c = this.storeMap[`/users/${t2.userId}/online`]) == null ? void 0 : _c.userCreated(e2, t2));
|
|
1992
2000
|
case "user.edited":
|
|
1993
2001
|
return void ((_d = this.storeMap[`/users/${t2.userId}`]) == null ? void 0 : _d.userEdited(e2, t2));
|
|
1994
2002
|
case "side.created":
|
|
1995
|
-
return (
|
|
2003
|
+
return (_e3 = this.convDataStores[t2.conversationId]) == null ? void 0 : _e3.sideCreated(e2, t2), (_f = this.storeMap[`/me/conversations/${t2.conversationId}/messages`]) == null ? void 0 : _f.sideCreated(e2, t2), (_g = this.storeMap[`/me/conversations/${t2.conversationId}/participants`]) == null ? void 0 : _g.sideCreated(e2, t2), void ((_h = this.storeMap["/me/conversations"]) == null ? void 0 : _h.sideCreated(e2, t2));
|
|
1996
2004
|
case "side.edited":
|
|
1997
2005
|
return (_i = this.convDataStores[t2.conversationId]) == null ? void 0 : _i.sideEdited(e2, t2), void ((_j = this.storeMap["/me/conversations"]) == null ? void 0 : _j.sideEdited(e2, t2));
|
|
1998
2006
|
case "side.deleted":
|
|
@@ -2006,7 +2014,7 @@ class Me {
|
|
|
2006
2014
|
case "message.deleted":
|
|
2007
2015
|
return void ((_s2 = this.storeMap[`/me/conversations/${t2.conversationId}/messages`]) == null ? void 0 : _s2.messageDeleted(e2, t2));
|
|
2008
2016
|
case "typing.available":
|
|
2009
|
-
return void ((
|
|
2017
|
+
return void ((_t3 = this.storeMap[`/me/conversations/${t2.conversationId}/typing`]) == null ? void 0 : _t3.typingAvailable(e2, t2));
|
|
2010
2018
|
case "typing.changed":
|
|
2011
2019
|
return void ((_u = this.storeMap[`/me/conversations/${t2.conversationId}/typing`]) == null ? void 0 : _u.typingChanged(e2, t2));
|
|
2012
2020
|
case "conversation.cleared":
|
|
@@ -3447,7 +3455,7 @@ class bs {
|
|
|
3447
3455
|
function ys({ method: e2, url: t2, data: s2, options: n2, attempts: r2, shouldRetry: i2, authProvider: o2 }) {
|
|
3448
3456
|
var _a2;
|
|
3449
3457
|
(!r2 || r2 <= 0) && (r2 = 1);
|
|
3450
|
-
const u2 = { "x-talkjs-client-build": "jssdk-dev", "x-talkjs-client-date": "2025-10-
|
|
3458
|
+
const u2 = { "x-talkjs-client-build": "jssdk-dev", "x-talkjs-client-date": "2025-10-30T09:02:16.772Z" };
|
|
3451
3459
|
s2 instanceof FormData || (u2["Content-Type"] = (_a2 = n2 == null ? void 0 : n2.contentType) != null ? _a2 : "application/json");
|
|
3452
3460
|
return a(r2, () => __async(this, null, function* () {
|
|
3453
3461
|
if (o2) {
|
|
@@ -3473,6 +3481,7 @@ function ys({ method: e2, url: t2, data: s2, options: n2, attempts: r2, shouldRe
|
|
|
3473
3481
|
}
|
|
3474
3482
|
const { cdnHost: Cs, appHost: As, restHost: Es, realtimeHost: ks, appProtocol: xs, appWsProtocol: Is } = function() {
|
|
3475
3483
|
if ("undefined" == typeof window) return { cdnHost: "test-hostname", appHost: "test-hostname", appProtocol: "http:", appWsProtocol: "ws:" };
|
|
3484
|
+
if (!globalThis.document) return { appHost: "app.talkjs.com", appProtocol: "http:", appWsProtocol: "ws:" };
|
|
3476
3485
|
const e2 = function() {
|
|
3477
3486
|
if (document.currentScript) return document.currentScript.src;
|
|
3478
3487
|
try {
|
|
@@ -3481,9 +3490,7 @@ const { cdnHost: Cs, appHost: As, restHost: Es, realtimeHost: ks, appProtocol: x
|
|
|
3481
3490
|
const t3 = e3.stack.match(/https?:\/\/.*\.(js|jsx|ts|tsx)/);
|
|
3482
3491
|
return t3 ? t3[0] : "";
|
|
3483
3492
|
}
|
|
3484
|
-
}(), t2 =
|
|
3485
|
-
t2.href = e2;
|
|
3486
|
-
const s2 = t2.host, n2 = function(e3) {
|
|
3493
|
+
}(), t2 = new URL(e2), s2 = t2.host, n2 = function(e3) {
|
|
3487
3494
|
if (e3.match(/^cdn[.-]/)) return e3.replace(/^cdn/, "app");
|
|
3488
3495
|
if ("talkjs.com" === e3) return "app.talkjs.com";
|
|
3489
3496
|
return e3;
|
|
@@ -3498,9 +3505,12 @@ const { cdnHost: Cs, appHost: As, restHost: Es, realtimeHost: ks, appProtocol: x
|
|
|
3498
3505
|
}();
|
|
3499
3506
|
const Ts = As.startsWith("app.talkjs.com");
|
|
3500
3507
|
const Ds = "undefined" == typeof window ? { log: (e2) => Promise.resolve(), setData: (e2) => {
|
|
3501
|
-
} } : new class {
|
|
3508
|
+
} } : new (_b = class {
|
|
3502
3509
|
constructor(e2) {
|
|
3503
|
-
|
|
3510
|
+
__privateAdd(this, _e2);
|
|
3511
|
+
__privateAdd(this, _t2);
|
|
3512
|
+
var _a2, _b2, _c, _d;
|
|
3513
|
+
this._timeCreated = Date.now(), this._enabled = Ts, __privateSet(this, _e2, (_b2 = (_a2 = globalThis.document) == null ? void 0 : _a2.referrer) != null ? _b2 : ""), __privateSet(this, _t2, ((_d = (_c = globalThis.location) == null ? void 0 : _c.href) != null ? _d : globalThis.HermesInternal) ? "React Native Hermes" : ""), this._trackJSData = { customer: { application: "", correlationId: "", sessionId: "", token: "", userId: "", version: "dev-2025-10-30T09:02:16.772Z" }, entry: "direct", environment: { age: Date.now() - this._timeCreated, dependencies: {}, originalUrl: __privateGet(this, _t2), referrer: __privateGet(this, _e2), userAgent: window.navigator.userAgent }, metadata: [], nav: [], network: [], url: __privateGet(this, _t2), stack: "", timestamp: (/* @__PURE__ */ new Date()).toISOString(), version: "dev-2025-10-30T09:02:16.772Z", throttled: 0 }, this._url = `https://capture.trackjs.com/capture?token=${e2}`, this._trackJSData.customer.token = e2;
|
|
3504
3514
|
}
|
|
3505
3515
|
setData({ appId: e2, meId: t2, sessionId: s2 }) {
|
|
3506
3516
|
this._trackJSData.customer.userId = e2, this._trackJSData.customer.sessionId = `${e2}/${t2}`, this._trackJSData.customer.correlationId = s2;
|
|
@@ -3516,7 +3526,7 @@ const Ds = "undefined" == typeof window ? { log: (e2) => Promise.resolve(), setD
|
|
|
3516
3526
|
}
|
|
3517
3527
|
});
|
|
3518
3528
|
}
|
|
3519
|
-
}("970cd0be0fb74630b75c8451051299dc");
|
|
3529
|
+
}, _e2 = new WeakMap(), _t2 = new WeakMap(), _b)("970cd0be0fb74630b75c8451051299dc");
|
|
3520
3530
|
class Ss {
|
|
3521
3531
|
constructor(e2, t2 = {}) {
|
|
3522
3532
|
this._onSubscription = t2, this._handlers = {};
|
|
@@ -3543,9 +3553,9 @@ class Ss {
|
|
|
3543
3553
|
return e2 in this._handlers;
|
|
3544
3554
|
}
|
|
3545
3555
|
on(e2, t2) {
|
|
3546
|
-
var _a2,
|
|
3556
|
+
var _a2, _b2;
|
|
3547
3557
|
if (!this.supports(e2)) throw new Error(`Unknown event type '${String(e2)}'`);
|
|
3548
|
-
(
|
|
3558
|
+
(_b2 = (_a2 = this._onSubscription)[e2]) == null ? void 0 : _b2.call(_a2), this._handlers[e2].push(t2);
|
|
3549
3559
|
}
|
|
3550
3560
|
off(e2, t2) {
|
|
3551
3561
|
if (!Object.hasOwnProperty.call(this._handlers, e2)) throw new Error(`Unknown event type '${String(e2)}'`);
|
|
@@ -3763,7 +3773,7 @@ class _s {
|
|
|
3763
3773
|
const { appId: t2, userId: s2, token: n2, tokenFetcher: r2, signature: i2 } = e2;
|
|
3764
3774
|
this._appId = t2, this._apiUrls = e2.apiUrls ? new bs(e2.apiUrls.realtimeWsApiUrl, e2.apiUrls.internalHttpApiUrl, e2.apiUrls.restApiHttpUrl) : bs.fromHost(e2.host), this._authProvider = new Ms(this._apiUrls, t2, s2, n2, r2, i2);
|
|
3765
3775
|
const a2 = Math.random().toString().split(".")[1];
|
|
3766
|
-
this._realtimeClient = new Be(this._apiUrls.getRealtimeWsUrl(t2, s2, "1.5.
|
|
3776
|
+
this._realtimeClient = new Be(this._apiUrls.getRealtimeWsUrl(t2, s2, "1.5.7", a2, e2.clientBuild), s2, this._authProvider), this.currentUser = new _e(this._realtimeClient.userId, this._realtimeClient), this._terminationReason = o(), this._terminationReason.promise.then((e3) => {
|
|
3767
3777
|
console.error(`[TalkSession] ${e3}`);
|
|
3768
3778
|
}), function(e3, t3, s3) {
|
|
3769
3779
|
return __async(this, null, function* () {
|