@liveblocks/react 2.0.0-alpha3 → 2.0.0-alpha5

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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/version.ts","../src/ClientSideSuspense.tsx","../src/liveblocks.tsx","../src/comments/lib/selected-inbox-notifications.ts","../src/lib/retry-error.ts","../src/lib/use-initial.ts","../src/lib/use-latest.ts","../src/comments/errors.ts","../src/comments/lib/selected-threads.ts","../src/room.tsx","../src/comments/lib/createIds.ts","../src/comments/lib/select-notification-settings.ts","../src/use-scroll-to-comment-on-load-effect.ts"],"names":["React","useCallback","useEffect","useInboxNotificationThread","useMarkInboxNotificationAsRead","useMarkAllInboxNotificationsAsRead","LiveblocksProvider","applyOptimisticUpdates","console","kInternal","makePoller","nanoid","useSyncExternalStoreWithSelector","comment","noop","useSyncExternalStore","POLLING_INTERVAL","_extras","_bundles","getExtrasForClient","makeExtrasForClient","subscribers","room","other","rootOrNull","state","err","metadata","inboxNotification","settings"],"mappings":";AAGO,IAAM,WAAW;AACjB,IAAM,cAAiD;AACvD,IAAM,aAAgD;;;ACJ7D,YAAY,WAAW;AAwBhB,SAAS,mBAAmB,OAAc;AAC/C,QAAM,CAAC,SAAS,UAAU,IAAU,eAAS,KAAK;AAElD,EAAM,gBAAU,MAAM;AAGpB,eAAW,IAAI;AAAA,EACjB,GAAG,CAAC,CAAC;AAEL,SACE,oCAAO,gBAAN,EAAe,UAAU,MAAM,YAC7B,UACG,OAAO,MAAM,aAAa,aACxB,MAAM,SAAS,IACf,MAAM,WACR,MAAM,QACZ;AAEJ;;;ACzBA,SAAS,cAAc,WAAW,YAAY,aAAa;AAC3D,SAAS,cAAc;AAEvB,OAAOA;AAAA,EACL;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,wCAAwC;;;ACxBjD,SAAS,8BAA8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K;AAAA,MACrD;AAAA,IACF;AAAA,IACA,CAAC,IAAI;AAAA,EACP;AAEA,QAAM,WAAWP;AAAA,IACf,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAa,eAAQ,MAAM;AACzB,WAAO,CAAC,UAAU,8BAA8B;AAAA,EAClD,GAAG,CAAC,UAAU,8BAA8B,CAAC;AAC/C;AAGO,SAAS,gBAMgB;AAC9B,SAAa,kBAAW,WAAW;AACrC;AAuBO,SAAS,kBAMd,QAAwD;AACxD,SAAO,6BAA4C,MAAM;AAC3D;AAEO,SAAS,iBACd,QACA,SACA;AACA,SAAO,GAAG,MAAM,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC;AAC9C;AAIA,IAAM,gBAA0D;AAChE,IAAM,qBACJ;AACF,IAAM,qBACJ;AACF,IAAM,WAAgD;AACtD,IAAM,kBACJ;AACF,IAAM,eAAwD;AAC9D,IAAM,mBACJ;AACF,IAAM,yBACJ;AACF,IAAM,oBACJ;AACF,IAAM,iBAA4D;AAClE,IAAM,mBACJ;AACF,IAAM,2BACJ;AACF,IAAM,cAAsD;AAC5D,IAAM,sBACJ;AACF,IAAM,YAAkD;AACxD,IAAM,aAAoD;AAC1D,IAAM,oBACJ;AACF,IAAM,qBACJ;AACF,IAAM,cAAsD;AAC5D,IAAM,sBACJ;AACF,IAAM,WAAgD;AACtD,IAAM,mBACJ;AACF,IAAM,kBACJ;AACF,IAAM,uBACJ","sourcesContent":["declare const __VERSION__: string;\ndeclare const TSUP_FORMAT: string;\n\nexport const PKG_NAME = \"@liveblocks/react\";\nexport const PKG_VERSION = typeof __VERSION__ === \"string\" && __VERSION__;\nexport const PKG_FORMAT = typeof TSUP_FORMAT === \"string\" && TSUP_FORMAT;\n","import type { ReactNode } from \"react\";\nimport * as React from \"react\";\n\ntype Props = {\n fallback: ReactNode;\n children: (() => ReactNode | undefined) | ReactNode | undefined;\n};\n\n/**\n * Almost like a normal <Suspense> component, except that for server-side\n * renders, the fallback will be used.\n *\n * The child props will have to be provided in a function, i.e. change:\n *\n * <Suspense fallback={<Loading />}>\n * <MyRealComponent a={1} />\n * </Suspense>\n *\n * To:\n *\n * <ClientSideSuspense fallback={<Loading />}>\n * <MyRealComponent a={1} />\n * </ClientSideSuspense>\n *\n */\nexport function ClientSideSuspense(props: Props) {\n const [mounted, setMounted] = React.useState(false);\n\n React.useEffect(() => {\n // Effects are never executed on the server side. The point of this is to\n // delay the flipping of this boolean until after hydration has happened.\n setMounted(true);\n }, []);\n\n return (\n <React.Suspense fallback={props.fallback}>\n {mounted\n ? typeof props.children === \"function\"\n ? props.children()\n : props.children\n : props.fallback}\n </React.Suspense>\n );\n}\n","import type {\n BaseMetadata,\n BaseUserMeta,\n Client,\n ThreadData,\n} from \"@liveblocks/client\";\nimport type {\n CacheState,\n CacheStore,\n ClientOptions,\n DM,\n DU,\n InboxNotificationData,\n InboxNotificationDeleteInfo,\n OpaqueClient,\n PrivateClientApi,\n ThreadDeleteInfo,\n} from \"@liveblocks/core\";\nimport { createClient, kInternal, makePoller, raise } from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport type { PropsWithChildren } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n} from \"react\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport { selectedInboxNotifications } from \"./comments/lib/selected-inbox-notifications\";\nimport { retryError } from \"./lib/retry-error\";\nimport { useInitial, useInitialUnlessFunction } from \"./lib/use-initial\";\nimport type {\n InboxNotificationsState,\n InboxNotificationsStateSuccess,\n LiveblocksContextBundle,\n RoomInfoState,\n RoomInfoStateSuccess,\n SharedContextBundle,\n UnreadInboxNotificationsCountState,\n UnreadInboxNotificationsCountStateSuccess,\n UserState,\n UserStateSuccess,\n} from \"./types\";\n\nexport const ClientContext = createContext<OpaqueClient | null>(null);\n\nconst missingUserError = new Error(\n \"resolveUsers didn't return anything for this user ID.\"\n);\nconst missingRoomInfoError = new Error(\n \"resolveRoomsInfo didn't return anything for this room ID.\"\n);\n\nconst _extras = new WeakMap<\n OpaqueClient,\n ReturnType<typeof makeExtrasForClient>\n>();\nconst _bundles = new WeakMap<\n OpaqueClient,\n LiveblocksContextBundle<BaseUserMeta, BaseMetadata>\n>();\n\nexport const POLLING_INTERVAL = 60 * 1000; // 1 minute\nexport const INBOX_NOTIFICATIONS_QUERY = \"INBOX_NOTIFICATIONS\";\n\nfunction selectorFor_useInboxNotifications(\n state: CacheState<BaseMetadata>\n): InboxNotificationsState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n inboxNotifications: selectedInboxNotifications(state),\n isLoading: false,\n };\n}\n\nfunction selectorFor_useInboxNotificationsSuspense(\n state: CacheState<BaseMetadata>\n): InboxNotificationsStateSuccess {\n return {\n inboxNotifications: selectedInboxNotifications(state),\n isLoading: false,\n };\n}\n\nfunction selectUnreadInboxNotificationsCount(state: CacheState<BaseMetadata>) {\n let count = 0;\n\n for (const notification of selectedInboxNotifications(state)) {\n if (\n notification.readAt === null ||\n notification.readAt < notification.notifiedAt\n ) {\n count++;\n }\n }\n\n return count;\n}\n\nfunction selectorFor_useUnreadInboxNotificationsCount(\n state: CacheState<BaseMetadata>\n): UnreadInboxNotificationsCountState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(state),\n };\n}\n\nfunction selectorFor_useUnreadInboxNotificationsCountSuspense(\n state: CacheState<BaseMetadata>\n): UnreadInboxNotificationsCountStateSuccess {\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(state),\n };\n}\n\nfunction getOrCreateContextBundle<\n U extends BaseUserMeta,\n M extends BaseMetadata,\n>(client: OpaqueClient): LiveblocksContextBundle<U, M> {\n let bundle = _bundles.get(client);\n if (!bundle) {\n bundle = makeLiveblocksContextBundle(client);\n _bundles.set(client, bundle);\n }\n return bundle as LiveblocksContextBundle<U, M>;\n}\n\n// TODO: Likely a better / more clear name for this helper will arise. I'll\n// rename this later. All of these are implementation details to support inbox\n// notifications on a per-client basis.\nfunction getExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n let extras = _extras.get(client);\n if (!extras) {\n extras = makeExtrasForClient(client);\n _extras.set(client, extras);\n }\n\n return extras as unknown as Omit<typeof extras, \"store\"> & {\n store: CacheStore<M>;\n };\n}\n\nfunction makeExtrasForClient<U extends BaseUserMeta, M extends BaseMetadata>(\n client: OpaqueClient\n) {\n const internals = client[kInternal] as PrivateClientApi<U, M>;\n const store = internals.cacheStore;\n const notifications = internals.notifications;\n\n let fetchInboxNotificationsRequest: Promise<{\n inboxNotifications: InboxNotificationData[];\n threads: ThreadData<M>[];\n deletedThreads: ThreadDeleteInfo[];\n deletedInboxNotifications: InboxNotificationDeleteInfo[];\n meta: {\n requestedAt: Date;\n };\n }> | null = null;\n\n let lastRequestedAt: Date | undefined;\n\n const poller = makePoller(() =>\n notifications.getInboxNotifications({ since: lastRequestedAt }).then(\n (result) => {\n lastRequestedAt = result.meta.requestedAt;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n },\n () => {\n // TODO: Error handling\n }\n )\n );\n\n async function fetchInboxNotifications(\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n if (fetchInboxNotificationsRequest !== null) {\n return fetchInboxNotificationsRequest;\n }\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: true,\n });\n\n try {\n fetchInboxNotificationsRequest = notifications.getInboxNotifications();\n\n const result = await fetchInboxNotificationsRequest;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n\n /**\n * We set the `lastRequestedAt` to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt`has not been set\n * OR\n * 2. The current `lastRequestedAt` is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAt = result.meta.requestedAt;\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (er) {\n fetchInboxNotificationsRequest = null;\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void fetchInboxNotifications({\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: false,\n error: er as Error,\n });\n }\n return;\n }\n\n let inboxNotificationsSubscribers = 0;\n\n function useSubscribeToInboxNotificationsEffect(options?: {\n autoFetch: boolean;\n }) {\n const autoFetch = useInitial(options?.autoFetch ?? true);\n useEffect(() => {\n if (autoFetch) {\n void fetchInboxNotifications();\n }\n\n // Increment\n inboxNotificationsSubscribers++;\n poller.start(POLLING_INTERVAL);\n\n return () => {\n // Decrement\n if (inboxNotificationsSubscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${INBOX_NOTIFICATIONS_QUERY}\"`\n );\n return;\n }\n\n inboxNotificationsSubscribers--;\n if (inboxNotificationsSubscribers <= 0) {\n poller.stop();\n }\n };\n }, [autoFetch]);\n }\n\n return {\n store,\n notifications,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n };\n}\n\nfunction makeLiveblocksContextBundle<\n U extends BaseUserMeta,\n M extends BaseMetadata,\n>(client: Client<U>): LiveblocksContextBundle<U, M> {\n // Bind all hooks to the current client instance\n const useInboxNotificationThread = (inboxNotificationId: string) =>\n useInboxNotificationThread_withClient<M>(client, inboxNotificationId);\n\n const useMarkInboxNotificationAsRead = () =>\n useMarkInboxNotificationAsRead_withClient(client);\n\n const useMarkAllInboxNotificationsAsRead = () =>\n useMarkAllInboxNotificationsAsRead_withClient(client);\n\n // NOTE: This version of the LiveblocksProvider does _not_ take any props.\n // This is because we already have a client bound to it.\n function LiveblocksProvider(props: PropsWithChildren) {\n return (\n <ClientContext.Provider value={client}>\n {props.children}\n </ClientContext.Provider>\n );\n }\n\n const shared = createSharedContext<U>(client);\n\n const bundle: LiveblocksContextBundle<U, M> = {\n LiveblocksProvider,\n\n useInboxNotifications: () => useInboxNotifications_withClient(client),\n useUnreadInboxNotificationsCount: () =>\n useUnreadInboxNotificationsCount_withClient(client),\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n useInboxNotificationThread,\n\n ...shared.classic,\n\n suspense: {\n LiveblocksProvider,\n\n useInboxNotifications: () =>\n useInboxNotificationsSuspense_withClient(client),\n useUnreadInboxNotificationsCount: () =>\n useUnreadInboxNotificationsCountSuspense_withClient(client),\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n useInboxNotificationThread,\n\n ...shared.suspense,\n },\n };\n return bundle;\n}\n\nfunction useInboxNotifications_withClient(client: OpaqueClient) {\n const { store, useSubscribeToInboxNotificationsEffect } =\n getExtrasForClient(client);\n\n useSubscribeToInboxNotificationsEffect();\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selectorFor_useInboxNotifications\n );\n}\n\nfunction useInboxNotificationsSuspense_withClient(client: OpaqueClient) {\n const {\n store,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n } = getExtrasForClient(client);\n\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n if (query.error !== undefined) {\n throw query.error;\n }\n\n useSubscribeToInboxNotificationsEffect({ autoFetch: false });\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selectorFor_useInboxNotificationsSuspense\n );\n}\n\nfunction useUnreadInboxNotificationsCount_withClient(client: OpaqueClient) {\n const { store, useSubscribeToInboxNotificationsEffect } =\n getExtrasForClient(client);\n\n useSubscribeToInboxNotificationsEffect();\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selectorFor_useUnreadInboxNotificationsCount\n );\n}\n\nfunction useUnreadInboxNotificationsCountSuspense_withClient(\n client: OpaqueClient\n) {\n const {\n store,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n } = getExtrasForClient(client);\n\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n useSubscribeToInboxNotificationsEffect({ autoFetch: false });\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selectorFor_useUnreadInboxNotificationsCountSuspense\n );\n}\n\nfunction useMarkInboxNotificationAsRead_withClient(client: OpaqueClient) {\n return useCallback(\n (inboxNotificationId: string) => {\n const { store, notifications } = getExtrasForClient(client);\n\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId,\n readAt,\n });\n\n notifications.markInboxNotificationAsRead(inboxNotificationId).then(\n () => {\n store.set((state) => {\n const existingNotification =\n state.inboxNotifications[inboxNotificationId];\n\n // If existing notification has been deleted, we return the existing state\n if (existingNotification === undefined) {\n return {\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n }\n\n return {\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotificationId]: {\n ...existingNotification,\n readAt,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n });\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n },\n [client]\n );\n}\n\nfunction useMarkAllInboxNotificationsAsRead_withClient(client: OpaqueClient) {\n return useCallback(() => {\n const { store, notifications } = getExtrasForClient(client);\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notifications-as-read\",\n id: optimisticUpdateId,\n readAt,\n });\n\n notifications.markAllInboxNotificationsAsRead().then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: Object.fromEntries(\n Array.from(Object.entries(state.inboxNotifications)).map(\n ([id, inboxNotification]) => [\n id,\n { ...inboxNotification, readAt },\n ]\n )\n ),\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n }, [client]);\n}\n\nfunction useInboxNotificationThread_withClient<M extends BaseMetadata>(\n client: OpaqueClient,\n inboxNotificationId: string\n): ThreadData<M> {\n const { store } = getExtrasForClient<M>(client);\n\n const selector = useCallback(\n (state: CacheState<M>) => {\n const inboxNotification =\n state.inboxNotifications[inboxNotificationId] ??\n raise(`Inbox notification with ID \"${inboxNotificationId}\" not found`);\n\n if (inboxNotification.kind !== \"thread\") {\n raise(\n `Inbox notification with ID \"${inboxNotificationId}\" is not of kind \"thread\"`\n );\n }\n\n const thread =\n state.threads[inboxNotification.threadId] ??\n raise(\n `Thread with ID \"${inboxNotification.threadId}\" not found, this inbox notification might not be of kind \"thread\"`\n );\n\n return thread;\n },\n [inboxNotificationId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n}\n\nfunction useUser_withClient<U extends BaseUserMeta>(\n client: Client<U>,\n userId: string\n): UserState<U[\"info\"]> {\n const usersStore = client[kInternal].usersStore;\n\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [usersStore, userId]\n );\n\n useEffect(() => {\n void usersStore.get(userId);\n }, [usersStore, userId]);\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n user: state.data,\n // Return an error if `undefined` was returned by `resolveUsers` for this user ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingUserError\n : state.error,\n } as UserState<U[\"info\"]>)\n : { isLoading: true };\n}\n\nfunction useUserSuspense_withClient<U extends BaseUserMeta>(\n client: Client<U>,\n userId: string\n) {\n const usersStore = client[kInternal].usersStore;\n\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [usersStore, userId]\n );\n const userState = getUserState();\n\n if (!userState || userState.isLoading) {\n throw usersStore.get(userId);\n }\n\n if (userState.error) {\n throw userState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveUsers` for this user ID\n if (!userState.data) {\n throw missingUserError;\n }\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return {\n isLoading: false,\n user: state?.data,\n error: state?.error,\n } as UserStateSuccess<U[\"info\"]>;\n}\n\nfunction useRoomInfo_withClient(\n client: OpaqueClient,\n roomId: string\n): RoomInfoState {\n const roomsInfoStore = client[kInternal].roomsInfoStore;\n\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomsInfoStore, roomId]\n );\n\n useEffect(() => {\n void roomsInfoStore.get(roomId);\n }, [roomsInfoStore, roomId]);\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n info: state.data,\n // Return an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingRoomInfoError\n : state.error,\n } as RoomInfoState)\n : { isLoading: true };\n}\n\nfunction useRoomInfoSuspense_withClient(client: OpaqueClient, roomId: string) {\n const roomsInfoStore = client[kInternal].roomsInfoStore;\n\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomsInfoStore, roomId]\n );\n const roomInfoState = getRoomInfoState();\n\n if (!roomInfoState || roomInfoState.isLoading) {\n throw roomsInfoStore.get(roomId);\n }\n\n if (roomInfoState.error) {\n throw roomInfoState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n if (!roomInfoState.data) {\n throw missingRoomInfoError;\n }\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return {\n isLoading: false,\n info: state?.data,\n error: state?.error,\n } as RoomInfoStateSuccess;\n}\n\n/** @internal */\nexport function createSharedContext<U extends BaseUserMeta>(\n client: Client<U>\n): SharedContextBundle<U> {\n return {\n classic: {\n useUser: (userId: string) => useUser_withClient(client, userId),\n useRoomInfo: (roomId: string) => useRoomInfo_withClient(client, roomId),\n },\n suspense: {\n useUser: (userId: string) => useUserSuspense_withClient(client, userId),\n useRoomInfo: (roomId: string) =>\n useRoomInfoSuspense_withClient(client, roomId),\n },\n };\n}\n\n/**\n * @private This is an internal API.\n */\nexport function useClientOrNull<U extends BaseUserMeta>() {\n return useContext(ClientContext) as Client<U> | null;\n}\n\n/**\n * Obtains a reference to the current Liveblocks client.\n */\nexport function useClient<U extends BaseUserMeta>() {\n return (\n useClientOrNull<U>() ??\n raise(\"LiveblocksProvider is missing from the React tree.\")\n );\n}\n\n/**\n * @private\n */\nexport function LiveblocksProviderWithClient(\n props: PropsWithChildren<{ client: OpaqueClient }>\n) {\n return (\n <ClientContext.Provider value={props.client}>\n {props.children}\n </ClientContext.Provider>\n );\n}\n\nexport function LiveblocksProvider<U extends BaseUserMeta = DU>(\n props: PropsWithChildren<ClientOptions<U>>\n) {\n const { children, ...o } = props;\n\n // It's important that the static options remain stable, otherwise we'd be\n // creating new client instances on every render.\n const options = {\n publicApiKey: useInitial(o.publicApiKey),\n throttle: useInitial(o.throttle),\n lostConnectionTimeout: useInitial(o.lostConnectionTimeout),\n backgroundKeepAliveTimeout: useInitial(o.backgroundKeepAliveTimeout),\n polyfills: useInitial(o.polyfills),\n unstable_fallbackToHTTP: useInitial(o.unstable_fallbackToHTTP),\n unstable_streamData: useInitial(o.unstable_streamData),\n\n authEndpoint: useInitialUnlessFunction(o.authEndpoint),\n resolveMentionSuggestions: useInitialUnlessFunction(\n o.resolveMentionSuggestions\n ),\n resolveUsers: useInitialUnlessFunction(o.resolveUsers),\n resolveRoomsInfo: useInitialUnlessFunction(o.resolveRoomsInfo),\n\n baseUrl: useInitial(\n // @ts-expect-error - Hidden config options\n o.baseUrl as string | undefined\n ),\n enableDebugLogging: useInitial(\n // @ts-expect-error - Hidden config options\n o.enableDebugLogging as boolean | undefined\n ),\n } as ClientOptions<U>;\n\n // NOTE: Deliberately not passing any deps here, because we'll _never_ want\n // to recreate a client instance after the first render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const client = useMemo(() => createClient<U>(options), []);\n return (\n <LiveblocksProviderWithClient client={client}>\n {children}\n </LiveblocksProviderWithClient>\n );\n}\n\nexport function createLiveblocksContext<\n U extends BaseUserMeta = DU,\n M extends BaseMetadata = DM,\n>(client: OpaqueClient): LiveblocksContextBundle<U, M> {\n return getOrCreateContextBundle<U, M>(client);\n}\n\nfunction useInboxNotifications() {\n return useInboxNotifications_withClient(useClient());\n}\n\nfunction useInboxNotificationsSuspense() {\n return useInboxNotificationsSuspense_withClient(useClient());\n}\n\nfunction useInboxNotificationThread<M extends BaseMetadata>(\n inboxNotificationId: string\n) {\n return useInboxNotificationThread_withClient<M>(\n useClient(),\n inboxNotificationId\n );\n}\n\nfunction useMarkAllInboxNotificationsAsRead() {\n return useMarkAllInboxNotificationsAsRead_withClient(useClient());\n}\n\nfunction useMarkInboxNotificationAsRead() {\n return useMarkInboxNotificationAsRead_withClient(useClient());\n}\n\nfunction useUnreadInboxNotificationsCount() {\n return useUnreadInboxNotificationsCount_withClient(useClient());\n}\n\nfunction useUnreadInboxNotificationsCountSuspense() {\n return useUnreadInboxNotificationsCountSuspense_withClient(useClient());\n}\n\nfunction useUser<U extends BaseUserMeta>(userId: string) {\n const client = useClient<U>();\n return useUser_withClient(client, userId);\n}\n\nfunction useUserSuspense<U extends BaseUserMeta>(userId: string) {\n const client = useClient<U>();\n return useUserSuspense_withClient(client, userId);\n}\n\nfunction useRoomInfo(roomId: string) {\n return useRoomInfo_withClient(useClient(), roomId);\n}\n\nfunction useRoomInfoSuspense(roomId: string) {\n return useRoomInfoSuspense_withClient(useClient(), roomId);\n}\n\n// TODO in 2.0 Copy/paste all the docstrings onto these global hooks :(\nconst __1: LiveblocksContextBundle<DU, DM>[\"useInboxNotificationThread\"] =\n useInboxNotificationThread;\nconst __2: LiveblocksContextBundle<DU, DM>[\"useUser\"] = useUser;\nconst __3: LiveblocksContextBundle<DU, DM>[\"suspense\"][\"useUser\"] =\n useUserSuspense;\n\n// eslint-disable-next-line simple-import-sort/exports\nexport {\n __1 as useInboxNotificationThread,\n __2 as useUser,\n __3 as useUserSuspense,\n useInboxNotifications,\n useInboxNotificationsSuspense,\n useMarkAllInboxNotificationsAsRead,\n useMarkInboxNotificationAsRead,\n useRoomInfo,\n useRoomInfoSuspense,\n useUnreadInboxNotificationsCount,\n useUnreadInboxNotificationsCountSuspense,\n};\n","import type {\n BaseMetadata,\n CacheState,\n InboxNotificationData,\n} from \"@liveblocks/core\";\nimport { applyOptimisticUpdates } from \"@liveblocks/core\";\n\nexport function selectedInboxNotifications<M extends BaseMetadata>(\n state: CacheState<M>\n): InboxNotificationData[] {\n const result = applyOptimisticUpdates(state);\n\n return Object.values(result.inboxNotifications).sort(\n // Sort so that the most recent notifications are first\n (a, b) => b.notifiedAt.getTime() - a.notifiedAt.getTime()\n );\n}\n","const MAX_ERROR_RETRY_COUNT = 5;\n\nconst ERROR_RETRY_INTERVAL = 5000; // 5 seconds\n\n/**\n * Retries an action using the exponential backoff algorithm\n * @param action The action to retry\n * @param retryCount The number of times the action has been retried\n */\nexport function retryError(action: () => void, retryCount: number) {\n if (retryCount >= MAX_ERROR_RETRY_COUNT) return;\n\n const timeout = Math.pow(2, retryCount) * ERROR_RETRY_INTERVAL;\n\n setTimeout(() => {\n void action();\n }, timeout);\n}\n","import type { Reducer } from \"react\";\nimport { useCallback, useReducer } from \"react\";\n\nimport { useLatest } from \"./use-latest\";\n\nconst noop = <T>(state: T) => state;\n\n/**\n * \"Freezes\" a given value, so that it will return the same value/instance on\n * each subsequent render. This can be used to freeze \"initial\" values for\n * custom hooks, much like how `useState(initialState)` or\n * `useRef(initialValue)` works.\n */\nexport function useInitial<T>(value: T): T {\n // Equivalent to useState(() => value)[0], but slightly more low-level\n return useReducer<Reducer<T, unknown>>(noop, value)[0];\n}\n\n/**\n * Like `useInitial`, but if the provided value is a function instance, will\n * instead return a stable wrapper that _is_ a stable reference itself between\n * re-renders, but one which will always call the _latest_ provided callback\n * instance.\n */\nexport function useInitialUnlessFunction<T>(latestValue: T): T {\n const frozenValue = useInitial(latestValue);\n\n // Normally the Rules of Hooks™ dictate that you should not call hooks\n // conditionally. In this case, we're good here, because the same code path\n // will always be taken on every subsequent render here, because we've frozen\n // the value.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (typeof frozenValue === \"function\") {\n type Fn = T & ((...args: unknown[]) => unknown);\n const ref = useLatest(latestValue as Fn);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useCallback(((...args: unknown[]) => ref.current(...args)) as Fn, [\n ref,\n ]);\n } else {\n return frozenValue;\n }\n /* eslint-enable react-hooks/rules-of-hooks */\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Keeps a ref in sync with a given value that may or may not change on\n * every render.\n *\n * The purpose of this hook is to return a stable ref that can be passed\n * to a callback function so the callback can be registered but still can\n * access the latest value at a later point in time.\n */\nexport function useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n","import type { BaseMetadata, CommentBody, Patchable } from \"@liveblocks/core\";\n\nexport class CreateThreadError<M extends BaseMetadata> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n metadata: M;\n }\n ) {\n super(\"Create thread failed.\");\n this.name = \"CreateThreadError\";\n }\n}\n\nexport class EditThreadMetadataError<M extends BaseMetadata> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n metadata: Patchable<M>;\n }\n ) {\n super(\"Edit thread metadata failed.\");\n this.name = \"EditThreadMetadataError\";\n }\n}\n\nexport class CreateCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Create comment failed.\");\n this.name = \"CreateCommentError\";\n }\n}\n\nexport class EditCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Edit comment failed.\");\n this.name = \"EditCommentError\";\n }\n}\n\nexport class DeleteCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n }\n ) {\n super(\"Delete comment failed.\");\n this.name = \"DeleteCommentError\";\n }\n}\n\nexport class AddReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Add reaction failed.\");\n this.name = \"AddReactionError\";\n }\n}\n\nexport class RemoveReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Remove reaction failed.\");\n this.name = \"RemoveReactionError\";\n }\n}\n\nexport class MarkInboxNotificationAsReadError extends Error {\n constructor(\n public cause: Error,\n public context: {\n inboxNotificationId: string;\n }\n ) {\n super(\"Mark inbox notification as read failed.\");\n this.name = \"MarkInboxNotificationAsReadError\";\n }\n}\n\nexport class UpdateNotificationSettingsError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n }\n ) {\n super(\"Update notification settings failed.\");\n this.name = \"UpdateNotificationSettingsError\";\n }\n}\n\nexport type CommentsError<M extends BaseMetadata> =\n | CreateThreadError<M>\n | EditThreadMetadataError<M>\n | CreateCommentError\n | EditCommentError\n | DeleteCommentError\n | MarkInboxNotificationAsReadError\n | UpdateNotificationSettingsError;\n","import {\n applyOptimisticUpdates,\n type BaseMetadata,\n type CacheState,\n type ThreadData,\n} from \"@liveblocks/core\";\n\nimport type { UseThreadsOptions } from \"../../types\";\n\nexport function selectedThreads<M extends BaseMetadata>(\n roomId: string,\n state: CacheState<M>,\n options: UseThreadsOptions<M>\n): ThreadData<M>[] {\n const result = applyOptimisticUpdates(state);\n\n // Filter threads to only include the non-deleted threads from the specified room and that match the specified filter options\n const threads = Object.values(result.threads).filter<ThreadData<M>>(\n (thread): thread is ThreadData<M> => {\n if (thread.roomId !== roomId) return false;\n\n // We do not want to include threads that have been marked as deleted\n if (thread.deletedAt !== undefined) {\n return false;\n }\n\n const query = options.query;\n if (!query) return true;\n\n for (const key in query.metadata) {\n const metadataValue = thread.metadata[key];\n const filterValue = query.metadata[key];\n\n if (\n assertFilterIsStartsWithOperator(filterValue) &&\n assertMetadataValueIsString(metadataValue)\n ) {\n if (metadataValue.startsWith(filterValue.startsWith)) {\n return true;\n }\n }\n\n if (metadataValue !== filterValue) {\n return false;\n }\n }\n\n return true;\n }\n );\n\n // Sort threads by creation date (oldest first)\n return threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n}\n\nconst assertFilterIsStartsWithOperator = (\n filter: boolean | string | number | undefined | { startsWith: string }\n): filter is { startsWith: string } => {\n if (typeof filter === \"object\" && typeof filter.startsWith === \"string\") {\n return true;\n } else {\n return false;\n }\n};\n\nconst assertMetadataValueIsString = (value: any): value is string => {\n return typeof value === \"string\";\n};\n","import type {\n BaseMetadata,\n BaseUserMeta,\n BroadcastOptions,\n Client,\n History,\n Json,\n JsonObject,\n LiveObject,\n LostConnectionEvent,\n LsonObject,\n OthersEvent,\n Room,\n Status,\n User,\n} from \"@liveblocks/client\";\nimport { shallow } from \"@liveblocks/client\";\nimport type {\n CacheState,\n CacheStore,\n CommentData,\n CommentsEventServerMsg,\n DE,\n DM,\n DP,\n DS,\n DU,\n EnterOptions,\n LiveblocksError,\n OpaqueClient,\n OpaqueRoom,\n PrivateRoomApi,\n RoomEventMessage,\n RoomNotificationSettings,\n ThreadData,\n ToImmutable,\n} from \"@liveblocks/core\";\nimport {\n addReaction,\n CommentsApiError,\n console,\n deleteComment,\n deprecateIf,\n errorIf,\n kInternal,\n makeEventSource,\n makePoller,\n NotificationsApiError,\n removeReaction,\n ServerMsgCode,\n stringify,\n upsertComment,\n} from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport * as React from \"react\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport {\n AddReactionError,\n type CommentsError,\n CreateCommentError,\n CreateThreadError,\n DeleteCommentError,\n EditCommentError,\n EditThreadMetadataError,\n MarkInboxNotificationAsReadError,\n RemoveReactionError,\n UpdateNotificationSettingsError,\n} from \"./comments/errors\";\nimport { createCommentId, createThreadId } from \"./comments/lib/createIds\";\nimport { selectNotificationSettings } from \"./comments/lib/select-notification-settings\";\nimport { selectedInboxNotifications } from \"./comments/lib/selected-inbox-notifications\";\nimport { selectedThreads } from \"./comments/lib/selected-threads\";\nimport { retryError } from \"./lib/retry-error\";\nimport { useInitial } from \"./lib/use-initial\";\nimport { useLatest } from \"./lib/use-latest\";\nimport {\n createSharedContext,\n LiveblocksProviderWithClient,\n useClient,\n useClientOrNull,\n} from \"./liveblocks\";\nimport type {\n CommentReactionOptions,\n CreateCommentOptions,\n CreateThreadOptions,\n DeleteCommentOptions,\n EditCommentOptions,\n EditThreadMetadataOptions,\n MutationContext,\n OmitFirstArg,\n RoomContextBundle,\n RoomNotificationSettingsState,\n RoomNotificationSettingsStateSuccess,\n RoomProviderProps,\n ThreadsState,\n ThreadsStateSuccess,\n ThreadSubscription,\n UseThreadsOptions,\n} from \"./types\";\nimport { useScrollToCommentOnLoadEffect } from \"./use-scroll-to-comment-on-load-effect\";\n\nconst noop = () => {};\nconst identity: <T>(x: T) => T = (x) => x;\n\nconst missing_unstable_batchedUpdates = (\n reactVersion: number,\n roomId: string\n) =>\n `We noticed you’re using React ${reactVersion}. Please pass unstable_batchedUpdates at the RoomProvider level until you’re ready to upgrade to React 18:\n\n import { unstable_batchedUpdates } from \"react-dom\"; // or \"react-native\"\n\n <RoomProvider id=${JSON.stringify(\n roomId\n )} ... unstable_batchedUpdates={unstable_batchedUpdates}>\n ...\n </RoomProvider>\n\nWhy? Please see https://liveblocks.io/docs/platform/troubleshooting#stale-props-zombie-child for more information`;\n\nconst superfluous_unstable_batchedUpdates =\n \"You don’t need to pass unstable_batchedUpdates to RoomProvider anymore, since you’re on React 18+ already.\";\n\nfunction useSyncExternalStore<Snapshot>(\n s: (onStoreChange: () => void) => () => void,\n gs: () => Snapshot,\n gss: undefined | null | (() => Snapshot)\n): Snapshot {\n return useSyncExternalStoreWithSelector(s, gs, gss, identity);\n}\n\nconst STABLE_EMPTY_LIST = Object.freeze([]);\n\nexport const POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes\n\nfunction makeNotificationSettingsQueryKey(roomId: string) {\n return `${roomId}:NOTIFICATION_SETTINGS`;\n}\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysEmptyList() {\n return STABLE_EMPTY_LIST;\n}\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysNull() {\n return null;\n}\n\nfunction selectorFor_useOthersConnectionIds(\n others: readonly User<JsonObject, BaseUserMeta>[]\n): number[] {\n return others.map((user) => user.connectionId);\n}\n\nfunction makeMutationContext<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(room: Room<P, S, U, E, M>): MutationContext<P, S, U> {\n const cannotUseUntil = \"This mutation cannot be used until\";\n const needsPresence = `${cannotUseUntil} connected to the Liveblocks room`;\n const needsStorage = `${cannotUseUntil} storage has been loaded`;\n\n return {\n get storage() {\n const mutableRoot = room.getStorageSnapshot();\n if (mutableRoot === null) {\n throw new Error(needsStorage);\n }\n return mutableRoot;\n },\n\n get self() {\n const self = room.getSelf();\n if (self === null) {\n throw new Error(needsPresence);\n }\n return self;\n },\n\n get others() {\n const others = room.getOthers();\n if (room.getSelf() === null) {\n throw new Error(needsPresence);\n }\n return others;\n },\n\n setMyPresence: room.updatePresence,\n };\n}\n\nfunction getCurrentUserId(room: OpaqueRoom): string {\n const self = room.getSelf();\n if (self === null || self.id === undefined) {\n return \"anonymous\";\n } else {\n return self.id;\n }\n}\n\nfunction handleApiError(err: CommentsApiError | NotificationsApiError): Error {\n const message = `Request failed with status ${err.status}: ${err.message}`;\n\n // Log details about FORBIDDEN errors\n if (err.details?.error === \"FORBIDDEN\") {\n const detailedMessage = [message, err.details.suggestion, err.details.docs]\n .filter(Boolean)\n .join(\"\\n\");\n\n console.error(detailedMessage);\n }\n\n return new Error(message);\n}\n\nconst _extras = new WeakMap<\n OpaqueClient,\n ReturnType<typeof makeExtrasForClient>\n>();\nconst _bundles = new WeakMap<\n OpaqueClient,\n RoomContextBundle<JsonObject, LsonObject, BaseUserMeta, Json, BaseMetadata>\n>();\n\nfunction getOrCreateRoomContextBundle<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(client: OpaqueClient): RoomContextBundle<P, S, U, E, M> {\n let bundle = _bundles.get(client);\n if (!bundle) {\n bundle = makeRoomContextBundle(client);\n _bundles.set(client, bundle);\n }\n return bundle as unknown as RoomContextBundle<P, S, U, E, M>;\n}\n\n// TODO: Likely a better / more clear name for this helper will arise. I'll\n// rename this later. All of these are implementation details to support inbox\n// notifications on a per-client basis.\nfunction getExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n let extras = _extras.get(client);\n if (!extras) {\n extras = makeExtrasForClient(client);\n _extras.set(client, extras);\n }\n\n return extras as unknown as Omit<typeof extras, \"store\"> & {\n store: CacheStore<M>;\n };\n}\n\nfunction makeExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n const store = client[kInternal].cacheStore as unknown as CacheStore<M>;\n\n const DEFAULT_DEDUPING_INTERVAL = 2000; // 2 seconds\n\n const lastRequestedAtByRoom = new Map<string, Date>(); // A map of room ids to the timestamp when the last request for threads updates was made\n const requestsByQuery = new Map<string, Promise<unknown>>(); // A map of query keys to the promise of the request for that query\n const requestStatusByRoom = new Map<string, boolean>(); // A map of room ids to a boolean indicating whether a request to retrieve threads updates is in progress\n const subscribersByQuery = new Map<string, number>(); // A map of query keys to the number of subscribers for that query\n\n const poller = makePoller(refreshThreadsAndNotifications);\n\n async function refreshThreadsAndNotifications() {\n const requests: Promise<unknown>[] = [];\n\n client[kInternal].getRoomIds().map((roomId) => {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n // Retrieve threads that have been updated/deleted since the last requestedAt value\n requests.push(getThreadsUpdates(room.id));\n });\n\n await Promise.allSettled(requests);\n }\n\n function incrementQuerySubscribers(queryKey: string) {\n const subscribers = subscribersByQuery.get(queryKey) ?? 0;\n subscribersByQuery.set(queryKey, subscribers + 1);\n\n poller.start(POLLING_INTERVAL);\n\n // Decrement in the unsub function\n return () => {\n const subscribers = subscribersByQuery.get(queryKey);\n\n if (subscribers === undefined || subscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${queryKey}\"`\n );\n return;\n }\n\n subscribersByQuery.set(queryKey, subscribers - 1);\n\n let totalSubscribers = 0;\n for (const subscribers of subscribersByQuery.values()) {\n totalSubscribers += subscribers;\n }\n\n if (totalSubscribers <= 0) {\n poller.stop();\n }\n };\n }\n\n /**\n * Retrieve threads that have been updated/deleted since the last time the room requested threads updates and update the local cache with the new data\n * @param roomId The id of the room for which to retrieve threads updates\n */\n async function getThreadsUpdates(roomId: string) {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n const since = lastRequestedAtByRoom.get(room.id);\n if (since === undefined) return;\n\n const isFetchingThreadsUpdates = requestStatusByRoom.get(room.id) ?? false;\n // If another request to retrieve threads updates for the room is in progress, we do not start a new one\n if (isFetchingThreadsUpdates === true) return;\n\n try {\n // Set the isFetchingThreadsUpdates flag to true to prevent multiple requests to fetch threads updates for the room from being made at the same time\n requestStatusByRoom.set(room.id, true);\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n const updates = await commentsAPI.getThreads({ since });\n\n // Set the isFetchingThreadsUpdates flag to false after a certain interval to prevent multiple requests from being made at the same time\n setTimeout(() => {\n requestStatusByRoom.set(room.id, false);\n }, DEFAULT_DEDUPING_INTERVAL);\n\n store.updateThreadsAndNotifications(\n updates.threads,\n updates.inboxNotifications,\n updates.deletedThreads,\n updates.deletedInboxNotifications\n );\n\n // Update the `lastRequestedAt` value for the room to the timestamp returned by the current request\n lastRequestedAtByRoom.set(room.id, updates.meta.requestedAt);\n } catch (err) {\n requestStatusByRoom.set(room.id, false);\n // TODO: Implement error handling\n return;\n }\n }\n\n async function getThreadsAndInboxNotifications(\n room: OpaqueRoom,\n queryKey: string,\n options: UseThreadsOptions<M>,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the query, we do not make another request and return the existing promise of the request\n if (existingRequest !== undefined) return existingRequest;\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n const request = commentsAPI.getThreads(options);\n\n // Store the promise of the request for the query so that we do not make another request for the same query\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n try {\n const result = await request;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n queryKey\n );\n\n const lastRequestedAt = lastRequestedAtByRoom.get(room.id);\n\n /**\n * We set the `lastRequestedAt` value for the room to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt` value for the room has not been set\n * OR\n * 2. The `lastRequestedAt` value for the room is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAtByRoom.set(room.id, result.meta.requestedAt);\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n // Set the query state to the error state\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n }\n return;\n }\n\n async function getInboxNotificationSettings(\n room: OpaqueRoom,\n queryKey: string,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the notifications query, we do not make another request and return the existing promise\n if (existingRequest !== undefined) return existingRequest;\n\n try {\n const request =\n room[kInternal].notifications.getRoomNotificationSettings();\n\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n const settings = await request;\n store.updateRoomInboxNotificationSettings(room.id, settings, queryKey);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n retryError(() => {\n void getInboxNotificationSettings(room, queryKey, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n }\n return;\n }\n\n const commentsErrorEventSource = makeEventSource<CommentsError<M>>();\n\n function onMutationFailure(\n innerError: Error,\n optimisticUpdateId: string,\n createPublicError: (error: Error) => CommentsError<M>\n ) {\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n\n if (innerError instanceof CommentsApiError) {\n const error = handleApiError(innerError);\n commentsErrorEventSource.notify(createPublicError(error));\n return;\n }\n\n if (innerError instanceof NotificationsApiError) {\n handleApiError(innerError);\n // TODO: Create public error and notify via notificationsErrorEventSource?\n return;\n }\n\n throw innerError;\n }\n\n return {\n store,\n incrementQuerySubscribers,\n commentsErrorEventSource,\n getThreadsUpdates,\n getThreadsAndInboxNotifications,\n getInboxNotificationSettings,\n onMutationFailure,\n };\n}\n\ntype RoomLeavePair<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n> = {\n room: Room<P, S, U, E, M>;\n leave: () => void;\n};\n\nconst RoomContext = React.createContext<OpaqueRoom | null>(null);\n\nfunction makeRoomContextBundle<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(client: Client<U>): RoomContextBundle<P, S, U, E, M> {\n type TRoom = Room<P, S, U, E, M>;\n\n function RoomProvider_withImplicitLiveblocksProvider(\n props: RoomProviderProps<P, S>\n ) {\n return (\n <LiveblocksProviderWithClient client={client}>\n <RoomProvider {...props} />\n </LiveblocksProviderWithClient>\n );\n }\n\n const shared = createSharedContext<U>(client);\n\n const bundle: RoomContextBundle<P, S, U, E, M> = {\n RoomContext: RoomContext as React.Context<TRoom | null>,\n RoomProvider: RoomProvider_withImplicitLiveblocksProvider,\n\n useRoom,\n useStatus,\n\n useBatch,\n useBroadcastEvent,\n useOthersListener,\n useLostConnectionListener,\n useErrorListener,\n useEventListener,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n useStorageRoot,\n useStorage,\n\n useSelf,\n useMyPresence,\n useUpdateMyPresence,\n useOthers,\n useOthersMapped,\n useOthersConnectionIds,\n useOther,\n\n useMutation: useMutation as RoomContextBundle<P, S, U, E, M>[\"useMutation\"],\n\n useThreads,\n\n useCreateThread,\n useEditThreadMetadata,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings,\n useUpdateRoomNotificationSettings,\n\n ...shared.classic,\n\n suspense: {\n RoomContext: RoomContext as React.Context<TRoom | null>,\n RoomProvider: RoomProvider_withImplicitLiveblocksProvider,\n\n useRoom,\n useStatus,\n\n useBatch,\n useBroadcastEvent,\n useOthersListener,\n useLostConnectionListener,\n useErrorListener,\n useEventListener,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n useStorageRoot,\n useStorage: useStorageSuspense,\n\n useSelf: useSelfSuspense,\n useMyPresence,\n useUpdateMyPresence,\n useOthers: useOthersSuspense,\n useOthersMapped: useOthersMappedSuspense,\n useOthersConnectionIds: useOthersConnectionIdsSuspense,\n useOther: useOtherSuspense,\n\n useMutation: useMutation as RoomContextBundle<\n P,\n S,\n U,\n E,\n M\n >[\"suspense\"][\"useMutation\"],\n\n useThreads: useThreadsSuspense,\n\n useCreateThread,\n useEditThreadMetadata,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings: useRoomNotificationSettingsSuspense,\n useUpdateRoomNotificationSettings,\n\n ...shared.suspense,\n },\n\n useCommentsErrorListener,\n };\n\n return Object.defineProperty(bundle, kInternal, {\n enumerable: false,\n });\n}\n\nfunction RoomProvider<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(props: RoomProviderProps<P, S>) {\n const client = useClient<U>();\n const [cache] = React.useState(\n () => new Map<string, RoomLeavePair<P, S, U, E, M>>()\n );\n\n // Produce a version of client.enterRoom() that when called for the same\n // room ID multiple times, will not keep producing multiple leave\n // functions, but instead return the cached one.\n const stableEnterRoom = React.useCallback(\n (\n roomId: string,\n options: EnterOptions<P, S>\n ): RoomLeavePair<P, S, U, E, M> => {\n const cached = cache.get(roomId);\n if (cached) return cached;\n\n const rv = client.enterRoom<P, S, E, M>(roomId, options);\n\n // Wrap the leave function to also delete the cached value\n const origLeave = rv.leave;\n rv.leave = () => {\n origLeave();\n cache.delete(roomId);\n };\n\n cache.set(roomId, rv);\n return rv;\n },\n [client, cache]\n );\n\n //\n // RATIONALE:\n // At the \"Outer\" RoomProvider level, we keep a cache and produce\n // a stableEnterRoom function, which we pass down to the real \"Inner\"\n // RoomProvider level.\n //\n // The purpose is to ensure that if `stableEnterRoom(\"my-room\")` is called\n // multiple times for the same room ID, it will always return the exact same\n // (cached) value, so that in total only a single \"leave\" function gets\n // produced and registered in the client.\n //\n // If we didn't use this cache, then in React StrictMode\n // stableEnterRoom(\"my-room\") might get called multiple (at least 4) times,\n // causing more leave functions to be produced in the client, some of which\n // we cannot get a hold on (because StrictMode would discard those results by\n // design). This would make it appear to the Client that the Room is still in\n // use by some party that hasn't called `leave()` on it yet, thus causing the\n // Room to not be freed and destroyed when the component unmounts later.\n //\n return <RoomProviderInner {...props} stableEnterRoom={stableEnterRoom} />;\n}\n\n/** @internal */\nfunction RoomProviderInner<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(\n props: RoomProviderProps<P, S> & {\n stableEnterRoom: (\n roomId: string,\n options: EnterOptions<P, S>\n ) => RoomLeavePair<P, S, U, E, M>;\n }\n) {\n const client = useClient();\n const { id: roomId, stableEnterRoom } = props;\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!roomId) {\n throw new Error(\n \"RoomProvider id property is required. For more information: https://liveblocks.io/docs/errors/liveblocks-react/RoomProvider-id-property-is-required\"\n );\n }\n\n if (typeof roomId !== \"string\") {\n throw new Error(\"RoomProvider id property should be a string.\");\n }\n\n const majorReactVersion = parseInt(React.version) || 1;\n const oldReactVersion = majorReactVersion < 18;\n errorIf(\n oldReactVersion && props.unstable_batchedUpdates === undefined,\n missing_unstable_batchedUpdates(majorReactVersion, roomId)\n );\n deprecateIf(\n !oldReactVersion && props.unstable_batchedUpdates !== undefined,\n superfluous_unstable_batchedUpdates\n );\n }\n\n // Note: We'll hold on to the initial value given here, and ignore any\n // changes to this argument in subsequent renders\n const frozenProps = useInitial({\n initialPresence: props.initialPresence,\n initialStorage: props.initialStorage,\n unstable_batchedUpdates: props.unstable_batchedUpdates,\n autoConnect: props.autoConnect ?? typeof window !== \"undefined\",\n });\n\n const [{ room }, setRoomLeavePair] = React.useState(() =>\n stableEnterRoom(roomId, {\n ...frozenProps,\n autoConnect: false, // Deliberately using false here on the first render, see below\n })\n );\n\n React.useEffect(() => {\n const { store } = getExtrasForClient(client);\n\n async function handleCommentEvent(message: CommentsEventServerMsg) {\n // TODO: Error handling\n const info = await room[kInternal].comments.getThread({\n threadId: message.threadId,\n });\n\n // If no thread info was returned (i.e., 404), we remove the thread and relevant inbox notifications from local cache.\n if (!info) {\n store.deleteThread(message.threadId);\n return;\n }\n const { thread, inboxNotification } = info;\n\n const existingThread = store.get().threads[message.threadId];\n\n switch (message.type) {\n case ServerMsgCode.COMMENT_EDITED:\n case ServerMsgCode.THREAD_METADATA_UPDATED:\n case ServerMsgCode.COMMENT_REACTION_ADDED:\n case ServerMsgCode.COMMENT_REACTION_REMOVED:\n case ServerMsgCode.COMMENT_DELETED:\n // If the thread doesn't exist in the local cache, we do not update it with the server data as an optimistic update could have deleted the thread locally.\n if (!existingThread) break;\n\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n case ServerMsgCode.COMMENT_CREATED:\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n default:\n break;\n }\n }\n\n return room.events.comments.subscribe(\n (message) => void handleCommentEvent(message)\n );\n }, [client, room]);\n\n React.useEffect(() => {\n const { getThreadsUpdates } = getExtrasForClient(client);\n // Retrieve threads that have been updated/deleted since the last time the room requested threads updates\n void getThreadsUpdates(room.id);\n }, [client, room.id]);\n\n /**\n * Subscribe to the 'online' event to fetch threads/notifications updates when the browser goes back online.\n */\n React.useEffect(() => {\n function handleIsOnline() {\n const { getThreadsUpdates } = getExtrasForClient(client);\n void getThreadsUpdates(room.id);\n }\n\n window.addEventListener(\"online\", handleIsOnline);\n return () => {\n window.removeEventListener(\"online\", handleIsOnline);\n };\n }, [client, room.id]);\n\n React.useEffect(() => {\n const pair = stableEnterRoom(roomId, frozenProps);\n\n setRoomLeavePair(pair);\n const { room, leave } = pair;\n\n // In React, it's important to start connecting to the room as an effect,\n // rather than doing this during the initial render. This means that\n // during the initial render (both on the server-side, and on the first\n // hydration on the client-side), the value of the `useStatus()` hook\n // will correctly be \"initial\", and transition to \"connecting\" as an\n // effect.\n if (frozenProps.autoConnect) {\n room.connect();\n }\n\n return () => {\n leave();\n };\n }, [roomId, frozenProps, stableEnterRoom]);\n\n return (\n <RoomContext.Provider value={room}>{props.children}</RoomContext.Provider>\n );\n}\n\nfunction useRoom<\n P extends JsonObject = DP,\n S extends LsonObject = DS,\n U extends BaseUserMeta = DU,\n E extends Json = DE,\n M extends BaseMetadata = DM,\n>(): Room<P, S, U, E, M> {\n const room = useRoomOrNull<P, S, U, E, M>();\n if (room === null) {\n throw new Error(\"RoomProvider is missing from the React tree.\");\n }\n return room;\n}\n\nfunction useStatus(): Status {\n const room = useRoom();\n const subscribe = room.events.status.subscribe;\n const getSnapshot = room.getStatus;\n const getServerSnapshot = room.getStatus;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\nfunction useBatch<T>(): (callback: () => T) => T {\n return useRoom().batch;\n}\n\nfunction useBroadcastEvent<E extends Json>(): (\n event: E,\n options?: BroadcastOptions\n) => void {\n const room = useRoom<never, never, never, E, never>();\n return React.useCallback(\n (\n event: E,\n options: BroadcastOptions = { shouldQueueEventIfNotReady: false }\n ) => {\n room.broadcastEvent(event, options);\n },\n [room]\n );\n}\n\nfunction useOthersListener<P extends JsonObject, U extends BaseUserMeta>(\n callback: (event: OthersEvent<P, U>) => void\n) {\n const room = useRoom<P, never, U, never, never>();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () => room.events.others.subscribe((event) => savedCallback.current(event)),\n [room, savedCallback]\n );\n}\n\nfunction useLostConnectionListener(\n callback: (event: LostConnectionEvent) => void\n): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () =>\n room.events.lostConnection.subscribe((event) =>\n savedCallback.current(event)\n ),\n [room, savedCallback]\n );\n}\n\nfunction useErrorListener(callback: (err: LiveblocksError) => void): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () => room.events.error.subscribe((e) => savedCallback.current(e)),\n [room, savedCallback]\n );\n}\n\nfunction useEventListener<\n P extends JsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>(callback: (data: RoomEventMessage<P, U, E>) => void): void {\n const room = useRoom<P, never, U, E, never>();\n const savedCallback = useLatest(callback);\n React.useEffect(() => {\n const listener = (eventData: RoomEventMessage<P, U, E>) => {\n savedCallback.current(eventData);\n };\n\n return room.events.customEvent.subscribe(listener);\n }, [room, savedCallback]);\n}\n\nfunction useHistory(): History {\n return useRoom().history;\n}\n\nfunction useUndo(): () => void {\n return useHistory().undo;\n}\n\nfunction useRedo(): () => void {\n return useHistory().redo;\n}\n\nfunction useCanUndo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canUndo = room.history.canUndo;\n return useSyncExternalStore(subscribe, canUndo, canUndo);\n}\n\nfunction useCanRedo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canRedo = room.history.canRedo;\n return useSyncExternalStore(subscribe, canRedo, canRedo);\n}\n\nfunction useSelf<P extends JsonObject, U extends BaseUserMeta>(): User<\n P,\n U\n> | null;\nfunction useSelf<P extends JsonObject, U extends BaseUserMeta, T>(\n selector: (me: User<P, U>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n): T | null;\nfunction useSelf<P extends JsonObject, U extends BaseUserMeta, T>(\n maybeSelector?: (me: User<P, U>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n): T | User<P, U> | null {\n type Snapshot = User<P, U> | null;\n type Selection = T | null;\n\n const room = useRoom<P, never, U, never, never>();\n const subscribe = room.events.self.subscribe;\n const getSnapshot: () => Snapshot = room.getSelf;\n\n const selector = maybeSelector ?? (identity as (me: User<P, U>) => T);\n const wrappedSelector = React.useCallback(\n (me: Snapshot): Selection => (me !== null ? selector(me) : null),\n [selector]\n );\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n}\n\nfunction useMyPresence<P extends JsonObject>(): [\n P,\n (patch: Partial<P>, options?: { addToHistory: boolean }) => void,\n] {\n const room = useRoom<P, never, never, never, never>();\n const subscribe = room.events.myPresence.subscribe;\n const getSnapshot = room.getPresence;\n const presence = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setPresence = room.updatePresence;\n return [presence, setPresence];\n}\n\nfunction useUpdateMyPresence<P extends JsonObject>(): (\n patch: Partial<P>,\n options?: { addToHistory: boolean }\n) => void {\n return useRoom<P, never, never, never, never>().updatePresence;\n}\n\nfunction useOthers<\n P extends JsonObject,\n U extends BaseUserMeta,\n>(): readonly User<P, U>[];\nfunction useOthers<P extends JsonObject, U extends BaseUserMeta, T>(\n selector: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T;\nfunction useOthers<P extends JsonObject, U extends BaseUserMeta, T>(\n selector?: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T | readonly User<P, U>[] {\n const room = useRoom<P, never, U, never, never>();\n const subscribe = room.events.others.subscribe;\n const getSnapshot = room.getOthers;\n const getServerSnapshot = alwaysEmptyList;\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n selector ?? (identity as (others: readonly User<P, U>[]) => T),\n isEqual\n );\n}\n\nfunction useOthersMapped<P extends JsonObject, U extends BaseUserMeta, T>(\n itemSelector: (other: User<P, U>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n): ReadonlyArray<readonly [connectionId: number, data: T]> {\n const wrappedSelector = React.useCallback(\n (others: readonly User<P, U>[]) =>\n others.map((other) => [other.connectionId, itemSelector(other)] as const),\n [itemSelector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (\n a: ReadonlyArray<readonly [connectionId: number, data: T]>,\n b: ReadonlyArray<readonly [connectionId: number, data: T]>\n ): boolean => {\n const eq = itemIsEqual ?? Object.is;\n return (\n a.length === b.length &&\n a.every((atuple, index) => {\n // We know btuple always exist because we checked the array length on the previous line\n const btuple = b[index];\n return atuple[0] === btuple[0] && eq(atuple[1], btuple[1]);\n })\n );\n },\n [itemIsEqual]\n );\n\n return useOthers(wrappedSelector, wrappedIsEqual);\n}\n\nfunction useOthersConnectionIds(): readonly number[] {\n return useOthers(selectorFor_useOthersConnectionIds, shallow);\n}\n\nconst NOT_FOUND = Symbol();\n\ntype NotFound = typeof NOT_FOUND;\n\nfunction useOther<P extends JsonObject, U extends BaseUserMeta, T>(\n connectionId: number,\n selector: (other: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T {\n const wrappedSelector = React.useCallback(\n (others: readonly User<P, U>[]) => {\n // TODO: Make this O(1) instead of O(n)?\n const other = others.find((other) => other.connectionId === connectionId);\n return other !== undefined ? selector(other) : NOT_FOUND;\n },\n [connectionId, selector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (prev: T | NotFound, curr: T | NotFound): boolean => {\n if (prev === NOT_FOUND || curr === NOT_FOUND) {\n return prev === curr;\n }\n\n const eq = isEqual ?? Object.is;\n return eq(prev, curr);\n },\n [isEqual]\n );\n\n const other = useOthers(wrappedSelector, wrappedIsEqual);\n if (other === NOT_FOUND) {\n throw new Error(\n `No such other user with connection id ${connectionId} exists`\n );\n }\n\n return other;\n}\n\n/** @internal */\nfunction useMutableStorageRoot<S extends LsonObject>(): LiveObject<S> | null {\n const room = useRoom<never, S, never, never, never>();\n const subscribe = room.events.storageDidLoad.subscribeOnce;\n const getSnapshot = room.getStorageSnapshot;\n const getServerSnapshot = alwaysNull;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\n// NOTE: This API exists for backward compatible reasons\nfunction useStorageRoot<S extends LsonObject>(): [root: LiveObject<S> | null] {\n return [useMutableStorageRoot<S>()];\n}\n\nfunction useStorage<S extends LsonObject, T>(\n selector: (root: ToImmutable<S>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n): T | null {\n type Snapshot = ToImmutable<S> | null;\n type Selection = T | null;\n\n const room = useRoom<never, S, never, never, never>();\n const rootOrNull = useMutableStorageRoot<S>();\n\n const wrappedSelector = React.useCallback(\n (rootOrNull: Snapshot): Selection =>\n rootOrNull !== null ? selector(rootOrNull) : null,\n [selector]\n );\n\n const subscribe = React.useCallback(\n (onStoreChange: () => void) =>\n rootOrNull !== null\n ? room.subscribe(rootOrNull, onStoreChange, { isDeep: true })\n : noop,\n [room, rootOrNull]\n );\n\n const getSnapshot = React.useCallback((): Snapshot => {\n if (rootOrNull === null) {\n return null;\n } else {\n const root = rootOrNull;\n const imm = root.toImmutable();\n return imm;\n }\n }, [rootOrNull]);\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n}\n\nfunction useMutation<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n F extends (context: MutationContext<P, S, U>, ...args: any[]) => any,\n>(callback: F, deps: readonly unknown[]): OmitFirstArg<F> {\n const room = useRoom<P, S, U, E, M>();\n return React.useMemo(\n () => {\n return ((...args) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n room.batch(() =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n callback(\n makeMutationContext<P, S, U, E, M>(room),\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args\n )\n )) as OmitFirstArg<F>;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [room, ...deps]\n );\n}\n\nfunction useThreads<M extends BaseMetadata>(\n options: UseThreadsOptions<M> = {\n query: { metadata: {} },\n }\n): ThreadsState<M> {\n const { scrollOnLoad = true } = options;\n const client = useClient();\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n const { store, getThreadsAndInboxNotifications, incrementQuerySubscribers } =\n getExtrasForClient<M>(client);\n\n React.useEffect(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options);\n return incrementQuerySubscribers(queryKey);\n }, [room, queryKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const selector = React.useCallback(\n (state: CacheState<M>): ThreadsState<M> => {\n const query = state.queries[queryKey];\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n return {\n threads: selectedThreads(room.id, state, options),\n isLoading: false,\n error: query.error,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n useScrollToCommentOnLoadEffect(scrollOnLoad, state);\n\n return state;\n}\n\nfunction useCommentsErrorListener<M extends BaseMetadata>(\n callback: (error: CommentsError<M>) => void\n) {\n const client = useClient();\n const savedCallback = useLatest(callback);\n const { commentsErrorEventSource } = getExtrasForClient<M>(client);\n\n React.useEffect(() => {\n return commentsErrorEventSource.subscribe(savedCallback.current);\n }, [savedCallback, commentsErrorEventSource]);\n}\n\nfunction useCreateThread<M extends BaseMetadata>(): (\n options: CreateThreadOptions<M>\n) => ThreadData<M> {\n const client = useClient();\n const room = useRoom();\n\n return React.useCallback(\n (options: CreateThreadOptions<M>): ThreadData<M> => {\n const body = options.body;\n const metadata = options.metadata ?? ({} as M);\n\n const threadId = createThreadId();\n const commentId = createCommentId();\n const createdAt = new Date();\n\n const newComment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n createdAt,\n type: \"comment\",\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n const newThread: ThreadData<M> = {\n id: threadId,\n type: \"thread\",\n createdAt,\n updatedAt: createdAt,\n roomId: room.id,\n metadata,\n comments: [newComment],\n };\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"create-thread\",\n thread: newThread,\n id: optimisticUpdateId,\n roomId: room.id,\n });\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n commentsAPI.createThread({ threadId, commentId, body, metadata }).then(\n (thread) => {\n store.set((state) => ({\n ...state,\n threads: {\n ...state.threads,\n [threadId]: thread,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateThreadError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n metadata,\n })\n )\n );\n\n return newThread;\n },\n [client, room]\n );\n}\n\nfunction useEditThreadMetadata<M extends BaseMetadata>() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (options: EditThreadMetadataOptions<M>): void => {\n if (!options.metadata) {\n return;\n }\n\n const threadId = options.threadId;\n const metadata = options.metadata;\n const updatedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"edit-thread-metadata\",\n metadata,\n id: optimisticUpdateId,\n threadId,\n updatedAt,\n });\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n commentsAPI.editThreadMetadata({ metadata, threadId }).then(\n (metadata) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n // If the thread has been deleted, we do not update the metadata\n if (existingThread.deletedAt !== undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n if (\n existingThread.updatedAt &&\n existingThread.updatedAt > updatedAt\n ) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: {\n ...existingThread,\n metadata,\n },\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditThreadMetadataError(error, {\n roomId: room.id,\n threadId,\n metadata,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useCreateComment(): (options: CreateCommentOptions) => CommentData {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, body }: CreateCommentOptions): CommentData => {\n const commentId = createCommentId();\n const createdAt = new Date();\n\n const comment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n type: \"comment\",\n createdAt,\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"create-comment\",\n comment,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .createComment({ threadId, commentId, body })\n .then(\n (newComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n const inboxNotification = Object.values(\n state.inboxNotifications\n ).find(\n (notification) =>\n notification.kind === \"thread\" &&\n notification.threadId === threadId\n );\n\n // If the thread has an inbox notification associated with it, we update the notification's `notifiedAt` and `readAt` values\n const updatedInboxNotifications =\n inboxNotification !== undefined\n ? {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n notifiedAt: newComment.createdAt,\n readAt: newComment.createdAt,\n },\n }\n : state.inboxNotifications;\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, newComment), // Upsert the new comment into the thread comments list (if applicable)\n },\n inboxNotifications: updatedInboxNotifications,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateCommentError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n\n return comment;\n },\n [client, room]\n );\n}\n\nfunction useEditComment(): (options: EditCommentOptions) => void {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, body }: EditCommentOptions): void => {\n const editedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n const thread = store.get().threads[threadId];\n if (thread === undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment in thread \"${threadId}\" because the thread does not exist in the cache.`\n );\n return;\n }\n\n const comment = thread.comments.find(\n (comment) => comment.id === commentId\n );\n\n if (comment === undefined || comment.deletedAt !== undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment \"${commentId}\" in thread \"${threadId}\" because the comment does not exist in the cache.`\n );\n return;\n }\n\n store.pushOptimisticUpdate({\n type: \"edit-comment\",\n comment: {\n ...comment,\n editedAt,\n body,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments.editComment({ threadId, commentId, body }).then(\n (editedComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, editedComment), // Upsert the edited comment into the thread comments list (if applicable)\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useDeleteComment() {\n const client = useClient();\n const room = useRoom();\n\n return React.useCallback(\n ({ threadId, commentId }: DeleteCommentOptions): void => {\n const deletedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"delete-comment\",\n threadId,\n commentId,\n deletedAt,\n id: optimisticUpdateId,\n roomId: room.id,\n });\n\n room[kInternal].comments.deleteComment({ threadId, commentId }).then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If thread does not exist, we return the existing state\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: deleteComment(existingThread, commentId, deletedAt),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new DeleteCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useAddReaction<M extends BaseMetadata>() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const createdAt = new Date();\n const userId = getCurrentUserId(room);\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient<M>(client);\n store.pushOptimisticUpdate({\n type: \"add-reaction\",\n threadId,\n commentId,\n reaction: {\n emoji,\n userId,\n createdAt,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments.addReaction({ threadId, commentId, emoji }).then(\n (addedReaction) => {\n store.set((state): CacheState<M> => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: addReaction(\n existingThread,\n commentId,\n addedReaction\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new AddReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useRemoveReaction() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const userId = getCurrentUserId(room);\n\n const removedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"remove-reaction\",\n threadId,\n commentId,\n emoji,\n userId,\n removedAt,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .removeReaction({ threadId, commentId, emoji })\n .then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: removeReaction(\n existingThread,\n commentId,\n emoji,\n userId,\n removedAt\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new RemoveReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useMarkThreadAsRead() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (threadId: string) => {\n const { store, onMutationFailure } = getExtrasForClient(client);\n const inboxNotification = Object.values(\n store.get().inboxNotifications\n ).find(\n (inboxNotification) =>\n inboxNotification.kind === \"thread\" &&\n inboxNotification.threadId === threadId\n );\n\n if (!inboxNotification) return;\n\n const optimisticUpdateId = nanoid();\n const now = new Date();\n\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId: inboxNotification.id,\n readAt: now,\n });\n\n room[kInternal].notifications\n .markInboxNotificationAsRead(inboxNotification.id)\n .then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n readAt: now,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) => {\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new MarkInboxNotificationAsReadError(error, {\n inboxNotificationId: inboxNotification.id,\n })\n );\n return;\n }\n );\n },\n [client, room]\n );\n}\n\nfunction useThreadSubscription(threadId: string): ThreadSubscription {\n const client = useClient();\n const { store } = getExtrasForClient(client);\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): ThreadSubscription => {\n const inboxNotification = selectedInboxNotifications(state).find(\n (inboxNotification) =>\n inboxNotification.kind === \"thread\" &&\n inboxNotification.threadId === threadId\n );\n\n const thread = state.threads[threadId];\n\n if (inboxNotification === undefined || thread === undefined) {\n return {\n status: \"not-subscribed\",\n };\n }\n\n return {\n status: \"subscribed\",\n unreadSince: inboxNotification.readAt,\n };\n },\n [threadId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n}\n\nfunction useRoomNotificationSettings(): [\n RoomNotificationSettingsState,\n (settings: Partial<RoomNotificationSettings>) => void,\n] {\n const client = useClient();\n const room = useRoom();\n const { store } = getExtrasForClient(client);\n\n React.useEffect(() => {\n const { getInboxNotificationSettings } = getExtrasForClient(client);\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n void getInboxNotificationSettings(room, queryKey);\n }, [client, room]);\n\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): RoomNotificationSettingsState => {\n const query = state.queries[makeNotificationSettingsQueryKey(room.id)];\n\n if (query === undefined || query.isLoading) {\n return { isLoading: true };\n }\n\n if (query.error !== undefined) {\n return { isLoading: false, error: query.error };\n }\n\n return {\n isLoading: false,\n settings: selectNotificationSettings(room.id, state),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n}\n\nfunction useUpdateRoomNotificationSettings() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (settings: Partial<RoomNotificationSettings>) => {\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n id: optimisticUpdateId,\n type: \"update-notification-settings\",\n roomId: room.id,\n settings,\n });\n\n room[kInternal].notifications\n .updateRoomNotificationSettings(settings)\n .then(\n (settings) => {\n store.set((state) => ({\n ...state,\n notificationSettings: {\n [room.id]: settings,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new UpdateNotificationSettingsError(error, {\n roomId: room.id,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction ensureNotServerSide(): void {\n // Error early if suspense is used in a server-side context\n if (typeof window === \"undefined\") {\n throw new Error(\n \"You cannot use the Suspense version of this hook on the server side. Make sure to only call them on the client side.\\nFor tips, see https://liveblocks.io/docs/api-reference/liveblocks-react#suspense-avoid-ssr\"\n );\n }\n}\n\nfunction useSuspendUntilPresenceLoaded(): void {\n const room = useRoom();\n if (room.getSelf() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until either\n // until either a presence update event, or a connection status change has\n // happened. After that, it will render this component tree again and\n // re-evaluate the .getSelf() condition above, or re-suspend again until\n // such event happens.\n throw new Promise<void>((res) => {\n room.events.self.subscribeOnce(() => res());\n room.events.status.subscribeOnce(() => res());\n });\n}\n\nfunction useSelfSuspense<P extends JsonObject, U extends BaseUserMeta>(): User<\n P,\n U\n>;\nfunction useSelfSuspense<P extends JsonObject, U extends BaseUserMeta, T>(\n selector: (me: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T;\nfunction useSelfSuspense<P extends JsonObject, U extends BaseUserMeta, T>(\n selector?: (me: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T | User<P, U> {\n useSuspendUntilPresenceLoaded();\n return useSelf(\n selector as (me: User<P, U>) => T,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T | User<P, U>;\n}\n\nfunction useOthersSuspense<\n P extends JsonObject,\n U extends BaseUserMeta,\n>(): readonly User<P, U>[];\nfunction useOthersSuspense<P extends JsonObject, U extends BaseUserMeta, T>(\n selector: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T;\nfunction useOthersSuspense<P extends JsonObject, U extends BaseUserMeta, T>(\n selector?: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T | readonly User<P, U>[] {\n useSuspendUntilPresenceLoaded();\n return useOthers(\n selector as (others: readonly User<P, U>[]) => T,\n isEqual as (prev: T, curr: T) => boolean\n ) as T | readonly User<P, U>[];\n}\n\nfunction useOthersConnectionIdsSuspense(): readonly number[] {\n useSuspendUntilPresenceLoaded();\n return useOthersConnectionIds();\n}\n\nfunction useOthersMappedSuspense<\n P extends JsonObject,\n U extends BaseUserMeta,\n T,\n>(\n itemSelector: (other: User<P, U>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n): ReadonlyArray<readonly [connectionId: number, data: T]> {\n useSuspendUntilPresenceLoaded();\n return useOthersMapped(itemSelector, itemIsEqual);\n}\n\nfunction useOtherSuspense<P extends JsonObject, U extends BaseUserMeta, T>(\n connectionId: number,\n selector: (other: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T {\n useSuspendUntilPresenceLoaded();\n return useOther(connectionId, selector, isEqual);\n}\n\nfunction useSuspendUntilStorageLoaded(): void {\n const room = useRoom();\n if (room.getStorageSnapshot() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until this\n // promise resolves (aka until storage has loaded). After that, it will\n // render this component tree again.\n throw new Promise<void>((res) => {\n room.events.storageDidLoad.subscribeOnce(() => res());\n });\n}\n\nfunction useStorageSuspense<S extends LsonObject, T>(\n selector: (root: ToImmutable<S>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T {\n useSuspendUntilStorageLoaded();\n return useStorage(\n selector,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T;\n}\n\nfunction useThreadsSuspense<M extends BaseMetadata>(\n options: UseThreadsOptions<M> = {\n query: { metadata: {} },\n }\n): ThreadsStateSuccess<M> {\n const { scrollOnLoad = true } = options;\n\n const client = useClient();\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n const { store, getThreadsAndInboxNotifications } =\n getExtrasForClient<M>(client);\n\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getThreadsAndInboxNotifications(room, queryKey, options);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (state: CacheState<M>): ThreadsStateSuccess<M> => {\n return {\n threads: selectedThreads(room.id, state, options),\n isLoading: false,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n React.useEffect(() => {\n const { incrementQuerySubscribers } = getExtrasForClient(client);\n return incrementQuerySubscribers(queryKey);\n }, [client, queryKey]);\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n useScrollToCommentOnLoadEffect(scrollOnLoad, state);\n\n return state;\n}\n\nfunction useRoomNotificationSettingsSuspense(): [\n RoomNotificationSettingsStateSuccess,\n (settings: Partial<RoomNotificationSettings>) => void,\n] {\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n const client = useClient();\n const room = useRoom();\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n\n const { store, getInboxNotificationSettings } = getExtrasForClient(client);\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getInboxNotificationSettings(room, queryKey);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): RoomNotificationSettingsStateSuccess => {\n return {\n isLoading: false,\n settings: selectNotificationSettings(room.id, state),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n}\n\n/** @internal */\nexport function useRoomOrNull<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(): Room<P, S, U, E, M> | null {\n return React.useContext(RoomContext) as Room<P, S, U, E, M> | null;\n}\n\n/**\n * @private\n *\n * This is an internal API, use `createRoomContext` instead.\n */\nexport function useRoomContextBundleOrNull() {\n const client = useClientOrNull();\n const room = useRoomOrNull<never, never, never, never, never>();\n return client && room ? getOrCreateRoomContextBundle(client) : null;\n}\n\n/**\n * @private\n *\n * This is an internal API, use `createRoomContext` instead.\n */\nexport function useRoomContextBundle() {\n const client = useClient();\n return getOrCreateRoomContextBundle(client);\n}\n\nexport function createRoomContext<\n P extends JsonObject = DP,\n S extends LsonObject = DS,\n U extends BaseUserMeta = DU,\n E extends Json = DE,\n M extends BaseMetadata = DM,\n>(client: OpaqueClient): RoomContextBundle<P, S, U, E, M> {\n return getOrCreateRoomContextBundle<P, S, U, E, M>(client);\n}\n\nexport function generateQueryKey(\n roomId: string,\n options: UseThreadsOptions<BaseMetadata>[\"query\"]\n) {\n return `${roomId}-${stringify(options ?? {})}`;\n}\n\ntype DefaultRoomContextBundle = RoomContextBundle<DP, DS, DU, DE, DM>;\n\nconst _RoomProvider: DefaultRoomContextBundle[\"RoomProvider\"] = RoomProvider;\nconst _useBroadcastEvent: DefaultRoomContextBundle[\"useBroadcastEvent\"] =\n useBroadcastEvent;\nconst _useOthersListener: DefaultRoomContextBundle[\"useOthersListener\"] =\n useOthersListener;\nconst _useRoom: DefaultRoomContextBundle[\"useRoom\"] = useRoom;\nconst _useAddReaction: DefaultRoomContextBundle[\"useAddReaction\"] =\n useAddReaction;\nconst _useMutation: DefaultRoomContextBundle[\"useMutation\"] = useMutation;\nconst _useCreateThread: DefaultRoomContextBundle[\"useCreateThread\"] =\n useCreateThread;\nconst _useEditThreadMetadata: DefaultRoomContextBundle[\"useEditThreadMetadata\"] =\n useEditThreadMetadata;\nconst _useEventListener: DefaultRoomContextBundle[\"useEventListener\"] =\n useEventListener;\nconst _useMyPresence: DefaultRoomContextBundle[\"useMyPresence\"] = useMyPresence;\nconst _useOthersMapped: DefaultRoomContextBundle[\"useOthersMapped\"] =\n useOthersMapped;\nconst _useOthersMappedSuspense: DefaultRoomContextBundle[\"suspense\"][\"useOthersMapped\"] =\n useOthersMappedSuspense;\nconst _useThreads: DefaultRoomContextBundle[\"useThreads\"] = useThreads;\nconst _useThreadsSuspense: DefaultRoomContextBundle[\"suspense\"][\"useThreads\"] =\n useThreadsSuspense;\nconst _useOther: DefaultRoomContextBundle[\"useOther\"] = useOther;\nconst _useOthers: DefaultRoomContextBundle[\"useOthers\"] = useOthers;\nconst _useOtherSuspense: DefaultRoomContextBundle[\"suspense\"][\"useOther\"] =\n useOtherSuspense;\nconst _useOthersSuspense: DefaultRoomContextBundle[\"suspense\"][\"useOthers\"] =\n useOthersSuspense;\nconst _useStorage: DefaultRoomContextBundle[\"useStorage\"] = useStorage;\nconst _useStorageSuspense: DefaultRoomContextBundle[\"suspense\"][\"useStorage\"] =\n useStorageSuspense;\nconst _useSelf: DefaultRoomContextBundle[\"useSelf\"] = useSelf;\nconst _useSelfSuspense: DefaultRoomContextBundle[\"suspense\"][\"useSelf\"] =\n useSelfSuspense;\nconst _useStorageRoot: DefaultRoomContextBundle[\"useStorageRoot\"] =\n useStorageRoot;\nconst _useUpdateMyPresence: DefaultRoomContextBundle[\"useUpdateMyPresence\"] =\n useUpdateMyPresence;\n\nexport {\n CreateThreadError,\n RoomContext,\n _RoomProvider as RoomProvider,\n _useAddReaction as useAddReaction,\n useBatch,\n _useBroadcastEvent as useBroadcastEvent,\n useCanRedo,\n useCanUndo,\n // TODO: Move to `liveblocks-react-lexical`\n useCommentsErrorListener,\n useCreateComment,\n _useCreateThread as useCreateThread,\n useDeleteComment,\n useEditComment,\n _useEditThreadMetadata as useEditThreadMetadata,\n useErrorListener,\n _useEventListener as useEventListener,\n useHistory,\n useLostConnectionListener,\n useMarkThreadAsRead,\n _useMutation as useMutation,\n _useMyPresence as useMyPresence,\n _useOther as useOther,\n _useOthers as useOthers,\n useOthersConnectionIds,\n useOthersConnectionIdsSuspense,\n _useOthersListener as useOthersListener,\n _useOthersMapped as useOthersMapped,\n _useOthersMappedSuspense as useOthersMappedSuspense,\n _useOthersSuspense as useOthersSuspense,\n _useOtherSuspense as useOtherSuspense,\n useRedo,\n useRemoveReaction,\n _useRoom as useRoom,\n useRoomNotificationSettings,\n _useSelf as useSelf,\n _useSelfSuspense as useSelfSuspense,\n useStatus,\n _useStorage as useStorage,\n _useStorageRoot as useStorageRoot,\n _useStorageSuspense as useStorageSuspense,\n _useThreads as useThreads,\n _useThreadsSuspense as useThreadsSuspense,\n useThreadSubscription,\n useUndo,\n _useUpdateMyPresence as useUpdateMyPresence,\n useUpdateRoomNotificationSettings,\n};\n","import { nanoid } from \"nanoid\";\n\nconst THREAD_ID_PREFIX = \"th\";\nconst COMMENT_ID_PREFIX = \"cm\";\nconst INBOX_NOTIFICATION_ID_PREFIX = \"in\";\n\nfunction createOptimisticId(prefix: string) {\n return `${prefix}_${nanoid()}`;\n}\n\nexport function createThreadId() {\n return createOptimisticId(THREAD_ID_PREFIX);\n}\n\nexport function createCommentId() {\n return createOptimisticId(COMMENT_ID_PREFIX);\n}\n\nexport function createInboxNotificationId() {\n return createOptimisticId(INBOX_NOTIFICATION_ID_PREFIX);\n}\n","import {\n applyOptimisticUpdates,\n type BaseMetadata,\n type CacheState,\n nn,\n type RoomNotificationSettings,\n} from \"@liveblocks/core\";\n\nexport function selectNotificationSettings<M extends BaseMetadata>(\n roomId: string,\n state: CacheState<M>\n): RoomNotificationSettings {\n const { notificationSettings } = applyOptimisticUpdates(state);\n return nn(notificationSettings[roomId]);\n}\n","import type { BaseMetadata } from \"@liveblocks/client\";\nimport * as React from \"react\";\n\nimport type { ThreadsState } from \"./types\";\n\nfunction handleScrollToCommentOnLoad(\n shouldScrollOnLoad: boolean,\n state: ThreadsState<BaseMetadata>\n) {\n if (shouldScrollOnLoad === false) return;\n\n if (state.isLoading) return;\n\n const isWindowDefined = typeof window !== \"undefined\";\n if (!isWindowDefined) return;\n\n const hash = window.location.hash;\n const commentId = hash.slice(1);\n\n // If the hash is not a comment ID, we do not scroll to it\n if (!commentId.startsWith(\"cm_\")) return;\n\n // If a comment with the ID does not exist in the DOM, we do not scroll to it\n const comment = document.getElementById(commentId);\n if (comment === null) return;\n\n const comments = state.threads.flatMap((thread) => thread.comments);\n const isCommentInThreads = comments.some(\n (comment) => comment.id === commentId\n );\n\n // If the comment is not in the threads for this hook, we do not scroll to it\n if (!isCommentInThreads) return;\n\n comment.scrollIntoView();\n}\n\n/**\n * Scroll to the comment with the ID in the hash of the URL based on whether\n * the query is loading and whether the hook should scroll to the comment on load.\n */\nexport function useScrollToCommentOnLoadEffect(\n shouldScrollOnLoad: boolean,\n state: ThreadsState<BaseMetadata>\n) {\n React.useEffect(\n () => {\n handleScrollToCommentOnLoad(shouldScrollOnLoad, state);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once\n [state.isLoading]\n );\n}\n"]}