@corva/chat-core 0.1.7 → 0.1.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/dist/index.d.ts CHANGED
@@ -497,10 +497,6 @@ interface TypingEventData {
497
497
  isTyping: boolean;
498
498
  roomId: string;
499
499
  }
500
- interface ReadyServerData {
501
- _id: string;
502
- name?: string;
503
- }
504
500
  interface ReadyChannelData {
505
501
  _id: string;
506
502
  channel_type: string;
@@ -518,7 +514,7 @@ interface RevoltSocketEventHandlers {
518
514
  onAuthenticated?: () => void;
519
515
  onDisconnected?: () => void;
520
516
  onInvalidSession?: () => void;
521
- onReady?: (channels: ReadyChannelData[], channelUnreads?: ChannelUnread[], servers?: ReadyServerData[]) => void;
517
+ onReady?: (channels: ReadyChannelData[], channelUnreads?: ChannelUnread[]) => void;
522
518
  onMessage?: (message: Message) => void;
523
519
  onMessageUpdate?: (messageId: string, channelId: string, data: {
524
520
  content?: string;
@@ -1179,6 +1175,7 @@ interface CorvaRevoltAuthResponse {
1179
1175
  revolt_channel_id: string;
1180
1176
  revolt_channel_server_id?: string;
1181
1177
  revolt_channel_company_id?: number;
1178
+ revolt_channel_joined?: boolean;
1182
1179
  revolt_chat_channels?: AssetChatChannel[];
1183
1180
  chat_used?: boolean | null;
1184
1181
  }
@@ -1250,8 +1247,11 @@ interface AssetChatSession {
1250
1247
  channelId: string;
1251
1248
  serverId: string | null;
1252
1249
  companyId: number | null;
1250
+ joined: boolean;
1253
1251
  }
1254
- declare function getAssetChatSession(assetId: string, assetType: ChatAssetType): Promise<AssetChatSession>;
1252
+ declare function getAssetChatSession(assetId: string, assetType: ChatAssetType, { join }?: {
1253
+ join?: boolean;
1254
+ }): Promise<AssetChatSession>;
1255
1255
  declare function getAssetChatChannel(assetId: string, assetType: ChatAssetType): Promise<string>;
1256
1256
 
1257
1257
  type StoredCorvaUser = CorvaUser | CorvaAPIUser;
@@ -1308,9 +1308,7 @@ interface ExternalChannel {
1308
1308
  interface AuthStore {
1309
1309
  user: User | null;
1310
1310
  serverId: string | null;
1311
- corvaCompanyId: number | null;
1312
1311
  externalChannels: Record<string, ExternalChannel>;
1313
- serverNames: string[] | null;
1314
1312
  isConnected: boolean;
1315
1313
  hasEverConnected: boolean;
1316
1314
  connectionGaveUp: boolean;
@@ -1321,7 +1319,6 @@ interface AuthStore {
1321
1319
  setHasEverConnected: (hasConnected: boolean) => void;
1322
1320
  addAssetChatChannel: (channel: AssetChatChannel) => void;
1323
1321
  setChannelServer: (channelId: string, serverId: string | null, companyId: number | null) => void;
1324
- setServerNames: (names: string[]) => void;
1325
1322
  markChatUsed: () => void;
1326
1323
  login: (credentials: LoginCredentials) => Promise<{
1327
1324
  success: boolean;
@@ -1341,7 +1338,6 @@ interface AuthStore {
1341
1338
  declare function keepChatUsed(current: boolean | null, incoming: boolean | null | undefined): boolean | null;
1342
1339
  declare const authStore: zustand_vanilla.StoreApi<AuthStore>;
1343
1340
  declare const getExternalChannel: (roomId: string | null | undefined) => ExternalChannel | null;
1344
- declare const waitForServerNames: (timeoutMs: number) => Promise<string[] | null>;
1345
1341
  declare const isExternalServerChannel: (roomId: string | null | undefined) => boolean;
1346
1342
  /** @public */
1347
1343
  declare const resetAuthStore: () => void;
@@ -1528,7 +1524,7 @@ declare const resetUIStore: () => void;
1528
1524
  interface JoinRequired {
1529
1525
  assetId: string;
1530
1526
  assetType: ChatAssetType;
1531
- companyId: number;
1527
+ companyId: number | null;
1532
1528
  companyName: string | null;
1533
1529
  }
1534
1530
  type LockedAsset = ChatAsset & {
@@ -1716,7 +1712,7 @@ declare const createSocketEventHandlers: (config: SocketEventHandlersConfig) =>
1716
1712
  onConnected: () => void;
1717
1713
  onAuthenticated: () => void;
1718
1714
  onDisconnected: () => void;
1719
- onReady: (channels: ReadyChannelData[], channelUnreads?: ChannelUnread[], servers?: ReadyServerData[]) => void;
1715
+ onReady: (channels: ReadyChannelData[], channelUnreads?: ChannelUnread[]) => void;
1720
1716
  onChannelAck: (channelId: string, messageId: string) => void;
1721
1717
  onMessage: (message: Message) => void;
1722
1718
  onRoomChange: (roomId: string, change: unknown) => void;
@@ -1738,4 +1734,4 @@ declare const createSocketEventHandlers: (config: SocketEventHandlersConfig) =>
1738
1734
 
1739
1735
  declare const installUnreadWatcher: () => void;
1740
1736
 
1741
- export { ALERT_SEVERITY, ASSET_API_FIELDS, ASSET_CHAT_PREFIXES, ASSET_NOUN, type AckScheduler, type AlertData, type AlertSeverity, type AlertWirePayload, type AppCommentAttachment, type AppCommentData, type AppCommentWirePayload, type AppStateAdapter, type AskCorvaData, type AskCorvaWirePayload, type AssetChatChannel, type AssetChatSession, type AssetStore, type Attachment, type AuthStore, CHANNEL_NAME_MAX_LENGTH, CHANNEL_TYPES, CORVA_MESSAGE_TYPES, CORVA_SYS_PREFIX, type ChannelAsset, type ChannelContentFilter, type ChannelContentFilterStore, type ChannelContentFilters, type ChannelNameValidation, type ChannelNotificationPreference, type ChannelNotificationSetting, type ChannelUnread, type ChatAsset, type ChatAssetIdentity, type ChatAssetType, type ChatDates, type ChatHost, type ChatNotifier, type ChatPlatform, type CorvaAPIUser, type CorvaApiAdapter, type CorvaRevoltAuthResponse, type CorvaSystemMessage, type CorvaUser, type CorvaUserService, DATE_SEPARATOR_LABELS, DEFAULT_CHANNEL_CONTENT_FILTER, DEFAULT_CHANNEL_CONTENT_FILTERS, DEFAULT_CHANNEL_PREFERENCE, DEFAULT_FAVORITE_ROOMS_SETTINGS, DEFAULT_HIDDEN_ROOMS_SETTINGS, DEFAULT_NOTIFICATION_PREFERENCES, DEFAULT_NOTIFICATION_SETTINGS, DEFAULT_ROOM_LIST_ORDER, DIRECT_MESSAGE_PLACEHOLDER, type ExternalChannel, type FavoriteRoomsSettings, type FavoriteRoomsStore, type FeedItemData, type FeedWirePayload, type FileAttachment, type FilterEntityWindow, type ForwardWirePayload, type ForwardedFrom, GENERAL_CHAT_NAME, type HiddenRoomsSettings, type HttpClient, type HttpClientConfig, HttpError, type HttpRequestInit, type HttpResponseLike, type JoinRequired, type KeyValueStorage, type LocatorContext, type LoginCredentials, MAX_ATTACHMENT_SIZE_BYTES, MAX_ATTACHMENT_SIZE_MB, MAX_NAVIGATION_HISTORY, MENTION_REPLACE_PATTERN, MENTION_SPLIT_PATTERN, MUTE_PRESET_OPTIONS, type MemberStore, type Message, type MessageCache, type MessageFormData, type MessageStore, NOTIFICATION_DESTINATIONS, NOTIFICATION_SETTING_ALL, NOTIFICATION_SETTING_MENTIONS, NOTIFICATION_SETTING_NOTHING, type NavigationEntry, type NavigationHistoryStore, type NotificationDestination, type NotificationPreferences, type NotificationSettings, type NotificationStore, PAUSE_INDEFINITELY, PAUSE_PRESETS, PAUSE_PRESET_OPTIONS, type PausePreset, type PausePresetOption, REVOLT_SYSTEM_USER_ID, ROOM_LIST_ORDER, type ReadyChannelData, type ReadyServerData, type RevoltAPIInstance, type RevoltChannel, type RevoltIncomingMessagePayload, type RevoltLoginResponse, type RevoltMessage, type RevoltMessageResponse, type RevoltSocketConfig, type RevoltSocketEventHandlers, type RevoltSocketInstance, type RevoltUploadResponse, type RevoltUserResponse, type Room, type RoomListOrder, type RoomStore, type RoomType, SESSION_STORAGE_KEY, SIDEBAR_SECTIONS, SIDEBAR_TABS, SOFT_DELETE_MARKER, SYSTEM_MESSAGE_TEXTS, type SaveSessionParams, type SelectableAssetType, type SessionData, SessionManager, type SharedFile, type SharedRefs, type SidebarSectionKey, type SidebarTabKey, type SocketCloseEventLike, type SocketEventHandlersConfig, type StoredChannelPreference, type Subscription, type TracesViewportRequest, type TypingManager, type UIStore, type UploadAndSendResult, type UploadFile, type UploadedFile, type User, type UserStatus, type ViewportDeepLink, type ViewportIndexCurve, type ViewportMode, WEBSOCKET_CONNECTING, WEBSOCKET_OPEN, type WebSocketLike, type WireSeverity, addMessage, addOrUpdateSubscription, alertMessageAsText, assetStore, authStore, buildAppCommentMessageContent, buildAskCorvaMessageContent, buildFinalMessage, buildForwardMessageContent, buildGroupChannelName, canDeleteMessage, canEditMessage, channelContentFilterStore, channelToAsset, chatToastStore, clearLastOpenedRoom, compareByActivity, compareByName, compareByRecencyDesc, configureChat, configureChatStorage, createAckScheduler, createCorvaUserService, createDMSubscription, createGroupSubscription, createHttpClient, createLatestWinsQueue, createMemoryStorage, createMessageCache, createRevoltAPI, createRevoltSocket, createRoomTaskQueue, createSocketEventHandlers, createSoftDeletedMessage, createTypingManager, deriveAllowedChatAsset, enrichWithCorvaData, ensureChatSession, extractTimestampFromULID, failOptimisticMessage, favoriteRoomsStore, findGeneralRoom, formatAssetChatName, getAppCommentAttachments, getAssetChatChannel, getAssetChatSession, getAssetTypeFromDisplayName, getChatHost, getChatStorage, getCorvaUserFields, getExternalChannel, getLastOpenedRoom, getMessageTimestamp, getPauseUntil, getReactionCount, getRoomDisplayName, getSystemMessageWithCorvaNames, getUserDisplayName, getUserSecondaryText, handleUnauthorized, hasReactions, hasUserReacted, initChat, installUnreadWatcher, isAlertMessage, isAppCommentMessage, isAskCorvaMessage, isChannelMuted, isChatAssetTypeAllowed, isChatStorageConfigured, isCurrentRoomSelection, isDeepEqual, isDefaultChannelPreference, isDisallowedAssetChatRoom, isDmGroup, isExternalServerChannel, isForwardedMessage, isGeneralRoom, isNotificationsPaused, isPauseActive, isSoftDeletedMessage, isSystemMessage, isUnread, isUserOnline, isValidPausePreset, isVisibleUnread, keepChatUsed, loadUntilFound, memberStore, messageStore, navigationHistoryStore, notificationStore, onChatStorageConfigured, parseCorvaSystemMessage, prepareRoomSelection, removeMessageFromList, removeSubscription, resetAssetStore, resetAuthStore, resetChannelContentFilterStore, resetChatAssetPermissionsSnapshot, resetChatHost, resetFavoriteRoomsStore, resetMemberStore, resetMessageStore, resetNavigationHistoryStore, resetNotificationStore, resetRoomStore, resetUIStore, roomStore, saveLastChatActivity, saveLastOpenedRoom, searchMessages, searchRooms, searchUsers, selectCanGoBack, selectCanGoForward, setAllowedChatAssetTypes, settleOptimisticMessage, sharedRefs, sortChannels, sortDMs, sortMessagesByTime, sortUsersByStatus, stripPlatformMentions, uiStore, updateMessageInList, uploadAndSend, validateChannelName, waitForNextPaint, waitForServerNames, wasRecentlyActive, withChannelPreferenceDefaults };
1737
+ export { ALERT_SEVERITY, ASSET_API_FIELDS, ASSET_CHAT_PREFIXES, ASSET_NOUN, type AckScheduler, type AlertData, type AlertSeverity, type AlertWirePayload, type AppCommentAttachment, type AppCommentData, type AppCommentWirePayload, type AppStateAdapter, type AskCorvaData, type AskCorvaWirePayload, type AssetChatChannel, type AssetChatSession, type AssetStore, type Attachment, type AuthStore, CHANNEL_NAME_MAX_LENGTH, CHANNEL_TYPES, CORVA_MESSAGE_TYPES, CORVA_SYS_PREFIX, type ChannelAsset, type ChannelContentFilter, type ChannelContentFilterStore, type ChannelContentFilters, type ChannelNameValidation, type ChannelNotificationPreference, type ChannelNotificationSetting, type ChannelUnread, type ChatAsset, type ChatAssetIdentity, type ChatAssetType, type ChatDates, type ChatHost, type ChatNotifier, type ChatPlatform, type CorvaAPIUser, type CorvaApiAdapter, type CorvaRevoltAuthResponse, type CorvaSystemMessage, type CorvaUser, type CorvaUserService, DATE_SEPARATOR_LABELS, DEFAULT_CHANNEL_CONTENT_FILTER, DEFAULT_CHANNEL_CONTENT_FILTERS, DEFAULT_CHANNEL_PREFERENCE, DEFAULT_FAVORITE_ROOMS_SETTINGS, DEFAULT_HIDDEN_ROOMS_SETTINGS, DEFAULT_NOTIFICATION_PREFERENCES, DEFAULT_NOTIFICATION_SETTINGS, DEFAULT_ROOM_LIST_ORDER, DIRECT_MESSAGE_PLACEHOLDER, type ExternalChannel, type FavoriteRoomsSettings, type FavoriteRoomsStore, type FeedItemData, type FeedWirePayload, type FileAttachment, type FilterEntityWindow, type ForwardWirePayload, type ForwardedFrom, GENERAL_CHAT_NAME, type HiddenRoomsSettings, type HttpClient, type HttpClientConfig, HttpError, type HttpRequestInit, type HttpResponseLike, type JoinRequired, type KeyValueStorage, type LocatorContext, type LoginCredentials, MAX_ATTACHMENT_SIZE_BYTES, MAX_ATTACHMENT_SIZE_MB, MAX_NAVIGATION_HISTORY, MENTION_REPLACE_PATTERN, MENTION_SPLIT_PATTERN, MUTE_PRESET_OPTIONS, type MemberStore, type Message, type MessageCache, type MessageFormData, type MessageStore, NOTIFICATION_DESTINATIONS, NOTIFICATION_SETTING_ALL, NOTIFICATION_SETTING_MENTIONS, NOTIFICATION_SETTING_NOTHING, type NavigationEntry, type NavigationHistoryStore, type NotificationDestination, type NotificationPreferences, type NotificationSettings, type NotificationStore, PAUSE_INDEFINITELY, PAUSE_PRESETS, PAUSE_PRESET_OPTIONS, type PausePreset, type PausePresetOption, REVOLT_SYSTEM_USER_ID, ROOM_LIST_ORDER, type ReadyChannelData, type RevoltAPIInstance, type RevoltChannel, type RevoltIncomingMessagePayload, type RevoltLoginResponse, type RevoltMessage, type RevoltMessageResponse, type RevoltSocketConfig, type RevoltSocketEventHandlers, type RevoltSocketInstance, type RevoltUploadResponse, type RevoltUserResponse, type Room, type RoomListOrder, type RoomStore, type RoomType, SESSION_STORAGE_KEY, SIDEBAR_SECTIONS, SIDEBAR_TABS, SOFT_DELETE_MARKER, SYSTEM_MESSAGE_TEXTS, type SaveSessionParams, type SelectableAssetType, type SessionData, SessionManager, type SharedFile, type SharedRefs, type SidebarSectionKey, type SidebarTabKey, type SocketCloseEventLike, type SocketEventHandlersConfig, type StoredChannelPreference, type Subscription, type TracesViewportRequest, type TypingManager, type UIStore, type UploadAndSendResult, type UploadFile, type UploadedFile, type User, type UserStatus, type ViewportDeepLink, type ViewportIndexCurve, type ViewportMode, WEBSOCKET_CONNECTING, WEBSOCKET_OPEN, type WebSocketLike, type WireSeverity, addMessage, addOrUpdateSubscription, alertMessageAsText, assetStore, authStore, buildAppCommentMessageContent, buildAskCorvaMessageContent, buildFinalMessage, buildForwardMessageContent, buildGroupChannelName, canDeleteMessage, canEditMessage, channelContentFilterStore, channelToAsset, chatToastStore, clearLastOpenedRoom, compareByActivity, compareByName, compareByRecencyDesc, configureChat, configureChatStorage, createAckScheduler, createCorvaUserService, createDMSubscription, createGroupSubscription, createHttpClient, createLatestWinsQueue, createMemoryStorage, createMessageCache, createRevoltAPI, createRevoltSocket, createRoomTaskQueue, createSocketEventHandlers, createSoftDeletedMessage, createTypingManager, deriveAllowedChatAsset, enrichWithCorvaData, ensureChatSession, extractTimestampFromULID, failOptimisticMessage, favoriteRoomsStore, findGeneralRoom, formatAssetChatName, getAppCommentAttachments, getAssetChatChannel, getAssetChatSession, getAssetTypeFromDisplayName, getChatHost, getChatStorage, getCorvaUserFields, getExternalChannel, getLastOpenedRoom, getMessageTimestamp, getPauseUntil, getReactionCount, getRoomDisplayName, getSystemMessageWithCorvaNames, getUserDisplayName, getUserSecondaryText, handleUnauthorized, hasReactions, hasUserReacted, initChat, installUnreadWatcher, isAlertMessage, isAppCommentMessage, isAskCorvaMessage, isChannelMuted, isChatAssetTypeAllowed, isChatStorageConfigured, isCurrentRoomSelection, isDeepEqual, isDefaultChannelPreference, isDisallowedAssetChatRoom, isDmGroup, isExternalServerChannel, isForwardedMessage, isGeneralRoom, isNotificationsPaused, isPauseActive, isSoftDeletedMessage, isSystemMessage, isUnread, isUserOnline, isValidPausePreset, isVisibleUnread, keepChatUsed, loadUntilFound, memberStore, messageStore, navigationHistoryStore, notificationStore, onChatStorageConfigured, parseCorvaSystemMessage, prepareRoomSelection, removeMessageFromList, removeSubscription, resetAssetStore, resetAuthStore, resetChannelContentFilterStore, resetChatAssetPermissionsSnapshot, resetChatHost, resetFavoriteRoomsStore, resetMemberStore, resetMessageStore, resetNavigationHistoryStore, resetNotificationStore, resetRoomStore, resetUIStore, roomStore, saveLastChatActivity, saveLastOpenedRoom, searchMessages, searchRooms, searchUsers, selectCanGoBack, selectCanGoForward, setAllowedChatAssetTypes, settleOptimisticMessage, sharedRefs, sortChannels, sortDMs, sortMessagesByTime, sortUsersByStatus, stripPlatformMentions, uiStore, updateMessageInList, uploadAndSend, validateChannelName, waitForNextPaint, wasRecentlyActive, withChannelPreferenceDefaults };
package/dist/index.js CHANGED
@@ -2091,7 +2091,7 @@ function createEventRouter(userCache2, sessionToken, autumnUrl, handlers, getMem
2091
2091
  break;
2092
2092
  case "Ready": {
2093
2093
  const readyEvent = message;
2094
- handlers.onReady?.(readyEvent.channels, readyEvent.channel_unreads, readyEvent.servers);
2094
+ handlers.onReady?.(readyEvent.channels, readyEvent.channel_unreads);
2095
2095
  break;
2096
2096
  }
2097
2097
  case "Message":
@@ -2988,11 +2988,11 @@ var ASSET_ID_PARAM = {
2988
2988
  frac_fleet: "frac_fleet_id",
2989
2989
  intervention_unit: "intervention_unit_id"
2990
2990
  };
2991
- async function getAssetChatSession(assetId, assetType) {
2991
+ async function getAssetChatSession(assetId, assetType, { join = false } = {}) {
2992
2992
  if (!assetId || Number.isNaN(Number(assetId))) {
2993
2993
  throw new Error("Asset ID is required");
2994
2994
  }
2995
- const body = { [ASSET_ID_PARAM[assetType]]: Number(assetId) };
2995
+ const body = { [ASSET_ID_PARAM[assetType]]: Number(assetId), ...join && { join: true } };
2996
2996
  const response = await getChatHost().corvaApi.post(
2997
2997
  "/v2/integration/revolt_chat_sessions",
2998
2998
  body
@@ -3003,7 +3003,8 @@ async function getAssetChatSession(assetId, assetType) {
3003
3003
  return {
3004
3004
  channelId: response.revolt_channel_id,
3005
3005
  serverId: response.revolt_channel_server_id ?? null,
3006
- companyId: response.revolt_channel_company_id ?? null
3006
+ companyId: response.revolt_channel_company_id ?? null,
3007
+ joined: response.revolt_channel_joined ?? true
3007
3008
  };
3008
3009
  }
3009
3010
  async function getAssetChatChannel(assetId, assetType) {
@@ -3606,7 +3607,6 @@ var ASSET_RESOURCE = {
3606
3607
  intervention_unit: "intervention_units"
3607
3608
  };
3608
3609
  var ownerRequests = /* @__PURE__ */ new Map();
3609
- var joinedThisSession = /* @__PURE__ */ new Set();
3610
3610
  async function fetchAssetOwnerCompany(assetId, assetType) {
3611
3611
  const response = await getChatHost().corvaApi.get(
3612
3612
  `/v2/${ASSET_RESOURCE[assetType]}/${assetId}`,
@@ -3628,55 +3628,45 @@ function getAssetOwnerCompany(assetId, assetType) {
3628
3628
  ownerRequests.set(key, request);
3629
3629
  return request;
3630
3630
  }
3631
- var normalizeName = (name) => name.trim().toLowerCase();
3632
- function isOnCompanyServer(serverNames, companyName) {
3633
- if (!companyName) return false;
3634
- const target = normalizeName(companyName);
3635
- return serverNames.some((name) => normalizeName(name) === target);
3636
- }
3637
- var joinedKey = (revoltUserId) => `corva_chat_joined_companies_${revoltUserId}`;
3638
- function readJoinedCompanies(revoltUserId) {
3639
- try {
3640
- const raw = getChatStorage().getItem(joinedKey(revoltUserId));
3641
- const parsed = raw ? JSON.parse(raw) : [];
3642
- return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "number") : [];
3643
- } catch {
3644
- return [];
3645
- }
3646
- }
3647
- function hasJoinedCompany(revoltUserId, companyId) {
3648
- return joinedThisSession.has(`${revoltUserId}:${companyId}`) || readJoinedCompanies(revoltUserId).includes(companyId);
3649
- }
3650
- function markCompanyJoined(revoltUserId, companyId) {
3651
- joinedThisSession.add(`${revoltUserId}:${companyId}`);
3652
- const joined = readJoinedCompanies(revoltUserId);
3653
- if (joined.includes(companyId)) return;
3654
- try {
3655
- getChatStorage().setItem(joinedKey(revoltUserId), JSON.stringify([...joined, companyId]));
3656
- } catch (error) {
3657
- console.error("Failed to save joined company:", error);
3658
- }
3659
- }
3660
3631
  function resetAssetOwnerCompanies() {
3661
3632
  ownerRequests.clear();
3662
- joinedThisSession.clear();
3663
3633
  }
3664
3634
 
3665
3635
  // src/store/stores/assetStore.ts
3666
- var SERVER_NAMES_WAIT_MS = 5e3;
3667
3636
  var joinApprovedAssets = /* @__PURE__ */ new Set();
3668
- async function getJoinRequired(assetId, assetType) {
3669
- const { corvaCompanyId, user } = authStore.getState();
3670
- if (!user?._id) return null;
3671
- if (joinApprovedAssets.has(`${assetType}:${assetId}`)) return null;
3672
- const owner = await getAssetOwnerCompany(assetId, assetType);
3673
- if (owner.id === corvaCompanyId || hasJoinedCompany(user._id, owner.id)) return null;
3674
- const serverNames = await waitForServerNames(SERVER_NAMES_WAIT_MS);
3675
- if (serverNames && isOnCompanyServer(serverNames, owner.name)) {
3676
- markCompanyJoined(user._id, owner.id);
3637
+ var assetKey = (assetType, assetId) => `${assetType}:${assetId}`;
3638
+ var isJoinUnderway = (assetType, assetId) => joinApprovedAssets.has(assetKey(assetType, assetId)) || assetStore.getState().currentAssetId === assetId && !!assetStore.getState().assetChatId;
3639
+ async function toJoinRequired(assetId, assetType, session) {
3640
+ const owner = await getAssetOwnerCompany(assetId, assetType).catch(() => null);
3641
+ return {
3642
+ assetId,
3643
+ assetType,
3644
+ companyId: session.companyId ?? owner?.id ?? null,
3645
+ companyName: owner?.name ?? null
3646
+ };
3647
+ }
3648
+ async function fetchJoinedAssetChatId(assetId, assetType) {
3649
+ let session;
3650
+ try {
3651
+ session = await getAssetChatSession(assetId, assetType);
3652
+ } catch (e) {
3653
+ console.error("Failed to fetch asset chat channel:", e);
3654
+ return null;
3655
+ }
3656
+ if (!session.joined) {
3657
+ const joinRequired = await toJoinRequired(assetId, assetType, session);
3658
+ const isCurrent = assetStore.getState().currentAssetId === assetId;
3659
+ if (isCurrent && !isJoinUnderway(assetType, assetId)) assetStore.setState({ joinRequired });
3677
3660
  return null;
3678
3661
  }
3679
- return { assetId, assetType, companyId: owner.id, companyName: owner.name };
3662
+ const chatId = session.channelId;
3663
+ registerChannelServer(session);
3664
+ registerAssetChatChannel(chatId, assetId, assetType);
3665
+ assetStore.setState((state) => ({
3666
+ assetChatId: chatId,
3667
+ knownAssetChatIds: new Set(Array.from(state.knownAssetChatIds).concat(chatId))
3668
+ }));
3669
+ return chatId;
3680
3670
  }
3681
3671
  var registerAssetChatChannel = (channelId, assetId, assetType) => {
3682
3672
  const id = Number(assetId);
@@ -3746,20 +3736,23 @@ var assetStore = createStore()((set, get) => ({
3746
3736
  });
3747
3737
  const isStale = () => get().currentAssetId !== assetId;
3748
3738
  try {
3749
- const joinRequired = await getJoinRequired(assetId, assetType);
3739
+ const join = joinApprovedAssets.has(assetKey(assetType, assetId));
3740
+ const session = await getAssetChatSession(assetId, assetType, { join });
3750
3741
  if (isStale()) return;
3751
- if (joinRequired) {
3742
+ if (!session.joined) {
3743
+ if (join) throw new Error("Could not join this chat");
3744
+ const joinRequired = await toJoinRequired(assetId, assetType, session);
3745
+ if (isStale() || isJoinUnderway(assetType, assetId)) return;
3752
3746
  set({ joinRequired });
3753
3747
  uiStore.setState({ isLoading: false });
3754
3748
  return;
3755
3749
  }
3756
- const session = await getAssetChatSession(assetId, assetType);
3757
- if (isStale()) return;
3758
3750
  const chatId = session.channelId;
3759
3751
  registerChannelServer(session);
3760
3752
  registerAssetChatChannel(chatId, assetId, assetType);
3761
3753
  set({
3762
3754
  assetChatId: chatId,
3755
+ joinRequired: null,
3763
3756
  knownAssetChatIds: new Set(Array.from(currentState.knownAssetChatIds).concat(chatId))
3764
3757
  });
3765
3758
  uiStore.setState({ isLoading: false });
@@ -3801,9 +3794,8 @@ var assetStore = createStore()((set, get) => ({
3801
3794
  },
3802
3795
  joinAssetChat: async () => {
3803
3796
  const { joinRequired } = get();
3804
- const userId = authStore.getState().user?._id;
3805
- if (!joinRequired || !userId) return;
3806
- const approvalKey = `${joinRequired.assetType}:${joinRequired.assetId}`;
3797
+ if (!joinRequired) return;
3798
+ const approvalKey = assetKey(joinRequired.assetType, joinRequired.assetId);
3807
3799
  joinApprovedAssets.add(approvalKey);
3808
3800
  set({ joinRequired: null });
3809
3801
  const { currentAssetName, currentAssetStatus } = get();
@@ -3814,46 +3806,21 @@ var assetStore = createStore()((set, get) => ({
3814
3806
  currentAssetName ?? void 0,
3815
3807
  currentAssetStatus ?? void 0
3816
3808
  );
3817
- if (get().assetChatId) markCompanyJoined(userId, joinRequired.companyId);
3818
3809
  } finally {
3819
3810
  joinApprovedAssets.delete(approvalKey);
3820
3811
  }
3821
3812
  },
3822
3813
  ensureAssetChatSubscription: async () => {
3823
- const { currentAssetId, currentAssetType } = get();
3814
+ const { currentAssetId, currentAssetType, joinRequired: pendingJoin } = get();
3824
3815
  if (!currentAssetId || !currentAssetType) return null;
3825
3816
  if (!isChatAssetTypeAllowed(currentAssetType)) return null;
3817
+ if (pendingJoin?.assetId === currentAssetId) return null;
3826
3818
  const cached = inFlightByAsset.get(currentAssetId);
3827
3819
  if (cached) return cached;
3828
3820
  const promise = (async () => {
3829
3821
  try {
3830
- let chatId = get().assetChatId;
3831
- if (!chatId) {
3832
- let joinRequired;
3833
- try {
3834
- joinRequired = await getJoinRequired(currentAssetId, currentAssetType);
3835
- } catch (e) {
3836
- console.error("Failed to check asset chat access:", e);
3837
- return null;
3838
- }
3839
- if (joinRequired) {
3840
- if (get().currentAssetId === currentAssetId) set({ joinRequired });
3841
- return null;
3842
- }
3843
- try {
3844
- const session = await getAssetChatSession(currentAssetId, currentAssetType);
3845
- chatId = session.channelId;
3846
- registerChannelServer(session);
3847
- registerAssetChatChannel(chatId, currentAssetId, currentAssetType);
3848
- set({
3849
- assetChatId: chatId,
3850
- knownAssetChatIds: new Set(Array.from(get().knownAssetChatIds).concat(chatId))
3851
- });
3852
- } catch (e) {
3853
- console.error("Failed to fetch asset chat channel:", e);
3854
- return null;
3855
- }
3856
- }
3822
+ const chatId = get().assetChatId ?? await fetchJoinedAssetChatId(currentAssetId, currentAssetType);
3823
+ if (!chatId) return null;
3857
3824
  const existing = roomStore.getState().subscriptions.find((s) => s.rid === chatId);
3858
3825
  if (existing) return existing;
3859
3826
  const { api } = sharedRefs;
@@ -4678,9 +4645,7 @@ onChatStorageConfigured(() => uiStore.setState(loadAttentionBudget()));
4678
4645
  var getInitialState6 = () => ({
4679
4646
  user: null,
4680
4647
  serverId: null,
4681
- corvaCompanyId: null,
4682
4648
  externalChannels: {},
4683
- serverNames: null,
4684
4649
  isConnected: false,
4685
4650
  hasEverConnected: false,
4686
4651
  connectionGaveUp: false,
@@ -4710,7 +4675,6 @@ var authStore = createStore()((set, get) => ({
4710
4675
  if (previous?.serverId === serverId && previous.companyId === companyId) return state;
4711
4676
  return { externalChannels: { ...rest, [channelId]: { serverId, companyId } } };
4712
4677
  }),
4713
- setServerNames: (names) => set({ serverNames: names }),
4714
4678
  markChatUsed: () => {
4715
4679
  if (get().chatUsed === true) return;
4716
4680
  set({ chatUsed: true });
@@ -4880,22 +4844,6 @@ var authStore = createStore()((set, get) => ({
4880
4844
  isSocketConnected: () => !!sharedRefs.socket?.isConnected()
4881
4845
  }));
4882
4846
  var getExternalChannel = (roomId) => roomId && authStore.getState().externalChannels[roomId] || null;
4883
- var waitForServerNames = (timeoutMs) => {
4884
- const current = authStore.getState().serverNames;
4885
- if (current) return Promise.resolve(current);
4886
- return new Promise((resolve) => {
4887
- const timer = setTimeout(() => {
4888
- unsubscribe();
4889
- resolve(null);
4890
- }, timeoutMs);
4891
- const unsubscribe = authStore.subscribe((state) => {
4892
- if (!state.serverNames) return;
4893
- clearTimeout(timer);
4894
- unsubscribe();
4895
- resolve(state.serverNames);
4896
- });
4897
- });
4898
- };
4899
4847
  var isExternalServerChannel = (roomId) => !!getExternalChannel(roomId);
4900
4848
  var resetAuthStore = () => authStore.setState(getInitialState6());
4901
4849
 
@@ -5371,11 +5319,8 @@ var createSocketEventHandlers = (config) => {
5371
5319
  onDisconnected: () => {
5372
5320
  authStore.setState({ isConnected: false });
5373
5321
  },
5374
- onReady: (channels, channelUnreads, servers) => {
5322
+ onReady: (channels, channelUnreads) => {
5375
5323
  if (!authStore.getState().user?._id) return;
5376
- authStore.getState().setServerNames(
5377
- (servers ?? []).map((server) => server.name).filter((name) => !!name)
5378
- );
5379
5324
  const channelLastMsg = /* @__PURE__ */ new Map();
5380
5325
  channels.forEach((ch) => {
5381
5326
  if (ch.last_message_id) {
@@ -5963,9 +5908,6 @@ async function handleUnauthorized() {
5963
5908
  function ensureChatSession(corvaUser) {
5964
5909
  lastCorvaUser = corvaUser;
5965
5910
  initChat();
5966
- if (authStore.getState().corvaCompanyId !== corvaUser.company_id) {
5967
- authStore.setState({ corvaCompanyId: corvaUser.company_id ?? null });
5968
- }
5969
5911
  sharedRefs.api?.setUnauthorizedHandler(() => {
5970
5912
  handleUnauthorized().catch((error) => console.error("Chat re-authentication failed", error));
5971
5913
  });
@@ -5989,6 +5931,6 @@ function ensureChatSession(corvaUser) {
5989
5931
  return inFlight;
5990
5932
  }
5991
5933
 
5992
- export { ALERT_SEVERITY, ASSET_API_FIELDS, ASSET_CHAT_PREFIXES, ASSET_NOUN, CHANNEL_NAME_MAX_LENGTH, CHANNEL_TYPES, CORVA_MESSAGE_TYPES, CORVA_SYS_PREFIX, DATE_SEPARATOR_LABELS, DEFAULT_CHANNEL_CONTENT_FILTER, DEFAULT_CHANNEL_CONTENT_FILTERS, DEFAULT_CHANNEL_PREFERENCE, DEFAULT_FAVORITE_ROOMS_SETTINGS, DEFAULT_HIDDEN_ROOMS_SETTINGS, DEFAULT_NOTIFICATION_PREFERENCES, DEFAULT_NOTIFICATION_SETTINGS, DEFAULT_ROOM_LIST_ORDER, DIRECT_MESSAGE_PLACEHOLDER, GENERAL_CHAT_NAME, HttpError, MAX_ATTACHMENT_SIZE_BYTES, MAX_ATTACHMENT_SIZE_MB, MAX_NAVIGATION_HISTORY, MENTION_REPLACE_PATTERN, MENTION_SPLIT_PATTERN, MUTE_PRESET_OPTIONS, NOTIFICATION_DESTINATIONS, NOTIFICATION_SETTING_ALL, NOTIFICATION_SETTING_MENTIONS, NOTIFICATION_SETTING_NOTHING, PAUSE_INDEFINITELY, PAUSE_PRESETS, PAUSE_PRESET_OPTIONS, REVOLT_SYSTEM_USER_ID, ROOM_LIST_ORDER, SESSION_STORAGE_KEY, SIDEBAR_SECTIONS, SIDEBAR_TABS, SOFT_DELETE_MARKER, SYSTEM_MESSAGE_TEXTS, SessionManager, WEBSOCKET_CONNECTING, WEBSOCKET_OPEN, addMessage, addOrUpdateSubscription, alertMessageAsText, assetStore, authStore, buildAppCommentMessageContent, buildAskCorvaMessageContent, buildFinalMessage, buildForwardMessageContent, buildGroupChannelName, canDeleteMessage, canEditMessage, channelContentFilterStore, channelToAsset, chatToastStore, clearLastOpenedRoom, compareByActivity, compareByName, compareByRecencyDesc, configureChat, configureChatStorage, createAckScheduler, createCorvaUserService, createDMSubscription, createGroupSubscription, createHttpClient, createLatestWinsQueue, createMemoryStorage, createMessageCache, createRevoltAPI, createRevoltSocket, createRoomTaskQueue, createSocketEventHandlers, createSoftDeletedMessage, createTypingManager, deriveAllowedChatAsset, enrichWithCorvaData, ensureChatSession, extractTimestampFromULID, failOptimisticMessage, favoriteRoomsStore, findGeneralRoom, formatAssetChatName, getAppCommentAttachments, getAssetChatChannel, getAssetChatSession, getAssetTypeFromDisplayName, getChatHost, getChatStorage, getCorvaUserFields, getExternalChannel, getLastOpenedRoom, getMessageTimestamp, getPauseUntil, getReactionCount, getRoomDisplayName, getSystemMessageWithCorvaNames, getUserDisplayName, getUserSecondaryText, handleUnauthorized, hasReactions, hasUserReacted, initChat, installUnreadWatcher, isAlertMessage, isAppCommentMessage, isAskCorvaMessage, isChannelMuted, isChatAssetTypeAllowed, isChatStorageConfigured, isCurrentRoomSelection, isDeepEqual, isDefaultChannelPreference, isDisallowedAssetChatRoom, isDmGroup, isExternalServerChannel, isForwardedMessage, isGeneralRoom, isNotificationsPaused, isPauseActive, isSoftDeletedMessage, isSystemMessage, isUnread, isUserOnline, isValidPausePreset, isVisibleUnread, keepChatUsed, loadUntilFound, memberStore, messageStore, navigationHistoryStore, notificationStore, onChatStorageConfigured, parseCorvaSystemMessage, prepareRoomSelection, removeMessageFromList, removeSubscription, resetAssetStore, resetAuthStore, resetChannelContentFilterStore, resetChatAssetPermissionsSnapshot, resetChatHost, resetFavoriteRoomsStore, resetMemberStore, resetMessageStore, resetNavigationHistoryStore, resetNotificationStore, resetRoomStore, resetUIStore, roomStore, saveLastChatActivity, saveLastOpenedRoom, searchMessages, searchRooms, searchUsers, selectCanGoBack, selectCanGoForward, setAllowedChatAssetTypes, settleOptimisticMessage, sharedRefs, sortChannels, sortDMs, sortMessagesByTime, sortUsersByStatus, stripPlatformMentions, uiStore, updateMessageInList, uploadAndSend, validateChannelName, waitForNextPaint, waitForServerNames, wasRecentlyActive, withChannelPreferenceDefaults };
5934
+ export { ALERT_SEVERITY, ASSET_API_FIELDS, ASSET_CHAT_PREFIXES, ASSET_NOUN, CHANNEL_NAME_MAX_LENGTH, CHANNEL_TYPES, CORVA_MESSAGE_TYPES, CORVA_SYS_PREFIX, DATE_SEPARATOR_LABELS, DEFAULT_CHANNEL_CONTENT_FILTER, DEFAULT_CHANNEL_CONTENT_FILTERS, DEFAULT_CHANNEL_PREFERENCE, DEFAULT_FAVORITE_ROOMS_SETTINGS, DEFAULT_HIDDEN_ROOMS_SETTINGS, DEFAULT_NOTIFICATION_PREFERENCES, DEFAULT_NOTIFICATION_SETTINGS, DEFAULT_ROOM_LIST_ORDER, DIRECT_MESSAGE_PLACEHOLDER, GENERAL_CHAT_NAME, HttpError, MAX_ATTACHMENT_SIZE_BYTES, MAX_ATTACHMENT_SIZE_MB, MAX_NAVIGATION_HISTORY, MENTION_REPLACE_PATTERN, MENTION_SPLIT_PATTERN, MUTE_PRESET_OPTIONS, NOTIFICATION_DESTINATIONS, NOTIFICATION_SETTING_ALL, NOTIFICATION_SETTING_MENTIONS, NOTIFICATION_SETTING_NOTHING, PAUSE_INDEFINITELY, PAUSE_PRESETS, PAUSE_PRESET_OPTIONS, REVOLT_SYSTEM_USER_ID, ROOM_LIST_ORDER, SESSION_STORAGE_KEY, SIDEBAR_SECTIONS, SIDEBAR_TABS, SOFT_DELETE_MARKER, SYSTEM_MESSAGE_TEXTS, SessionManager, WEBSOCKET_CONNECTING, WEBSOCKET_OPEN, addMessage, addOrUpdateSubscription, alertMessageAsText, assetStore, authStore, buildAppCommentMessageContent, buildAskCorvaMessageContent, buildFinalMessage, buildForwardMessageContent, buildGroupChannelName, canDeleteMessage, canEditMessage, channelContentFilterStore, channelToAsset, chatToastStore, clearLastOpenedRoom, compareByActivity, compareByName, compareByRecencyDesc, configureChat, configureChatStorage, createAckScheduler, createCorvaUserService, createDMSubscription, createGroupSubscription, createHttpClient, createLatestWinsQueue, createMemoryStorage, createMessageCache, createRevoltAPI, createRevoltSocket, createRoomTaskQueue, createSocketEventHandlers, createSoftDeletedMessage, createTypingManager, deriveAllowedChatAsset, enrichWithCorvaData, ensureChatSession, extractTimestampFromULID, failOptimisticMessage, favoriteRoomsStore, findGeneralRoom, formatAssetChatName, getAppCommentAttachments, getAssetChatChannel, getAssetChatSession, getAssetTypeFromDisplayName, getChatHost, getChatStorage, getCorvaUserFields, getExternalChannel, getLastOpenedRoom, getMessageTimestamp, getPauseUntil, getReactionCount, getRoomDisplayName, getSystemMessageWithCorvaNames, getUserDisplayName, getUserSecondaryText, handleUnauthorized, hasReactions, hasUserReacted, initChat, installUnreadWatcher, isAlertMessage, isAppCommentMessage, isAskCorvaMessage, isChannelMuted, isChatAssetTypeAllowed, isChatStorageConfigured, isCurrentRoomSelection, isDeepEqual, isDefaultChannelPreference, isDisallowedAssetChatRoom, isDmGroup, isExternalServerChannel, isForwardedMessage, isGeneralRoom, isNotificationsPaused, isPauseActive, isSoftDeletedMessage, isSystemMessage, isUnread, isUserOnline, isValidPausePreset, isVisibleUnread, keepChatUsed, loadUntilFound, memberStore, messageStore, navigationHistoryStore, notificationStore, onChatStorageConfigured, parseCorvaSystemMessage, prepareRoomSelection, removeMessageFromList, removeSubscription, resetAssetStore, resetAuthStore, resetChannelContentFilterStore, resetChatAssetPermissionsSnapshot, resetChatHost, resetFavoriteRoomsStore, resetMemberStore, resetMessageStore, resetNavigationHistoryStore, resetNotificationStore, resetRoomStore, resetUIStore, roomStore, saveLastChatActivity, saveLastOpenedRoom, searchMessages, searchRooms, searchUsers, selectCanGoBack, selectCanGoForward, setAllowedChatAssetTypes, settleOptimisticMessage, sharedRefs, sortChannels, sortDMs, sortMessagesByTime, sortUsersByStatus, stripPlatformMentions, uiStore, updateMessageInList, uploadAndSend, validateChannelName, waitForNextPaint, wasRecentlyActive, withChannelPreferenceDefaults };
5993
5935
  //# sourceMappingURL=index.js.map
5994
5936
  //# sourceMappingURL=index.js.map