@cometchat/chat-uikit-react
Version:
Ready-to-use Chat UI Components for React
880 lines (874 loc) • 28.6 kB
JavaScript
import './index.css';
import { formatDateWithConfig } from './chunk-PJV2HJD5.js';
import { translationResources } from './chunk-ERWUU2OZ.js';
import { __require } from './chunk-WZOKFQUZ.js';
import { CometChat } from '@cometchat/chat-sdk-javascript';
import { useState, useEffect } from 'react';
var UIKitSettings = class _UIKitSettings {
/**
* Private constructor to initialize the settings using the provided builder.
* @param {UIKitSettingsBuilder} builder - The builder instance containing the settings configuration.
*/
constructor(builder) {
this.appId = builder.appId ?? "";
this.region = builder.region ?? "";
this.subscriptionType = builder.subscriptionType ?? "ALL_USERS";
this.roles = builder.roles ?? [];
this.autoEstablishSocketConnection = builder.autoEstablishSocketConnection ?? true;
this.authKey = builder.authKey;
this.adminHost = builder.adminHost;
this.clientHost = builder.clientHost;
this.storageMode = builder.storageMode ?? CometChat.StorageMode.LOCAL;
this.callingEnabled = builder.callingEnabled ?? false;
this.callAppSettings = builder.callAppSettings;
}
/**
* Creates an instance of UIKitSettings from the provided builder.
* @param {UIKitSettingsBuilder} builder - The builder instance containing the settings configuration.
* @returns {UIKitSettings} A new instance of UIKitSettings.
*/
static fromBuilder(builder) {
return new _UIKitSettings(builder);
}
/**
* Retrieves the app ID.
* @returns {string} The unique ID of the app.
*/
getAppId() {
return this.appId;
}
/**
* Retrieves the region.
* @returns {string} The region of the app.
*/
getRegion() {
return this.region;
}
/**
* Retrieves the subscription type for presence.
* @returns {CometChatPresenceSubscription} The subscription type.
*/
getSubscriptionType() {
return this.subscriptionType;
}
/**
* Retrieves the roles for presence subscription.
* @returns {string[]} The list of roles subscribed to presence.
*/
getRoles() {
return this.roles;
}
/**
* Checks if auto-establish socket connection is enabled.
* @returns {boolean} True if auto-establish is enabled, otherwise false.
*/
isAutoEstablishSocketConnection() {
return this.autoEstablishSocketConnection;
}
/**
* Retrieves the authentication key.
* @returns {string | undefined} The authentication key.
*/
getAuthKey() {
return this.authKey;
}
/**
* Retrieves the custom admin host URL.
* @returns {string | undefined} The admin host URL.
*/
getAdminHost() {
return this.adminHost;
}
/**
* Retrieves the custom client host URL.
* @returns {string | undefined} The client host URL.
*/
getClientHost() {
return this.clientHost;
}
/**
* Retrieves the storage mode.
* @returns {CometChat.StorageMode} The storage mode.
*/
getStorageMode() {
return this.storageMode;
}
/**
* Checks if calling functionality is enabled.
* @returns {boolean} True if calling is enabled, otherwise false.
*/
isCallingEnabled() {
return this.callingEnabled;
}
/**
* Retrieves the custom CallAppSettings for Calls SDK initialization.
* @returns {any | undefined} The custom CallAppSettings, or undefined if not set.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getCallAppSettings() {
return this.callAppSettings;
}
};
var UIKitSettingsBuilder = class {
/**
* Builds and returns an instance of UIKitSettings.
* @returns {UIKitSettings} A new instance of UIKitSettings with the specified configuration.
*/
build() {
return UIKitSettings.fromBuilder(this);
}
/**
* Sets the app ID.
* @param {string} appId - The unique ID of the app.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setAppId(appId) {
this.appId = appId;
return this;
}
/**
* Sets the region.
* @param {string} region - The region of the app.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setRegion(region) {
this.region = region;
return this;
}
/**
* Sets the authentication key.
* @param {string} authKey - The authentication key.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setAuthKey(authKey) {
this.authKey = authKey;
return this;
}
/**
* Subscribes to presence updates for all users.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
subscribePresenceForAllUsers() {
this.subscriptionType = "ALL_USERS";
return this;
}
/**
* Subscribes to presence updates for friends.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
subscribePresenceForFriends() {
this.subscriptionType = "FRIENDS";
return this;
}
/**
* Subscribes to presence updates for specific roles.
* @param {string[]} roles - The roles to subscribe to.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
subscribePresenceForRoles(roles) {
this.subscriptionType = "ROLES";
this.roles = roles;
return this;
}
/**
* Sets the roles for presence subscription.
* @param {string[]} roles - The roles to subscribe to.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setRoles(roles) {
this.roles = roles;
return this;
}
/**
* Enables or disables the auto-establish socket connection.
* @param {boolean} value - True to enable, false to disable.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setAutoEstablishSocketConnection(value) {
this.autoEstablishSocketConnection = value;
return this;
}
/**
* Sets the custom admin host URL.
* @param {string} host - The admin host URL.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setAdminHost(host) {
this.adminHost = host;
return this;
}
/**
* Sets the custom client host URL.
* @param {string} host - The client host URL.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setClientHost(host) {
this.clientHost = host;
return this;
}
/**
* Sets the storage mode.
* @param {CometChat.StorageMode} mode - The storage mode.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setStorageMode(mode) {
this.storageMode = mode;
return this;
}
/**
* Enables or disables calling functionality.
* @param {boolean} enabled - True to enable, false to disable.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
setCallingEnabled(enabled) {
this.callingEnabled = enabled;
return this;
}
/**
* Sets custom CallAppSettings for Calls SDK initialization.
* If not set, the UIKit builds default settings from appId and region.
*
* @example
* ```typescript
* new UIKitSettingsBuilder()
* .setCallingEnabled(true)
* .setCallAppSettings({ appId: 'APP_ID', region: 'us' })
* .build();
* ```
*
* @param {any} callAppSettings - The CallAppSettings object.
* @returns {UIKitSettingsBuilder} The builder instance.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setCallAppSettings(callAppSettings) {
this.callAppSettings = callAppSettings;
return this;
}
};
// src/CometChatUIKit/CometChatCalls.ts
var CometChatUIKitCalls = null;
try {
const callsModule = __require("@cometchat/calls-sdk-javascript");
CometChatUIKitCalls = callsModule?.CometChatCalls ?? callsModule?.default?.CometChatCalls ?? callsModule?.default ?? null;
} catch {
}
async function loadCallsSDK() {
if (CometChatUIKitCalls) return CometChatUIKitCalls;
try {
const mod = await import('@cometchat/calls-sdk-javascript');
const sdk = mod?.CometChatCalls ?? mod?.default?.CometChatCalls ?? mod?.default ?? null;
if (sdk) {
CometChatUIKitCalls = sdk;
}
return CometChatUIKitCalls;
} catch {
return null;
}
}
function initCallsSDK(sdk) {
if (sdk) {
CometChatUIKitCalls = sdk;
}
}
// src/resources/CometChatLocalize/CometChatLocalize.ts
var DEFAULT_LNG = "en-us";
var _CometChatLocalize = class _CometChatLocalize {
constructor(options = {}) {
this.setLanguageCallback = () => {
};
this.disableDateTimeLocalization = false;
this.disableAutoDetection = false;
this.t = (key) => key;
this.currentLanguage = (options.language ?? DEFAULT_LNG).toLowerCase();
this.fallbackLanguage = (options.fallbackLanguage ?? DEFAULT_LNG).toLowerCase();
this.translations = {};
for (const [lang, namespaces] of Object.entries(translationResources)) {
this.translations[lang] = namespaces.translation ?? {};
}
if (options.translationsForLanguage) {
const existing = this.translations[this.currentLanguage] ?? {};
this.translations[this.currentLanguage] = { ...existing, ...options.translationsForLanguage };
}
this.t = this.createTranslateFunction();
this.tDateTimeParser = (input) => input ? new Date(input) : /* @__PURE__ */ new Date();
}
/**
* Returns the shared CometChatLocalize instance (set by LocaleProvider on mount).
* Use this in non-React code (plugins, utilities) to access `getLocalizedString()` without a hook.
*/
static getSharedInstance() {
return _CometChatLocalize._sharedInstance;
}
/**
* Called by LocaleProvider to register the active instance for static access.
*/
static setSharedInstance(instance) {
_CometChatLocalize._sharedInstance = instance;
}
/**
* Creates the translate function bound to the current language and fallback settings.
*/
createTranslateFunction() {
return (key) => {
const result = this.translations[this.currentLanguage]?.[key] ?? this.translations[this.fallbackLanguage]?.[key];
if (result !== void 0) {
return result;
}
if (this.missingKeyHandler) {
const handlerResult = this.missingKeyHandler(key);
if (typeof handlerResult === "string") {
return handlerResult;
}
}
return key;
};
}
init(settings = {}) {
if (settings.fallbackLanguage !== void 0) {
this.fallbackLanguage = settings.fallbackLanguage.toLowerCase();
}
if (settings.translationsForLanguage !== void 0) {
this.addTranslation(settings.translationsForLanguage);
}
if (settings.timezone !== void 0) {
this.timezone = settings.timezone;
}
if (settings.calendarObject !== void 0) {
this.calendarObject = settings.calendarObject;
}
if (settings.disableAutoDetection !== void 0) {
this.disableAutoDetection = settings.disableAutoDetection;
}
if (settings.disableDateTimeLocalization !== void 0) {
this.disableDateTimeLocalization = settings.disableDateTimeLocalization;
}
if (settings.missingKeyHandler !== void 0) {
this.missingKeyHandler = settings.missingKeyHandler;
}
this.t = this.createTranslateFunction();
if (settings.language !== void 0) {
this.setCurrentLanguage(settings.language);
}
}
getTranslators() {
return { t: this.t, tDateTimeParser: this.tDateTimeParser };
}
/**
* Adds translations for one or more languages. Existing keys are overwritten.
*/
addTranslation(resources) {
for (const [language, translations] of Object.entries(resources)) {
const lang = language.toLowerCase();
if (!this.translations[lang]) {
this.translations[lang] = translations;
} else {
this.translations[lang] = { ...this.translations[lang], ...translations };
}
}
}
/**
* Sets the active language and recreates the getLocalizedString() function.
*/
setCurrentLanguage(language) {
this.currentLanguage = language.toLowerCase();
this.t = this.createTranslateFunction();
this.setLanguageCallback(this.t);
}
/**
* Returns the currently active language code.
*/
getCurrentLanguage() {
return this.currentLanguage;
}
registerSetLanguageCallback(callback) {
this.setLanguageCallback = callback;
}
// --- Date/time configuration getters ---
/**
* Returns the configured IANA timezone string, or undefined if not set.
*/
getTimezone() {
return this.timezone;
}
/**
* Returns the locale language for date formatting.
* Returns "en-US" when disableDateTimeLocalization is true, otherwise the current language.
*/
getDateLocaleLanguage() {
if (this.disableDateTimeLocalization) {
return "en-US";
}
return this.currentLanguage;
}
/**
* Returns the stored calendar object configuration, or undefined if not set.
*/
getCalendarObject() {
return this.calendarObject;
}
/**
* Formats a Unix timestamp (seconds) using a CometChatDateFormatConfig.
*
* When a calendarObject argument is provided, uses it directly.
* When not provided, falls back to the globally configured calendarObject from init().
* If neither is available, uses a sensible default config.
*/
formatDate(timestamp, calendarObject) {
const config = calendarObject ?? this.calendarObject ?? {
today: "Today",
yesterday: "Yesterday",
lastWeek: "dddd",
otherDays: "DD MMM, YYYY"
};
return formatDateWithConfig(timestamp, config, {
timezone: this.timezone,
locale: this.getDateLocaleLanguage()
});
}
getBrowserLanguage() {
if (typeof window === "undefined") return this.fallbackLanguage;
const languages = window.navigator.languages?.length ? window.navigator.languages : [window.navigator.language];
for (const lang of languages) {
const normalized = lang.toLowerCase();
if (this.translations[normalized]) {
return normalized;
}
const baseLang = normalized.split("-")[0];
if (baseLang && this.translations[baseLang]) {
return baseLang;
}
}
return this.fallbackLanguage;
}
getLocalizedString(key) {
return this.t(key);
}
getDefaultLanguage() {
if (this.disableAutoDetection) {
return this.fallbackLanguage;
}
return this.getBrowserLanguage();
}
};
_CometChatLocalize._sharedInstance = null;
var CometChatLocalize = _CometChatLocalize;
// src/context/CometChatEvents.types.ts
var CometChatMessageStatus = /* @__PURE__ */ ((CometChatMessageStatus2) => {
CometChatMessageStatus2["inprogress"] = "inprogress";
CometChatMessageStatus2["success"] = "success";
CometChatMessageStatus2["error"] = "error";
CometChatMessageStatus2["cancelled"] = "cancelled";
return CometChatMessageStatus2;
})(CometChatMessageStatus || {});
var _CometChatUIKit = class _CometChatUIKit {
// --- Emit bridge (static ↔ React context) ---
/**
* Register the emit function from CometChatEventsProvider.
* Called internally by the provider on mount/unmount.
*/
static _setEmit(fn) {
_CometChatUIKit._emit = fn;
}
// --- Getters ---
/** Returns the UIKit settings used during initialization. */
static getSettings() {
return _CometChatUIKit._settings;
}
/** Returns the currently logged-in user (synchronous). */
static getLoggedInUser() {
return _CometChatUIKit._loggedInUser;
}
/** Returns whether the SDK has been initialized. */
static isInitialized() {
return _CometChatUIKit._initialized;
}
/** Returns whether the Calls SDK is ready. */
static isCallingReady() {
return _CometChatUIKit._callingReady;
}
/** Returns the conversation update settings fetched from the dashboard. */
static getConversationUpdateSettings() {
return _CometChatUIKit._conversationUpdateSettings;
}
// --- Initialization ---
/**
* Initialize the CometChat SDK and UIKit.
*
* This:
* 1. Validates settings
* 2. Builds AppSettings from UIKitSettings
* 3. Calls CometChat.init()
* 4. Sets source metadata for analytics
* 5. Sets up plugin registry
* 6. Resumes existing session (if any)
* 7. Initializes Calls SDK (if enabled)
*/
static async init(settings) {
_CometChatUIKit._settings = settings;
_CometChatUIKit._callsInitSettings = null;
const appSettingsBuilder = new CometChat.AppSettingsBuilder();
if (settings.getRoles().length > 0) {
appSettingsBuilder.subscribePresenceForRoles(settings.getRoles());
} else if (settings.getSubscriptionType() === "ALL_USERS") {
appSettingsBuilder.subscribePresenceForAllUsers();
} else if (settings.getSubscriptionType() === "FRIENDS") {
appSettingsBuilder.subscribePresenceForFriends();
}
appSettingsBuilder.autoEstablishSocketConnection(settings.isAutoEstablishSocketConnection());
appSettingsBuilder.setRegion(settings.getRegion());
const adminHost = settings.getAdminHost();
if (adminHost) {
appSettingsBuilder.overrideAdminHost(adminHost);
}
const clientHost = settings.getClientHost();
if (clientHost) {
appSettingsBuilder.overrideClientHost(clientHost);
}
appSettingsBuilder.setStorageMode(settings.getStorageMode());
const appSettings = appSettingsBuilder.build();
if (typeof CometChat.setSource === "function") {
CometChat.setSource("uikit-v7", "web", "reactjs");
}
if (typeof window !== "undefined") {
window.CometChatUiKit = {
name: "@cometchat/chat-uikit-react",
version: "7.1.0"
};
}
await CometChat.init(settings.getAppId(), appSettings);
_CometChatUIKit._initialized = true;
if (!CometChatLocalize.getSharedInstance()) {
const localize = new CometChatLocalize();
localize.init();
CometChatLocalize.setSharedInstance(localize);
}
try {
const existingUser = await CometChat.getLoggedinUser();
if (existingUser) {
_CometChatUIKit._loggedInUser = existingUser;
await _CometChatUIKit._postLogin();
}
} catch {
}
return _CometChatUIKit._loggedInUser;
}
/**
* @internal
* File-based init for AI agent skills.
* Calls CometChat.initFromSettings(settings) which sets
* integrationSource = "ai-agent" in persistent storage.
*
* This method is completely independent of init() — new→new, old→old.
* Regular init(uikitSettings) does NOT set the integrationSource flag.
*/
static initFromSettings(settings) {
const credentials = settings.credentials;
const authKey = credentials?.authKey;
const uiKitConfig = settings.uiKit;
const callingEnabled = !!uiKitConfig?.callsSDK;
_CometChatUIKit._callsInitSettings = settings;
const builder = new UIKitSettingsBuilder().setAppId(settings.appId).setRegion(settings.region);
if (authKey) builder.setAuthKey(authKey);
if (callingEnabled) builder.setCallingEnabled(true);
_CometChatUIKit._settings = builder.build();
if (CometChat.setSource) {
CometChat.setSource("uikit-v7", "web", "reactjs");
}
return new Promise((resolve, reject) => {
if (typeof window !== "undefined") {
window.CometChatUiKit = {
name: "@cometchat/chat-uikit-react",
version: "7.1.0"
};
}
CometChat.initFromSettings(settings).then(() => {
_CometChatUIKit._initialized = true;
if (!CometChatLocalize.getSharedInstance()) {
const localize = new CometChatLocalize();
localize.init();
CometChatLocalize.setSharedInstance(localize);
}
CometChat.getLoggedinUser().then((user) => {
if (user) {
_CometChatUIKit._loggedInUser = user;
void _CometChatUIKit._postLogin();
}
resolve(user);
}).catch((error) => {
console.log(error);
reject(error instanceof Error ? error : new Error(String(error)));
});
}).catch((error) => {
reject(error instanceof Error ? error : new Error(String(error)));
});
});
}
// --- Login ---
/**
* Log in a user by UID.
* Requires authKey to be set in UIKitSettings.
*/
static async login(uid) {
_CometChatUIKit._checkInitialized();
const authKey = _CometChatUIKit._settings?.getAuthKey();
if (!authKey) {
throw new Error("CometChatUIKit.login: authKey is required in UIKitSettings for UID login");
}
const existing = await CometChat.getLoggedinUser();
if (existing) {
_CometChatUIKit._loggedInUser = existing;
await _CometChatUIKit._postLogin();
return existing;
}
const user = await CometChat.login(uid, authKey);
_CometChatUIKit._loggedInUser = user;
await _CometChatUIKit._postLogin();
return user;
}
/**
* Log in a user with an auth token.
*/
static async loginWithAuthToken(authToken) {
_CometChatUIKit._checkInitialized();
const user = await CometChat.login(authToken);
_CometChatUIKit._loggedInUser = user;
await _CometChatUIKit._postLogin();
return user;
}
// --- Logout ---
/**
* Log out the current user.
*/
static async logout() {
await CometChat.logout();
_CometChatUIKit._loggedInUser = null;
_CometChatUIKit._callingReady = false;
if (_CometChatUIKit._loginListenerId) {
CometChat.removeLoginListener(_CometChatUIKit._loginListenerId);
_CometChatUIKit._loginListenerId = null;
}
}
// --- User management ---
/**
* Create a new user.
* Requires authKey in UIKitSettings.
*/
static async createUser(user) {
_CometChatUIKit._checkInitialized();
const authKey = _CometChatUIKit._settings?.getAuthKey();
if (!authKey) {
throw new Error("CometChatUIKit.createUser: authKey is required");
}
return CometChat.createUser(user, authKey);
}
/**
* Update an existing user.
* Requires authKey in UIKitSettings.
*/
static async updateUser(user) {
_CometChatUIKit._checkInitialized();
const authKey = _CometChatUIKit._settings?.getAuthKey();
if (!authKey) {
throw new Error("CometChatUIKit.updateUser: authKey is required");
}
return CometChat.updateUser(user, authKey);
}
// --- Send methods (convenience for non-React usage) ---
/**
* Send a text message with optimistic UI updates.
* Emits 'ui:message/sent' at each stage (inprogress → success/error).
*/
static async sendTextMessage(message) {
_CometChatUIKit._prepareMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "inprogress" /* inprogress */
});
try {
const sent = await CometChat.sendMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message: sent,
status: "success" /* success */
});
return sent;
} catch (error) {
const meta = message.getMetadata() ?? {};
message.setMetadata({ ...meta, error });
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "error" /* error */
});
throw error;
}
}
/**
* Send a media message with optimistic UI updates.
* Emits 'ui:message/sent' at each stage (inprogress → success/error).
*/
static async sendMediaMessage(message) {
_CometChatUIKit._prepareMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "inprogress" /* inprogress */
});
try {
const sent = await CometChat.sendMediaMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message: sent,
status: "success" /* success */
});
return sent;
} catch (error) {
const meta = message.getMetadata() ?? {};
message.setMetadata({ ...meta, error });
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "error" /* error */
});
throw error;
}
}
/**
* Send a custom message with optimistic UI updates.
* Emits 'ui:message/sent' at each stage (inprogress → success/error).
*/
static async sendCustomMessage(message) {
_CometChatUIKit._prepareMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "inprogress" /* inprogress */
});
try {
const sent = await CometChat.sendCustomMessage(message);
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message: sent,
status: "success" /* success */
});
return sent;
} catch (error) {
const meta = message.getMetadata() ?? {};
message.setMetadata({ ...meta, error });
_CometChatUIKit._emit?.({
type: "ui:message/sent",
message,
status: "error" /* error */
});
throw error;
}
}
// --- Private helpers ---
/** Post-login initialization: calls SDK, conversation settings, login listener. */
static async _postLogin() {
try {
_CometChatUIKit._conversationUpdateSettings = await CometChat.getConversationUpdateSettings();
} catch {
}
_CometChatUIKit._attachLoginListener();
if (_CometChatUIKit._settings?.isCallingEnabled()) {
await _CometChatUIKit._initCalling();
}
}
/** Attach SDK login listener to track login/logout from other tabs or direct SDK calls. */
static _attachLoginListener() {
if (_CometChatUIKit._loginListenerId) {
CometChat.removeLoginListener(_CometChatUIKit._loginListenerId);
}
_CometChatUIKit._loginListenerId = `CometChatUIKit_login_${String(Date.now())}`;
CometChat.addLoginListener(
_CometChatUIKit._loginListenerId,
new CometChat.LoginListener({
loginSuccess: (user) => {
_CometChatUIKit._loggedInUser = user;
},
logoutSuccess: () => {
_CometChatUIKit._loggedInUser = null;
_CometChatUIKit._callingReady = false;
}
})
);
}
/** Initialize the Calls SDK. */
static async _initCalling() {
try {
const callsSDK = CometChatUIKitCalls ?? await loadCallsSDK();
if (!callsSDK) return;
const settings = _CometChatUIKit._settings;
const callsInitSettings = _CometChatUIKit._callsInitSettings;
if (callsInitSettings && typeof callsSDK.initFromSettings === "function") {
await callsSDK.initFromSettings(callsInitSettings);
} else {
const callAppSetting = settings?.getCallAppSettings() ?? {
appId: settings?.getAppId(),
region: settings?.getRegion()
};
await callsSDK.init(callAppSetting);
}
const loggedInUser = _CometChatUIKit._loggedInUser;
if (loggedInUser) {
const authToken = loggedInUser.getAuthToken();
if (authToken) {
await callsSDK.loginWithAuthToken(authToken);
}
}
_CometChatUIKit._callingReady = true;
} catch (error) {
console.error("CometChatUIKit: Calls SDK initialization failed:", error);
}
}
/** Prepare a message for sending (set muid, sentAt, sender). */
static _prepareMessage(message) {
if (!message.getMuid()) {
message.setMuid(`_${Math.random().toString(36).slice(2, 12)}`);
}
if (!message.getSentAt()) {
message.setSentAt(Math.floor(Date.now() / 1e3));
}
const senderUid = message.getSender()?.getUid?.();
if (!senderUid && _CometChatUIKit._loggedInUser) {
message.setSender(_CometChatUIKit._loggedInUser);
}
}
/** Throw if not initialized. */
static _checkInitialized() {
if (!_CometChatUIKit._initialized) {
throw new Error("CometChatUIKit: Not initialized. Call CometChatUIKit.init() first.");
}
}
};
// --- Static state ---
_CometChatUIKit._settings = null;
_CometChatUIKit._loggedInUser = null;
_CometChatUIKit._initialized = false;
/** Settings from the initFromSettings() (ai-agent) path; routes the Calls SDK through initFromSettings too. Null on plain init(). */
_CometChatUIKit._callsInitSettings = null;
_CometChatUIKit._callingReady = false;
_CometChatUIKit._loginListenerId = null;
_CometChatUIKit._conversationUpdateSettings = null;
_CometChatUIKit._emit = null;
var CometChatUIKit = _CometChatUIKit;
function useLoggedInUser() {
const [user, setUser] = useState(() => CometChatUIKit.getLoggedInUser());
useEffect(() => {
if (user) return;
let cancelled = false;
void CometChat.getLoggedinUser().then((resolved) => {
if (!cancelled && resolved && typeof resolved.getUid === "function") {
setUser(resolved);
}
}).catch(() => {
});
return () => {
cancelled = true;
};
}, [user]);
return user;
}
export { CometChatLocalize, CometChatMessageStatus, CometChatUIKit, CometChatUIKitCalls, UIKitSettings, UIKitSettingsBuilder, initCallsSDK, loadCallsSDK, useLoggedInUser };