@talkjs/core
Version:
Lets you connect to your TalkJS chat as a user and read, subscribe to, and update your chat data.
1,225 lines • 272 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a2, b2) => {
for (var prop in b2 || (b2 = {}))
if (__hasOwnProp.call(b2, prop))
__defNormalProp(a2, prop, b2[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b2)) {
if (__propIsEnum.call(b2, prop))
__defNormalProp(a2, prop, b2[prop]);
}
return a2;
};
var __spreadProps = (a2, b2) => __defProps(a2, __getOwnPropDescs(b2));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
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);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e2) {
reject(e2);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e2) {
reject(e2);
}
};
var step = (x2) => x2.done ? resolve(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var _a, _b, _e2, _t2;
const e = Symbol("*"), t = e, s = e, n = e, r = e, a = e;
function i(t2, s2) {
if (t2.length !== s2.length) return false;
for (let n2 = 0; n2 < t2.length; n2++) if (s2[n2] !== e && t2[n2] !== s2[n2]) return false;
return true;
}
function o(e2) {
return e2 <= 0 ? Promise.resolve() : new Promise((t2) => setTimeout(t2, e2));
}
function c(e2, t2) {
return e2 * (1 - t2 + 2 * Math.random() * t2);
}
const l = () => true;
function u(_0, _1, _2) {
return __async(this, arguments, function* (e2, t2, { initialDelay: s2, maxDelay: n2, log: r2, shouldRetry: a2 = l }) {
return t2().catch((i2) => __async(null, null, function* () {
if (0 === e2) throw i2;
if (!(yield a2(i2))) throw i2;
const l2 = 1e3 * s2 * 1.2, h2 = c(n2 ? Math.min(1e3 * n2, l2) : l2, 0.05);
return o(h2).then(() => u(e2 - 1, t2, { initialDelay: h2 / 1e3, maxDelay: n2, log: r2, shouldRetry: a2 }));
}));
});
}
function h() {
const e2 = {}, t2 = new Promise(function(t3, s2) {
e2.resolve = t3, e2.reject = s2;
});
return e2.promise = t2, e2;
}
class d {
constructor(e2, t2, s2) {
this.layer = e2, this.states = t2, this.transitions = s2, this._state = t2[0];
}
get state() {
return this._state;
}
transition(e2) {
const t2 = this.transitions[e2];
if (!t2) return;
if (!this.canTransition(e2)) return;
const s2 = this.state;
this._state = t2.to, t2.afterTransition({ from: s2, to: this.state });
}
canTransition(e2) {
const t2 = this.transitions[e2];
return !!t2 && ("ANY" === t2.from || t2.from.includes(this.state));
}
}
function p(e2) {
return { ok: true, value: e2 };
}
function f(e2) {
return { ok: false, where: "client", value: e2 };
}
function m(e2) {
return { ok: false, where: "server", value: e2 };
}
function g() {
const e2 = {}, t2 = new Promise((t3) => {
e2.ok = (e3) => __async(null, null, function* () {
return t3(p(e3));
}), e2.clientErr = (e3) => t3(f(e3)), e2.serverErr = (e3) => t3(m(e3)), e2.resolve = (e3) => t3(e3);
});
return e2.promise = t2, e2;
}
function v(e2) {
return e2.filter((e3) => e3.ok).map((e3) => e3.value);
}
function y(e2, t2) {
if (t2.ok) return t2.value.data;
if ("SESSION_DESTROYED" === t2.value) throw new Error(`${e2} failed because the session was destroyed`);
if ("server" === t2.where) throw new Error(w(e2, t2.value));
throw "unreachable";
}
function w(e2, t2) {
let s2;
return s2 = Array.isArray(t2.reasons) ? t2.reasons.join() : JSON.stringify(t2.reasons), `${e2} failed, got status ${t2.status} ${t2.errorCode}, reasons: ${s2}`;
}
let b = null;
function k({ WebSocket: e2 }) {
b = e2;
}
class C {
constructor(e2, t2) {
this.realtimeUrl = e2, this.handlers = t2, this.socket = null, this.stateMachine = new d("ReconnectingSocket", ["STOPPED", "CONNECTING", "READY", "DISCONNECTED", "TERMINATED"], { startWs: { from: ["STOPPED", "DISCONNECTED"], to: "CONNECTING", afterTransition: () => {
const e3 = new ((function() {
if (b) return b;
if (globalThis.WebSocket) return globalThis.WebSocket;
throw new Error("Missing WebSocket implementation");
})())(this.realtimeUrl + "&talkjs-time=" + Date.now());
this.socket = e3, e3.addEventListener("open", () => {
this.socket === e3 && this.stateMachine.transition("onOpen");
}), e3.addEventListener("close", () => {
this.socket === e3 && this.stateMachine.transition("onClose");
}), e3.addEventListener("message", (t3) => {
this.socket === e3 && this.handlers.onMessage(t3);
});
} }, onOpen: { from: ["CONNECTING"], to: "READY", afterTransition: () => {
this.handlers.onOpen();
} }, onClose: { from: ["CONNECTING", "READY"], to: "DISCONNECTED", afterTransition: (_0) => __async(this, [_0], function* ({ from: e3 }) {
"READY" === e3 && this.handlers.onClose(), this.socket = null;
const t3 = c(1e4, 0.5);
setTimeout(() => {
"DISCONNECTED" === this.stateMachine.state && this.stateMachine.transition("startWs");
}, t3);
}) }, stopWs: { from: ["CONNECTING", "DISCONNECTED", "READY"], to: "STOPPED", afterTransition: ({ from: e3 }) => {
"READY" === e3 && this.handlers.onClose();
const t3 = this.socket;
this.socket = null, t3 == null ? void 0 : t3.close(1e3);
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
const e3 = this.socket;
this.socket = null, e3 == null ? void 0 : e3.close(1e3);
} } });
}
stopWs() {
this.stateMachine.transition("stopWs");
}
startWs() {
this.stateMachine.transition("startWs");
}
send(e2) {
return "READY" === this.stateMachine.state ? (this.socket.send(e2), p(void 0)) : f("SOCKET_NOT_READY");
}
terminate() {
const e2 = this.socket;
this.stateMachine.canTransition("onClose") && this.stateMachine.transition("onClose"), e2 && ("terminate" in e2 ? e2.terminate() : e2.close(1e3));
}
destroy() {
this.stateMachine.transition("destroy");
}
}
class S {
constructor(e2, t2) {
this.handlers = t2, this.socket = new C(e2, { onOpen: () => this.handlers.onOpen(), onClose: () => this.handlers.onClose(), onMessage: (e3) => this.onWebSocketMessage(e3) });
}
call(e2, t2) {
const s2 = `/${t2.path.map((e3) => encodeURIComponent(e3)).join("/")}`, n2 = JSON.stringify([e2, t2.method, s2, t2.data, t2.headers]);
return this.socket.send(n2);
}
stopWs() {
this.socket.stopWs();
}
startWs() {
this.socket.startWs();
}
destroy() {
this.socket.destroy();
}
terminate() {
this.socket.terminate();
}
onWebSocketMessage(e2) {
try {
const t2 = JSON.parse(e2.data);
if ("PUBLISH" === t2[1]) {
const e3 = t2[0], s2 = JSON.stringify([e3, "ACK"]);
this.socket.send(s2);
const n2 = t2.slice(2), r2 = [];
n2.forEach((e4) => {
"session.expired" === e4.type ? this.handlers.onAuthExpired() : "upstream.restarting" === e4.type ? this.handlers.onUpstreamRestarting() : r2.push(e4);
}), r2.length > 0 && this.handlers.onPublish(e3, r2);
} else {
const e3 = t2[0], s2 = t2[1], n2 = t2[2];
this.handlers.onResponse(e3, s2, n2);
}
} catch (e3) {
}
}
}
class I {
constructor(e2) {
this.delayMs = e2, this.timeout = void 0;
}
schedule(e2) {
this.stop(), this.timeout = setTimeout(() => {
void 0 !== this.timeout && (this.stop(), e2());
}, this.delayMs);
}
stop() {
void 0 !== this.timeout && (clearTimeout(this.timeout), this.timeout = void 0);
}
}
const T = "undefined" != typeof window ? (_a = window.queueMicrotask) != null ? _a : setTimeout : setTimeout;
class x {
constructor() {
this.i = -1;
}
next() {
return this.i++, this.i;
}
reset() {
this.i = -1;
}
}
class E {
constructor(e2, t2) {
this.handlers = t2, this.seqCounter = new x(), this.responseHandlers = {}, this.heartbeats = new M(this), this.socket = new S(e2, { 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((e3) => {
e3.clientErr("WEBSOCKET_DISCONNECTED");
}), this.responseHandlers = {}, this.seqCounter.reset(), this.handlers.onNotReady();
}, onResponse: (e3, t3, s2) => {
this.heartbeats.serverActive(), this.onResponse(e3, t3, s2);
}, onPublish: (e3, t3) => {
this.heartbeats.serverActive(), this.handlers.onPublish(e3, t3), this.heartbeats.clientActive();
}, onAuthExpired: () => {
this.heartbeats.serverActive(), this.handlers.onAuthExpired();
} });
}
sync() {
return __async(this, null, function* () {
yield new Promise((e3) => T(() => e3()));
const e2 = Object.values(this.responseHandlers).map((e3) => e3.promise.catch(() => {
}));
return Promise.all(e2);
});
}
call(e2) {
const t2 = this.seqCounter.next(), s2 = g();
this.responseHandlers[t2] = s2;
const n2 = this.socket.call(t2, e2);
return n2.ok || (s2.resolve(n2), delete this.responseHandlers[t2]), this.heartbeats.clientActive(), s2.promise;
}
onResponse(e2, t2, s2) {
return __async(this, null, function* () {
const n2 = this.responseHandlers[e2];
n2 && (200 === t2 ? n2.ok({ status: t2, data: s2 }) : n2.serverErr({ status: t2, errorCode: s2.errorCode, reasons: s2.reasons }), delete this.responseHandlers[e2]);
});
}
stopWs() {
this.socket.stopWs();
}
startWs() {
this.socket.startWs();
}
destroy() {
this.heartbeats.stop(), Object.values(this.responseHandlers).forEach((e2) => {
e2.clientErr("WEBSOCKET_DISCONNECTED");
}), this.responseHandlers = {}, this.socket.destroy();
}
terminate() {
this.socket.terminate();
}
}
class M {
constructor(e2) {
this.connection = e2, this.clientInactivityTimer = new I(25e3), this.serverInactivityTimer = new I(1e4), this.serverTimeoutTimer = new I(5e3);
}
clientActive() {
this.clientInactivityTimer.schedule(() => {
this.sendHeartbeat();
});
}
serverActive() {
this.serverTimeoutTimer.stop(), this.serverInactivityTimer.schedule(() => {
this.sendHeartbeat(), this.serverTimeoutTimer.schedule(() => {
this.connection.terminate();
});
});
}
stop() {
this.clientInactivityTimer.stop(), this.serverInactivityTimer.stop(), this.serverTimeoutTimer.stop();
}
sendHeartbeat() {
this.connection.call({ method: "GET", path: ["ping"], data: {}, headers: {} }).catch(() => {
});
}
}
class R {
constructor(e2, t2, s2) {
this.authProvider = t2, this.handlers = s2, this.stateMachine = new d("AuthenticatedConnection", ["WAITING_FOR_WS", "LOGGING_IN", "RENEWING_SESSION", "READY", "TERMINATED"], { logIn: { from: ["WAITING_FOR_WS"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
yield this.renewSession();
}) }, logInFailed: { from: ["LOGGING_IN"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
this.authProvider.invalidateAndRefresh(), yield this.renewSession();
}) }, scheduledReauth: { from: ["READY"], to: "RENEWING_SESSION", afterTransition: () => __async(this, null, function* () {
yield this.renewSession();
}) }, scheduledReauthFailed: { from: ["RENEWING_SESSION"], to: "RENEWING_SESSION", afterTransition: () => __async(this, null, function* () {
this.authProvider.invalidateAndRefresh(), yield this.renewSession();
}) }, authenticated: { from: ["LOGGING_IN", "RENEWING_SESSION"], to: "READY", afterTransition: ({ from: e3 }) => {
"LOGGING_IN" === e3 && this.handlers.onReady();
} }, authExpired: { from: ["READY", "RENEWING_SESSION"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
this.handlers.onNotReady(), this.authProvider.invalidateAndRefresh(), yield this.renewSession();
}) }, wsDisconnected: { from: ["READY", "LOGGING_IN", "RENEWING_SESSION"], to: "WAITING_FOR_WS", afterTransition: ({ from: e3 }) => {
"READY" !== e3 && "RENEWING_SESSION" !== e3 || this.handlers.onNotReady(), this.authProvider.clearScheduledRefresh();
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
this.authProvider.clearScheduledRefresh(), this.connection.destroy();
} } }), this.connection = new E(e2, { onUpstreamRestarting: () => this.handlers.onUpstreamRestarting(), onReady: () => this.stateMachine.transition("logIn"), onNotReady: () => {
this.stateMachine.transition("wsDisconnected");
}, onAuthExpired: () => {
this.stateMachine.transition("authExpired");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} }), t2.onTokenChanged(() => {
"READY" === this.stateMachine.state && this.stateMachine.transition("scheduledReauth");
});
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
const t2 = this.connection.call(e2);
return t2.then((e3) => {
e3.ok || "server" !== e3.where || 401 !== e3.value.status || "READY" !== this.stateMachine.state && "RENEWING_SESSION" !== this.stateMachine.state || this.stateMachine.transition("authExpired");
}), t2;
}
stopWs() {
this.connection.stopWs();
}
startWs() {
this.connection.startWs(), this.authProvider.getToken().catch(() => {
});
}
destroy() {
this.stateMachine.transition("destroy");
}
renewSession() {
return __async(this, null, function* () {
let e2;
try {
const t3 = this.authProvider.getCachedToken();
e2 = t3 || (yield this.authProvider.getToken());
} catch (e3) {
return;
}
const t2 = yield this.connection.call({ method: "POST", path: ["session", "renew"], data: { token: e2 }, headers: {} });
if (!t2.ok && "client" === t2.where) return;
const s2 = t2.value;
if (s2.status, 200 === s2.status) {
const t3 = s2.data.expiresInSeconds;
return void (null !== t3 && t3 < 120 ? (console.warn(`[TalkJS] Authenticated with a token that expires in ${t3}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(t3), this.authProvider.emitTokenAccepted(e2), this.stateMachine.canTransition("authenticated") && this.stateMachine.transition("authenticated")));
}
if (401 === s2.status) return void ("LOGGING_IN" === this.stateMachine.state ? this.stateMachine.transition("logInFailed") : "RENEWING_SESSION" === this.stateMachine.state && this.stateMachine.transition("scheduledReauthFailed"));
if (400 === s2.status) return void this.authProvider.emitTokenRefreshFailed(w("Authentication", s2));
if (402 === s2.status) return void this.authProvider.emitTokenRefreshFailed(w("Authentication", s2));
const n2 = 5e3 * Math.random() + 5e3;
setTimeout(() => {
this.call({ method: "POST", path: ["session", "renew"], data: { token: e2 }, headers: {} }).catch(() => {
});
}, n2);
});
}
}
class A {
constructor(e2, t2, s2) {
this.handlers = s2, 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 I(3e3), this.connection = new R(e2, t2, { onUpstreamRestarting: () => {
this.handlers.onUpstreamRestarting();
}, onReady: () => {
this.stateMachine.transition("ready");
}, onNotReady: () => {
"READY" === this.stateMachine.state && this.stateMachine.transition("unexpectedDisconnect");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
get inactive() {
return 0 === this.pendingCalls && 0 === this.activeSubscriptions;
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
ensureStarted() {
this.stateMachine.canTransition("start") && this.stateMachine.transition("start");
}
call(e2) {
return __async(this, null, function* () {
this.inactivityTimer.stop(), this.pendingCalls++, this.logTrace("Called", e2.path, e2.data);
const t2 = yield this.connection.call(e2);
return this.pendingCalls--, this.logTrace("Received", e2.path, e2.data), "SUBSCRIBE" === e2.method && t2.ok ? (this.activeSubscriptions++, this.logTrace("Subscribed", e2.path, e2.data)) : "UNSUBSCRIBE" === e2.method && t2.ok && (this.activeSubscriptions--, this.logTrace("Unsubscribed", e2.path, e2.data)), this.inactive && this.inactivityTimer.schedule(() => {
this.stateMachine.transition("stop");
}), t2;
});
}
destroy() {
this.stateMachine.transition("destroy");
}
isConnected() {
return "READY" === this.stateMachine.state;
}
logTrace(e2, t2, s2) {
}
}
class _ {
constructor(e2, t2, s2) {
this.handlers = s2, 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((e3) => e3.deferred.ok({ status: 200, data: {} })), this.subscribeQueue = {}, this.handlers.onSubscriptionsLost();
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
var _a2;
for (; this.callQueue.length; ) {
const e3 = (_a2 = this.callQueue.shift()) == null ? void 0 : _a2.deferred;
e3 == null ? void 0 : e3.clientErr("SESSION_DESTROYED");
}
this.connection.destroy();
} } }), this.subscribeQueue = {}, this.callQueue = [], this.connection = new A(e2, t2, { onUpstreamRestarting: () => {
this.handlers.onUpstreamRestarting();
}, onReady: () => {
this.stateMachine.transition("processQueue");
}, onNotReady: () => {
this.stateMachine.transition("notReady");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
return "READY" === this.stateMachine.state ? this.connection.call(e2) : ("NOT_READY" === this.stateMachine.state && this.connection.ensureStarted(), "SUBSCRIBE" === e2.method || "UNSUBSCRIBE" === e2.method ? this._subscribe(e2) : this._call(e2));
}
_subscribe(e2) {
const t2 = e2.path.join("/"), s2 = this.subscribeQueue[t2];
if (s2 && s2.params.method === e2.method) return s2.deferred.promise;
s2 && s2.params.method !== e2.method && (s2.deferred.ok({ status: 200, data: {} }), delete this.subscribeQueue[t2]);
const n2 = { deferred: g(), params: e2 };
return this.subscribeQueue[t2] = n2, n2.deferred.promise;
}
_call(e2) {
const t2 = { deferred: g(), params: e2 };
return this.callQueue.push(t2), t2.deferred.promise;
}
dequeue() {
for (const e2 in this.subscribeQueue) {
const t2 = this.subscribeQueue[e2];
return delete this.subscribeQueue[e2], t2;
}
return this.callQueue.shift();
}
destroy() {
this.stateMachine.transition("destroy");
}
sendQueuedCalls() {
return __async(this, null, function* () {
let e2 = 0;
for (; "PROCESSING_QUEUE" === this.stateMachine.state; ) {
e2++;
const t2 = this.dequeue();
if (!t2) return void this.stateMachine.transition("ready");
this.connection.call(t2.params).then((e3) => {
t2.deferred.resolve(e3);
}), e2 > 50 && (yield new Promise((e3) => setTimeout(e3, 100)));
}
});
}
isConnected() {
return "READY" === this.stateMachine.state || "PROCESSING_QUEUE" === this.stateMachine.state;
}
}
function N(e2) {
return Object.freeze(e2);
}
function D(e2) {
return N(e2.map((e3) => (function(e4) {
switch (e4.type) {
case "text":
return Object.freeze({ type: "text", children: O(e4.children) });
case "file":
case "location":
return Object.freeze(e4);
}
})(e3)));
}
function O(e2) {
return N(e2.map((e3) => (function(e4) {
if ("string" == typeof e4) return e4;
switch (e4.type) {
case "bold":
case "italic":
case "strikethrough":
case "bulletList":
case "bulletPoint":
case "link":
case "actionLink":
case "actionButton":
return Object.freeze(__spreadProps(__spreadValues({}, e4), { children: O(e4.children) }));
case "mention":
case "autoLink":
case "codeSpan":
case "customEmoji":
return Object.freeze(e4);
}
})(e3)));
}
function P(e2, t2) {
return void 0 === t2 ? e2 : t2;
}
function j(e2, t2) {
return void 0 === t2 ? e2 : N(t2);
}
function U(e2, t2) {
if (void 0 === t2) return e2;
if (null === t2) return N({});
const s2 = __spreadValues({}, e2);
for (const e3 in t2) {
const n2 = t2[e3];
null === n2 ? delete s2[e3] : s2[e3] = n2;
}
return N(s2);
}
function $(e2, t2) {
if (e2 === t2) return true;
if (!e2 || !t2) return false;
if ("object" != typeof e2 || "object" != typeof t2) return false;
if (e2.constructor !== t2.constructor) return false;
if (Array.isArray(e2) && Array.isArray(t2)) {
if (e2.length !== t2.length) return false;
for (let s2 = 0; s2 < e2.length; s2++) if (!$(e2[s2], t2[s2])) return false;
} else {
const s2 = Object.keys(e2);
if (s2.length !== Object.keys(t2).length) return false;
for (const n2 of s2) {
if (!Object.hasOwnProperty.call(t2, n2)) return false;
if (!$(e2[n2], t2[n2])) return false;
}
}
return true;
}
const W = "undefined" != typeof window ? (_b = window.queueMicrotask) != null ? _b : setTimeout : setTimeout;
class q {
constructor(e2, t2, s2) {
this.headers = e2, this.clearPendingBatch = t2, this.sendCalls = s2, this.sent = false, W(() => this.send());
}
send() {
this.sent || (this.sent = true, this.clearPendingBatch(), this.sendCalls());
}
destroy() {
this.sent = true;
}
}
class L extends q {
constructor(e2, t2, s2) {
super(t2, s2, () => {
this.sendSubscribe(), this.sendGet();
}), this.connection = e2, this.getCalls = [], this.subscribeCalls = [];
}
canPush(e2) {
return L.isCorrectBatchTypeFor(e2) && $(this.headers, e2.headers);
}
static isCorrectBatchTypeFor(e2) {
const t2 = i(e2.path, ["users", n]), s2 = "GET" === e2.method || "SUBSCRIBE" === e2.method;
return t2 && s2;
}
push(e2) {
const t2 = e2.path[1], s2 = g();
return "GET" === e2.method ? this.getCalls.push({ userId: t2, deferred: s2 }) : this.subscribeCalls.push({ userId: t2, deferred: s2 }), 1e3 !== this.getCalls.length && 1e3 !== this.subscribeCalls.length || this.send(), s2.promise;
}
sendGet() {
return __async(this, null, function* () {
if (0 === this.getCalls.length) return;
const e2 = [...new Set(this.getCalls.map((e3) => e3.userId))], t2 = yield this.connection.call({ method: "GET", path: ["users"], data: { ids: e2, includePrivateFields: false }, headers: this.headers });
if (t2.ok) for (const e3 of this.getCalls) {
const s2 = t2.value.data[e3.userId];
s2 ? e3.deferred.ok({ status: 200, data: s2 }) : e3.deferred.serverErr({ status: 404, errorCode: "NOT_FOUND", reasons: ["No user with that ID exists"] });
}
else this.getCalls.forEach((e3) => e3.deferred.resolve(t2));
});
}
sendSubscribe() {
if (0 === this.subscribeCalls.length) return;
const e2 = [...new Set(this.subscribeCalls.map((e3) => e3.userId))];
this.connection.call({ method: "SUBSCRIBE", path: ["users"], data: { ids: e2 }, headers: this.headers }).then((e3) => this.subscribeCalls.forEach((t2) => t2.deferred.resolve(e3)));
}
}
class B extends q {
constructor(e2, t2, s2, n2) {
super(s2, n2, () => this.sendMutate()), this.conversationId = e2, this.connection = t2, this.calls = [];
}
canPush(e2) {
return !(!B.isCorrectBatchTypeFor(e2) || e2.path[1] !== this.conversationId || !$(this.headers, e2.headers));
}
static isCorrectBatchTypeFor(e2) {
if (i(e2.path, ["conversations", t, "participants", n])) {
if ("PUT" === e2.method || "POST" === e2.method || "PATCH" === e2.method) return true;
}
return false;
}
push(e2) {
const t2 = e2.path[3], s2 = g();
return this.calls.push({ action: { id: t2, method: e2.method, params: e2.data }, deferred: s2 }), 100 === this.calls.length && this.send(), s2.promise;
}
sendMutate() {
return __async(this, null, function* () {
const e2 = this.calls.map((e3) => e3.action), t2 = yield this.connection.call({ method: "POST", path: ["conversations", this.conversationId, "participants"], data: { actions: e2 }, headers: this.headers });
if (!t2.ok) return void this.calls.forEach((e3) => e3.deferred.resolve(t2));
const s2 = t2.value.data.responses;
for (let e3 = 0; e3 < s2.length; e3++) {
const t3 = this.calls[e3].deferred, n2 = s2[e3];
200 === n2.status ? t3.ok(__spreadProps(__spreadValues({}, n2), { data: {} })) : t3.serverErr(n2);
}
});
}
}
class G {
constructor(e2, t2, s2) {
this.pendingBatch = null, this.connection = new _(e2, t2, s2);
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
return __async(this, null, function* () {
var _a2;
if ((_a2 = this.pendingBatch) == null ? void 0 : _a2.canPush(e2)) return this.pendingBatch.push(e2);
this.pendingBatch && this.pendingBatch.send();
const t2 = this.createEmptyBatchFor(e2);
return t2 ? (this.pendingBatch = t2, t2.push(e2)) : this.connection.call(e2);
});
}
destroy() {
var _a2;
this.connection.destroy(), (_a2 = this.pendingBatch) == null ? void 0 : _a2.destroy();
}
isConnected() {
return this.connection.isConnected();
}
createEmptyBatchFor(e2) {
var _a2, _b2;
if (L.isCorrectBatchTypeFor(e2)) return new L(this.connection, (_a2 = e2.headers) != null ? _a2 : {}, () => this.pendingBatch = null);
if (B.isCorrectBatchTypeFor(e2)) {
const t2 = e2.path[1];
return new B(t2, this.connection, (_b2 = e2.headers) != null ? _b2 : {}, () => this.pendingBatch = null);
}
return null;
}
}
const F = { 200: "RESOLVE", 400: "RESOLVE", 401: "RETRY", 402: "RESOLVE", 403: "RESOLVE", 404: "RESOLVE", 405: "RESOLVE", 409: "RESOLVE", 429: "DELAY", 500: "DELAY" };
class H {
constructor(e2, t2, s2) {
this.throttler = new z(), this.alive = true, this.connection = new G(e2, t2, s2);
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
return __async(this, null, function* () {
let t2 = 0;
for (; this.alive; ) {
const s2 = yield this.connection.call(e2);
if ((s2.ok || "client" !== s2.where || "SOCKET_NOT_READY" !== s2.value) && (s2.ok || "server" !== s2.where || 500 !== s2.value.status) || t2++, 10 === t2) return s2;
if (s2.ok || "client" !== s2.where) {
const e3 = s2.value, t3 = e3.status, n2 = F[t3];
if ("RESOLVE" === n2) return this.throttler.resetDelay(), s2;
if ("RETRY" === n2) continue;
if ("DELAY" === n2) {
yield this.throttler.wait();
continue;
}
return console.warn("[TalkJS] Unexpected status code", t3), e3;
}
if ("SESSION_DESTROYED" === s2.value) return f("SESSION_DESTROYED");
"WEBSOCKET_DISCONNECTED" !== s2.value && ("SOCKET_NOT_READY" !== s2.value ? s2.value : yield this.throttler.wait());
}
return f("SESSION_DESTROYED");
});
}
destroy() {
this.alive = false, this.connection.destroy();
}
isConnected() {
return this.connection.isConnected();
}
}
class z {
constructor() {
this.initialDelayMs = 200, this.exponentialFactor = 1.2, this.maxDelayMs = 3e4, this.currentDelayMs = this.initialDelayMs, this.lastCall = 0;
}
getCurrentDelay() {
return this.currentDelayMs;
}
wait() {
const e2 = (/* @__PURE__ */ new Date()).getTime(), t2 = c(this.currentDelayMs, 0.05), s2 = this.lastCall + t2, n2 = Math.max(0, s2 - e2);
return this.lastCall = e2 + n2, this.currentDelayMs = Math.min(t2 * this.exponentialFactor, this.maxDelayMs), o(n2);
}
resetDelay() {
this.currentDelayMs = this.initialDelayMs;
}
}
function J(e2) {
return e2.map((e3) => encodeURIComponent(e3)).join();
}
class Y {
constructor() {
this.paths = {};
}
add(e2) {
this.paths[J(e2)] = e2;
}
delete(e2) {
delete this.paths[J(e2)];
}
has(e2) {
return Object.hasOwnProperty.call(this.paths, J(e2));
}
clear() {
this.paths = {};
}
forEach(e2) {
Object.values(this.paths).forEach((t2) => e2(t2));
}
}
class V {
constructor(e2, t2, s2) {
this.handlers = s2, this.targetSubscriptions = new Y(), this.connection = new H(e2, t2, { onUpstreamRestarting: () => this.handlers.onUpstreamRestarting(), onSubscriptionsLost: () => {
this.targetSubscriptions.forEach((e3) => {
this.resubscribe(e3);
}), this.handlers.onResubscribeSent();
}, onReady: () => this.handlers.onReady(), onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
return this.connection.call(e2);
}
subscribe(e2) {
return __async(this, null, function* () {
return this.targetSubscriptions.add(e2), this.connection.call({ method: "SUBSCRIBE", path: e2, data: {}, headers: {} });
});
}
unsubscribe(e2) {
return __async(this, null, function* () {
return this.targetSubscriptions.delete(e2), this.connection.call({ method: "UNSUBSCRIBE", path: e2, data: {}, headers: {} });
});
}
resubscribe(e2) {
return __async(this, null, function* () {
const t2 = yield this.connection.call({ method: "SUBSCRIBE", path: e2, data: {}, headers: {} });
t2.ok || this.handlers.onResubscribeError(e2, t2);
});
}
destroy() {
this.targetSubscriptions.clear(), this.connection.destroy();
}
isConnected() {
return this.connection.isConnected();
}
}
class Q {
constructor(e2, t2, s2) {
this.handlers = s2, this.virtualPathsPerRealSubscription = /* @__PURE__ */ new Map(), this.connection = new V(e2, t2, { onUpstreamRestarting: () => this.handlers.onUpstreamRestarting(), onResubscribeSent: () => this.handlers.onResubscribeSent(), onResubscribeError: (e3, t3) => this.handlers.onResubscribeError(e3, t3), onReady: () => this.handlers.onReady(), onPublish: (e3, t3) => this.handlers.onPublish(e3, t3) });
}
toRealPath(e2) {
return i(e2, ["<filtered>", "me", "conversations", a]) ? ["me", "conversations"] : e2;
}
sync() {
return __async(this, null, function* () {
return this.connection.sync();
});
}
call(e2) {
return this.connection.call(e2);
}
subscribe(e2) {
return __async(this, null, function* () {
const t2 = e2.join("/"), s2 = this.toRealPath(e2), n2 = s2.join("/"), r2 = this.virtualPathsPerRealSubscription.get(n2);
return r2 ? (r2.add(t2), { ok: true, value: { status: 200, data: {} } }) : (this.virtualPathsPerRealSubscription.set(n2, /* @__PURE__ */ new Set([t2])), this.connection.subscribe(s2));
});
}
unsubscribe(e2) {
return __async(this, null, function* () {
const t2 = e2.join("/"), s2 = this.toRealPath(e2), n2 = s2.join("/"), r2 = this.virtualPathsPerRealSubscription.get(n2);
return r2 ? (r2.delete(t2), 0 === r2.size ? (this.virtualPathsPerRealSubscription.delete(n2), this.connection.unsubscribe(s2)) : { ok: true, value: { status: 200, data: {} } }) : { ok: true, value: { status: 200, data: {} } };
});
}
destroy() {
this.virtualPathsPerRealSubscription.clear(), this.connection.destroy();
}
isConnected() {
return this.connection.isConnected();
}
}
class K {
constructor() {
this.prev = Promise.resolve();
}
runExclusive(e2) {
return __async(this, null, function* () {
const t2 = this.prev.then(() => e2());
return this.prev = t2, t2;
});
}
sync() {
return __async(this, null, function* () {
return this.runExclusive(() => {
});
});
}
}
class Z {
constructor(e2) {
this.initialised = false, this.getPointer = void 0, this.pendingStates = [e2], e2.resultPromise.then(() => this.initialised = true);
}
get pendingPointer() {
if (0 !== this.pendingStates.length) return this.pendingStates[this.pendingStates.length - 1];
}
get mostRecentState() {
var _a2;
return (_a2 = this.pendingPointer) != null ? _a2 : this.getPointer;
}
canAppendState(e2) {
var _a2, _b2;
const t2 = (_a2 = this.getPointer) == null ? void 0 : _a2.seq;
if (void 0 !== t2 && e2 <= t2) return false;
const s2 = (_b2 = this.pendingPointer) == null ? void 0 : _b2.seq;
return !(void 0 !== s2 && e2 < s2);
}
set(e2) {
if (!this.canAppendState(e2.seq)) throw "Appending in the past";
this.pendingStates.push(e2);
}
mutate(e2, t2) {
if (!this.initialised) return;
if (!this.canAppendState(e2)) throw "Mutating in the past";
const s2 = this.mostRecentState.resultPromise.then((e3) => e3.ok ? t2(e3) : e3);
this.pendingStates.push({ seq: e2, resultPromise: s2 });
}
get(e2) {
for (; this.pendingStates.length > 0 && (void 0 === this.getPointer || this.pendingStates[0].seq <= e2); ) this.getPointer = this.pendingStates.shift();
return this.getPointer;
}
}
class X extends Z {
constructor(e2, t2) {
super(e2), this.onTeardown = t2, this._error = null, this._lastGoodState = Promise.resolve(void 0), this.registerNewState(e2.resultPromise);
}
get error() {
return this._error;
}
get lastGoodState() {
return this._lastGoodState;
}
mutate(e2, t2) {
super.mutate(e2, t2), this.registerNewState(this.mostRecentState.resultPromise);
}
set(e2) {
super.set(e2), this.registerNewState(this.mostRecentState.resultPromise);
}
registerNewState(e2) {
const t2 = this.lastGoodState;
this._lastGoodState = e2.then((e3) => e3.ok ? e3.value : t2), e2.then((e3) => {
e3.ok || this.setError(e3);
});
}
setError(e2) {
var _a2;
this._error || (this._error = e2, (_a2 = this.onTeardown) == null ? void 0 : _a2.call(this, e2), this.lastGoodState.then((e3) => {
void 0 !== e3 && this.teardownNested(e3);
}));
}
}
class ee extends X {
constructor(e2, t2) {
const s2 = new Promise((e3) => setTimeout(e3)).then(() => this.fetchInitial(e2));
super({ seq: e2, resultPromise: s2 }, t2.onTeardown), this.initialSeq = e2, this.getDeepMutex = new K(), this.lastDeep = void 0;
}
refetchInitial(e2) {
return __async(this, null, function* () {
const t2 = this.mostRecentState.resultPromise, s2 = this.fetchInitial(e2), [n2, r2] = yield Promise.all([t2, s2]);
if (void 0 === n2 || !n2.ok) return r2;
if (!r2.ok) return r2;
return this.equal(n2.value, r2.value) ? n2 : r2;
});
}
refetch(e2) {
if (null !== this.error) return;
const t2 = { seq: e2, resultPromise: this.refetchInitial(e2) };
this.set(t2);
}
changedBetween(e2, t2) {
return __async(this, null, function* () {
if (e2 >= t2) return false;
const s2 = this.get(t2), n2 = yield s2.resultPromise;
if (!n2.ok) return false;
if (n2.value.lastChanged > Math.max(this.initialSeq, e2) && n2.value.lastChanged <= t2) return true;
return yield this.anyChildChanged(e2, t2, n2.value);
});
}
getDeep(e2) {
return __async(this, null, function* () {
return this.getDeepMutex.runExclusive(() => __async(this, null, function* () {
var _a2;
if (null !== this.error) return this.error;
const t2 = (_a2 = this.lastDeep) == null ? void 0 : _a2.seq;
if (e2 === t2) return this.lastDeep.deep;
if (void 0 !== t2) {
if (e2 < t2) throw `Trying to load seq ${e2} when we have previously loaded seq ${t2}`;
if (!(yield this.changedBetween(t2, e2))) return this.lastDeep.seq = e2, this.lastDeep.deep;
}
const s2 = this.get(e2).resultPromise, n2 = s2.then((t3) => t3.ok ? this.loadNested(e2, t3.value) : t3);
this.lastDeep = { seq: e2, shallow: s2, deep: n2 };
const r2 = yield n2;
return null !== this.error ? this.error : (r2.ok || this.setError(r2), r2);
}));
});
}
}
class te extends ee {
constructor(e2, t2, s2) {
super(e2, s2), this.emitMutex = t2, this.externallyIdleTimer = new se(), this.externallyIdle = true, this.internallyIdleTimer = new se(), this.internallyIdle = true, this.referencedByOtherStores = 0, this.listeners = [], this.lastEmitSeq = void 0, this.lastEmitResult = void 0, t2.runExclusive(() => __async(this, null, function* () {
yield this.emit(e2);
}));
}
registerInternalSubscription() {
this.internallyIdleTimer.stop(), this.internallyIdle = false, this.referencedByOtherStores++;
let e2 = true;
return () => {
e2 && (e2 = false, this.referencedByOtherStores--, 0 === this.referencedByOtherStores && this.internallyIdleTimer.restart(() => {
this.internallyIdle = true, this.tryFullyUnsubscribe();
}, this.unsubscribeDebounceMs), this.tryFullyUnsubscribe());
};
}
get onlyUsedInternally() {
return 0 === this.listeners.length;
}
listen(e2) {
this.externallyIdleTimer.stop(), this.externallyIdle = false, this.listeners.push(e2), void 0 !== this.lastEmitResult && e2(this.lastEmitResult);
let t2 = true;
return () => {
t2 && (t2 = false, this.listeners = this.listeners.filter((t3) => t3 !== e2), 0 === this.listeners.length && this.externallyIdleTimer.restart(() => {
this.externallyIdle = true, this.tryFullyUnsubscribe();
}, this.unsubscribeDebounceMs));
};
}
tryFullyUnsubscribe() {
this.externallyIdle && this.internallyIdle && this.setError(f("UNSUBSCRIBED"));
}
emit(e2) {
return __async(this, null, function* () {
var _a2;
if (this.lastEmitSeq && this.lastEmitSeq >= e2) return;
if (false === ((_a2 = this.lastEmitResult) == null ? void 0 : _a2.ok)) return;
this.lastEmitSeq = e2;
const t2 = yield this.getDeep(e2);
t2 !== this.lastEmitResult && (this.lastEmitResult = t2, this.listeners.forEach((e3) => e3(t2)));
});
}
}
class se {
constructor() {
this.timerId = void 0;
}
restart(e2, t2) {
void 0 !== this.timerId && clearTimeout(this.timerId), this.timerId = setTimeout(() => e2(), t2);
}
stop() {
clearTimeout(this.timerId);
}
}
var ne, re = {};
!(function() {
if (ne) return re;
function e2(e3) {
return String.fromCharCode(parseInt(e3.slice(1), 16));
}
function t2(e3) {
return `%${`00${e3.charCodeAt(0).toString(16)}`.slice(-2)}`;
}
ne = 1, Object.defineProperty(re, "__esModule", { value: true }), re.encode = function(t3) {
return btoa(encodeURIComponent(t3).replace(/%[0-9A-F]{2}/g, e2));
}, re.decode = function(e3) {
return decodeURIComponent(Array.from(atob(e3), t2).join(""));
};
})();
function ae(e2, t2) {
const s2 = t2.lastIndex;
let n2;
const r2 = [];
for (; null !== (n2 = t2.exec(e2)); ) r2.push(n2), "" === n2[0] && (t2.lastIndex += 1);
return t2.lastIndex = s2, r2;
}
function ie(e2) {
const t2 = e2.replace(/%2F/g, "/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/, "$1"), s2 = decodeURIComponent(t2);
if (/%[0-9A-Fa-f]{2}/.test(s2)) try {
return decodeURIComponent(s2.replace(/\+/g, "%20"));
} catch (e3) {
return s2;
}
return s2;
}
function oe(e2, t2) {
if (!e2() && !t2) {
t2 = e2.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/, "`$1`") + " was not true";
}
}
((e2) => {
function t2(e3) {
}
function s2(e3, t3) {
(function(e4, t4) {
switch (t4) {
case "undefined":
return void 0 === e4;
case String:
return "string" == typeof e4 || e4 instanceof String;
case Boolean:
return "boolean" == typeof e4 || e4 instanceof Boolean;
case Number:
return "number" == typeof e4 || e4 instanceof Number;
default:
return e4 instanceof t4;
}
})(e3, t3) || (t3.name, String(e3));
}
e2.defined = t2, e2.has = function(e3, t3) {
e3[t3];
}, e2.is = s2, e2.equals = function(e3, t3) {
}, e2.oneOf = function(e3, t3) {
t3.includes(e3) || JSON.stringify(t3);
}, e2.isArray = function(e3, t3) {
s2(e3, Array), e3 && e3.length > 0 && s2(e3[0], t3);
}, e2.optional = function(e3, t3) {
void 0 !== e3 && s2(e3, t3);
}, e2.falsy = function(e3) {
}, e2.never = function(e3) {
};
})(oe || (oe = {}));
const ce = oe, le = /^\/.*[^\\]\/[im]*$/;
function ue(e2) {
if (!le.test(e2)) return false;
return !he(e2).test("");
}
function he(e2) {
const t2 = e2.match(/^\/(.*[^\\])\/(.*)$/);
if (!t2) throw new Error(`Expected ${e2} to be a (non-empty) regex`);
let s2 = t2[2] || "";
return s2 = s2.replace(/[^im]/g, "") + "g", new RegExp(t2[1], s2);
}
class de {
constructor({ mode: e2, allowedHostnames: t2, allowedPhoneNrs: s2, allowedMatches: n2, forbiddenMatches: r2, forbiddenWords: a2, suppressLinks: i2, suppressEmailAddresses: o2, suppressPhoneNumbers: c2, replacement: l2 }) {
if (ce.oneOf(e2, ["all", "otherOnly", "off"]), this.mode = e2, this.suppressLinks = false !== i2, this.suppressEmailAddresses = false !== o2, this.suppressPhoneNumbers = false !== c2, this.allowedHostnames = t2 || [], this.allowedPhoneNrs = (s2 || []).filter((e3) => e3).map((e3) => e3.replace(/[^0-9]/g, "")), this.allowedMatches = (n2 || []).filter(ue).map((e3) => he(e3)), this.forbiddenMatches = (r2 || []).filter(ue).map((e3) => he(e3)), a2) {
const e3 = a2.split("\n").map((e4) => e4.trim().toLowerCase()).filter((e4) => e4.length > 0 && !e4.startsWith("#")).map((e4) => e4.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"));
e3.length && this.forbiddenMatches.push(new RegExp(`\\b(${e3.join("|")})\\b`, "gi"));
}
ce(() => this.allowedMatches.every((e3) => e3.flags.includes("g")), "All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"), ce(() => this.forbiddenMatches.every((e3) => e3.flags.includes("g")), "All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"), l2 = l2 == null ? void 0 : l2.trim(), this.replacement = l2 && l2.length > 0 ? l2 : void 0;
}
shouldSuppress({ isContentBySender: e2 }) {
return "all" === this.mode || "otherOnly" === this.mode && !e2;
}
}
function pe(e2, t2) {
const s2 = e2.map((e3) => (function(e4, t3) {
if ("text" === e4.type) return (function(e5, t4) {
const s3 = (function(e6) {
var _a2, _b2, _c, _d, _e3, _f, _g, _h, _i, _j, _k, _l, _m, _n2;
let t5 = "";
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 : [], highlightFromWordBeginnings: (_g = e6.highlightFromWordBeginnings) != null ? _g : false, contactInfo: (_h = e6.contactInfo) != null ? _h : false, suppression: (_i = e6.suppression) != null ? _i : new de({ mode: "off" }), contactInfoHiddenText: (_l = (_k = e6.contactInfoHiddenText) != null ? _k : (_j = e6.suppression) == null ? void 0 : _j.replacement) != null ? _l : t5, customEmojiUrls: (_m = e6.customEmojiUrls) != null ? _m : {}, enableActions: (_n2 = e6.enableActions) != null ? _n2 : true };
})(t4);
return fe(e5, s3);
})(e4.children, t3);
if ("file" === e4.type && "video" === e4.subtype) return `🎥 ${ie(e4.url)}`;
if ("file" === e4.type && "image" === e4.subtype) return `📷 ${ie(e4.url)}`;
if ("file" === e4.type && "audio" === e4.subtype) return `🎧 ${ie(e4.url)}`;
if ("file" === e4.type && "voice" === e4.subtype) {
const t4 = e4.duration;
if (void 0 === t4) return "🎙️";
return `🎙️ (${Math.floor(t4 / 60)}:${Math.floor(t4 % 60).toString().padStart(2, "0")})`;
}
if ("file" === e4.type) return e4.subtype, `📎 ${ie(e4.url)}`;
if ("location" === e4.type) return "📍";
return "";
})(e3, t2));
return s2.join("\n\n");
}
function fe(e2, t2) {
return e2.flatMap((e3) => {
if ("string" == typeof e3) return e3;
switch (e3.type) {
case "blockquote":
case "bold":
case "italic":
case "strikethrough":
case "link":
case "actionlink":
case "actionLink":
case "actionbutton":
case "actionButton":
return fe(e3.children, t2);
case "bulletlist":
case "bulletList":
return "\n" + fe(e3.children, t2);
case "bulletpoint":
case "bulletPoint":
return "- " + fe(e3.children, t2) + "\n";
case "autolink":
case "autoLink":
case "codeblock":
case "codeBlock":
case "codespan":
case "codeSpan":
case "emoji":
case "customemoji":
case "customEmoji":
return e3.text;
case "suppressed":
return t2.contactInfoHiddenText;
case "mention":
return `@${e3.text}`;
}
}).join("");
}
function me(e2) {
return N({ id: e2.id, name: e2.name, custom: N(e2.custom), locale: e2.locale, photoUrl: e2.photoUrl, role: e2.role, welcomeMessage: e2.welcomeMessage });
}
function ge(e2, t2) {
return N({ user: t2, access: e2.access, notify: e2.notify, joinedAt: e2.joinedAt });
}
function ve(e2) {
const t2 = Object.entries(e2);
t2.sort(([e3, t3], [s2, n2]) => {
const r2 = t3.createdAt - n2.createdAt;
return 0 !== r2 ? r2 : e3.localeCompare(s2);
});
return N(t2.map(([e3, t3]) => ({ emoji: e3, count: t3.count, currentUserReacted: t3.currentUserReacted })));
}
class ye extends te {
constructor(e2, t2, s2, n2, r2) {
super(e2, n2, r2), this.userId = t2, this.realtimeClient = s2, this.unsubscribeDebounceMs = 3e4;
}
fetchInitial(e2) {
return __async(this, null, function* () {
const t2 = yield this.realtimeClient.call({ method: "GET", path: ["users", this.userId], data: { includePrivateFields: false }, flags: { bypassCache: true } });
return t2.ok ? p({ snapshot: me(t2.value.data), lastChanged: e2 }) : "server" === t2.where && 404 === t2.value.status ? p({ snapshot: null, lastChanged: e2 }) : t2;
});
}
equal(e2, t2) {
return $(e2.snapshot, t2.snapshot);
}
loadNested(e2, t2) {
return __async(this, null, function* () {
return p(t2);
});
}
userCreated(e2, t2) {
this.mutate(e2, (s2) => null !== s2.value.snapshot ? s2 : p({ snapshot: me(t2.state), lastChanged: e2 }));
}