{"version":3,"file":"ably-chat-react.umd.cjs","sources":["../../src/react/contexts/chat-room-context.tsx","../../src/core/connection.ts","../../src/core/errors.ts","../../src/react/contexts/chat-client-context.tsx","../../node_modules/dequal/dist/index.mjs","../../src/react/helper/room-reference-manager.ts","../../src/react/hooks/internal/use-room-reference-manager.ts","../../src/react/providers/chat-client-provider.tsx","../../src/react/hooks/internal/use-chat-client-context.ts","../../src/react/hooks/internal/use-room-context.ts","../../src/react/hooks/internal/use-logger.ts","../../src/react/hooks/use-chat-client.ts","../../src/react/hooks/internal/use-event-listener-ref.ts","../../src/react/hooks/use-chat-connection.ts","../../src/react/helper/room-promise.ts","../../src/core/room-status.ts","../../src/react/hooks/internal/use-room-status.ts","../../src/react/hooks/use-messages.ts","../../src/react/hooks/use-occupancy.ts","../../src/react/hooks/use-presence.ts","../../src/react/hooks/use-presence-listener.ts","../../src/react/hooks/use-room.ts","../../src/react/hooks/use-room-reactions.ts","../../src/react/hooks/use-typing.ts","../../src/react/providers/chat-room-provider.tsx"],"sourcesContent":["import { createContext } from 'react';\n\nimport { ChatClient } from '../../core/chat-client.js';\nimport { Room } from '../../core/room.js';\nimport { RoomOptions } from '../../core/room-options.js';\n\n/**\n * Data type for {@link ChatRoomContext}.\n */\nexport interface ChatRoomContextType {\n  /**\n   * Promise that resolves to the chat room.\n   */\n  room: Promise<Room>;\n\n  /**\n   * The unique identifier of the room that promise will resolve to.\n   */\n  roomName: string;\n\n  /**\n   * Options used to create the room.\n   */\n  options?: RoomOptions;\n\n  /**\n   * The chat client used to create the room.\n   */\n  client: ChatClient;\n}\n\n/**\n * React Context for sharing chat room instances across component trees.\n *\n * **Note**: This context should not be used directly.\n * Use {@link ChatRoomProvider} to provide room context and room-specific hooks to consume it.\n */\nexport const ChatRoomContext = createContext<ChatRoomContextType | undefined>(undefined);\n","import * as Ably from '@ably/pubsub-core';\n\nimport { Logger } from './logger.js';\nimport { on } from './realtime-subscriptions.js';\nimport { StatusSubscription } from './subscription.js';\nimport EventEmitter, { emitterHasListeners, wrap } from './utils/event-emitter.js';\n\n/**\n * The different states that the connection can be in through its lifecycle.\n */\nexport enum ConnectionStatus {\n  /**\n   * A temporary state for when the library is first initialized.\n   */\n  Initialized = 'initialized',\n\n  /**\n   * The library is currently connecting to Ably.\n   */\n  Connecting = 'connecting',\n\n  /**\n   * The library is currently connected to Ably.\n   */\n  Connected = 'connected',\n\n  /**\n   * The library is currently disconnected from Ably, but will attempt to reconnect.\n   */\n  Disconnected = 'disconnected',\n\n  /**\n   * The library is in an extended state of disconnection, but will attempt to reconnect.\n   */\n  Suspended = 'suspended',\n\n  /**\n   * The library is currently disconnected from Ably and will not attempt to reconnect.\n   */\n  Failed = 'failed',\n\n  /**\n   * An explicit request by the developer to close the connection has been sent to the Ably service.\n   * If a reply is not received from Ably within a short period of time, the connection is forcibly\n   * terminated and the connection status becomes Closed.\n   */\n  Closing = 'closing',\n\n  /**\n   * The connection has been explicitly closed by the client. In the closed state, no reconnection\n   * attempts are made automatically. No connection state is preserved by the service or the library.\n   */\n  Closed = 'closed',\n}\n\n/**\n * Represents a change in the status of the connection.\n */\nexport interface ConnectionStatusChange {\n  /**\n   * The new status of the connection.\n   */\n  current: ConnectionStatus;\n\n  /**\n   * The previous status of the connection.\n   */\n  previous: ConnectionStatus;\n\n  /**\n   * An error that provides a reason why the connection has\n   * entered the new status, if applicable.\n   */\n  error?: Ably.ErrorInfo;\n\n  /**\n   * The time in milliseconds that the client will wait before attempting to reconnect.\n   */\n  retryIn?: number;\n}\n\n/**\n * A function that can be called when the connection status changes.\n * @param change The change in status.\n */\nexport type ConnectionStatusListener = (change: ConnectionStatusChange) => void;\n\n/**\n * Represents a connection to Ably.\n */\nexport interface Connection {\n  /**\n   * The current status of the connection.\n   * @returns The current ConnectionStatus value\n   * @example\n   * ```typescript\n   * import { ChatClient, ConnectionStatus } from '@ably/chat';\n   *\n   * const chatClient: ChatClient; // existing ChatClient instance\n   *\n   * // Check connection status\n   * if (chatClient.connection.status === ConnectionStatus.Connected) {\n   *   console.log('Connected to Ably');\n   * } else if (chatClient.connection.status === ConnectionStatus.Failed) {\n   *   console.error('Connection failed');\n   * }\n   *\n   * // Use status for conditional logic\n   * function canAttachToRoom(): boolean {\n   *   return chatClient.connection.status === ConnectionStatus.Connected;\n   * }\n   * ```\n   */\n  get status(): ConnectionStatus;\n\n  /**\n   * The error that caused the connection to enter its current status, if any.\n   * @returns ErrorInfo if an error caused the current status, undefined otherwise\n   * @example\n   * ```typescript\n   * import { ChatClient, ConnectionStatus } from '@ably/chat';\n   *\n   * const chatClient: ChatClient; // existing ChatClient instance\n   *\n   * // Check for connection errors\n   * if (chatClient.connection.error) {\n   *   console.error('Connection error:', chatClient.connection.error.message);\n   *   console.error('Error code:', chatClient.connection.error.code);\n   * }\n   * // Monitor for errors during status changes\n   * chatClient.connection.onStatusChange((change) => {\n   *   if (change.error) {\n   *     reportErrorToMonitoring(change.error);\n   *   }\n   * });\n   * ```\n   */\n  get error(): Ably.ErrorInfo | undefined;\n\n  /**\n   * Registers a listener to be notified of connection status changes.\n   *\n   * Status changes indicate the connection lifecycle, including connecting,\n   * connected, disconnected, suspended, and failed states. Use this to monitor\n   * connection health and handle network issues.\n   * @param listener - Callback invoked when the connection status changes\n   * @returns Subscription object with an off method to unregister\n   * @example\n   * ```typescript\n   * import * as Ably from '@ably/pubsub-device';\n   * import { ChatClient, ConnectionStatus } from '@ably/chat';\n   *\n   * const chatClient: ChatClient; // existing ChatClient instance\n   *\n   * // Monitor connection status changes\n   * const { off } = chatClient.connection.onStatusChange((change) => {\n   *   console.log(`Connection: ${change.previous} -> ${change.current}`);\n   *\n   *   // Handle different connection states..\n   *   switch (change.current) {\n   *     case ConnectionStatus.Connected:\n   *       console.log('✅ Connected to Ably');\n   *       enableChatFeatures();\n   *       hideConnectionWarning();\n   *       break;\n   *\n   *     case ConnectionStatus.Failed:\n   *       console.error('❌ Connection failed permanently');\n   *       if (change.error) {\n   *         console.error('Failure reason:', change.error.message);\n   *         showErrorMessage(`Connection failed: ${change.error.message}`);\n   *       }\n   *       requireManualReconnection();\n   *       break;\n   *\n   *     // Other states: Connecting, Disconnected, Suspended\n   *   }\n   * });\n   *\n   * // Clean up when done\n   * off();\n   * ```\n   */\n  onStatusChange(listener: ConnectionStatusListener): StatusSubscription;\n}\n\n/**\n * An internal interface for the connection with additional methods.\n */\nexport interface InternalConnection extends Connection {\n  /**\n   * Disposes of the connection instance, cleaning up any registered listeners.\n   * This method should be called when the connection is no longer needed.\n   * @internal\n   */\n  dispose(): void;\n}\n\ntype ConnectionEventsMap = Record<ConnectionStatus, ConnectionStatusChange>;\n\n/**\n * An implementation of the `Connection` interface.\n * @internal\n */\nexport class DefaultConnection implements InternalConnection {\n  private _status: ConnectionStatus = ConnectionStatus.Initialized;\n  private _error?: Ably.ErrorInfo;\n  private readonly _logger: Logger;\n  private _emitter = new EventEmitter<ConnectionEventsMap>();\n  private readonly _clearAblyConnectionListener: () => void;\n\n  /**\n   * Constructs a new `DefaultConnection` instance.\n   * @param ably The Ably Realtime client.\n   * @param logger The logger to use.\n   */\n  constructor(ably: Ably.PubSubRealtimeClient, logger: Logger) {\n    this._logger = logger;\n\n    // Set our initial status and error\n    // CHA-RS5\n    this._status = this._mapAblyStatusToChat(ably.connection.state);\n    this._error = ably.connection.errorReason;\n\n    // Store the listener function so we can dispose of it later\n    const connectionListener = (change: Ably.ConnectionStateChange) => {\n      const chatState = this._mapAblyStatusToChat(change.current);\n      if (chatState === this._status) {\n        return;\n      }\n\n      const stateChange: ConnectionStatusChange = {\n        current: chatState,\n        previous: this._status,\n        error: change.reason,\n        retryIn: change.retryIn,\n      };\n\n      this._applyStatusChange(stateChange);\n    };\n\n    // Use subscription helper to create cleanup function\n    this._clearAblyConnectionListener = on(ably.connection, connectionListener);\n  }\n\n  /**\n   * @inheritdoc\n   */\n  get status(): ConnectionStatus {\n    return this._status;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  get error(): Ably.ErrorInfo | undefined {\n    return this._error;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  onStatusChange(listener: ConnectionStatusListener): StatusSubscription {\n    const wrapped = wrap(listener);\n    this._emitter.on(wrapped);\n\n    return {\n      off: () => {\n        this._emitter.off(wrapped);\n      },\n    };\n  }\n\n  /**\n   * @inheritdoc\n   */\n  dispose(): void {\n    this._logger.trace('DefaultConnection.dispose();');\n    // Remove the connection state listener from the Ably connection\n    this._clearAblyConnectionListener();\n    // Clear all listeners from the internal emitter\n    this._emitter.off();\n  }\n\n  /**\n   * Checks if there are any listeners registered on the connection.\n   * @internal\n   * @returns true if there are listeners, false otherwise.\n   */\n  hasListeners(): boolean {\n    return emitterHasListeners(this._emitter);\n  }\n\n  private _applyStatusChange(change: ConnectionStatusChange): void {\n    this._status = change.current;\n    this._error = change.error;\n    this._logger.info(`Connection state changed`, change);\n    this._emitter.emit(change.current, change);\n  }\n\n  /**\n   * Maps an Ably connection state to a connection status.\n   * @param status The Ably connection state to map.\n   * @returns The corresponding connection status.\n   */\n  private _mapAblyStatusToChat(status: Ably.ConnectionState): ConnectionStatus {\n    switch (status) {\n      case 'initialized': {\n        return ConnectionStatus.Initialized;\n      }\n      case 'connecting': {\n        return ConnectionStatus.Connecting;\n      }\n      case 'connected': {\n        return ConnectionStatus.Connected;\n      }\n      case 'disconnected': {\n        return ConnectionStatus.Disconnected;\n      }\n      case 'suspended': {\n        return ConnectionStatus.Suspended;\n      }\n      case 'closing': {\n        return ConnectionStatus.Closing;\n      }\n      case 'closed': {\n        return ConnectionStatus.Closed;\n      }\n      case 'failed': {\n        return ConnectionStatus.Failed;\n      }\n      default: {\n        this._logger.error('DefaultConnection._mapAblyStatusToChat(); unknown connection state', {\n          status,\n        });\n        return ConnectionStatus.Failed;\n      }\n    }\n  }\n}\n","import * as Ably from '@ably/pubsub-core';\n\n/**\n * Error codes for the Chat SDK.\n */\nexport enum ErrorCode {\n  /**\n   * The request was invalid.\n   */\n  BadRequest = 40000,\n\n  /**\n   * Invalid argument provided.\n   */\n  InvalidArgument = 40003,\n\n  /**\n   * Invalid client ID.\n   */\n  InvalidClientId = 40012,\n\n  /**\n   * Resource has been disposed.\n   */\n  ResourceDisposed = 40014,\n\n  /**\n   * The message was rejected before publishing by a rule on the chat room.\n   */\n  MessageRejectedByBeforePublishRule = 42211,\n\n  /**\n   * The message was rejected before publishing by a moderation rule on the chat room.\n   */\n  MessageRejectedByModeration = 42213,\n\n  /**\n   * The client is not connected to Ably.\n   */\n  Disconnected = 80003,\n\n  /**\n   * Could not re-enter presence automatically after a room re-attach occurred.\n   */\n  PresenceAutoReentryFailed = 91004,\n\n  /**\n   * The room has experienced a discontinuity.\n   */\n  RoomDiscontinuity = 102100,\n\n  // Unable to perform operation;\n\n  /**\n   * Cannot perform operation because the room is in an invalid state.\n   */\n  RoomInInvalidState = 102112,\n\n  /**\n   * Room was released before the operation could complete.\n   */\n  RoomReleasedBeforeOperationCompleted = 102106,\n\n  /**\n   * A room already exists with different options.\n   */\n  RoomExistsWithDifferentOptions = 102107,\n\n  /**\n   * Feature is not enabled in room options.\n   */\n  FeatureNotEnabledInRoom = 102108,\n\n  /**\n   * Listener has not been subscribed yet.\n   */\n  ListenerNotSubscribed = 102109,\n\n  /**\n   * Channel serial is not defined when expected.\n   */\n  ChannelSerialNotDefined = 102110,\n\n  /**\n   * Channel options cannot be modified after the channel has been requested.\n   */\n  ChannelOptionsCannotBeModified = 102111,\n\n  /**\n   * Failed to enforce sequential execution of the operation.\n   */\n  OperationSerializationFailed = 102113,\n\n  // 102200 - 102300 are reserved for React errors\n\n  /**\n   * React hook must be used within the appropriate provider.\n   */\n  ReactHookMustBeUsedWithinProvider = 102200,\n\n  /**\n   * React component has been unmounted.\n   */\n  ReactComponentUnmounted = 102201,\n\n  /**\n   * Failed to fetch presence data after maximum retries.\n   */\n  PresenceFetchFailed = 102202,\n}\n\n/**\n * Returns true if the {@link Ably.ErrorInfo} code matches the provided ErrorCode value.\n * @param errorInfo The error info to check.\n * @param error The error code to compare against.\n * @returns true if the error code matches, false otherwise.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\nexport const errorInfoIs = (errorInfo: Ably.ErrorInfo, error: ErrorCode): boolean => errorInfo.code === error;\n","import React from 'react';\n\nimport { ChatClient } from '../../core/chat-client.js';\n\n/**\n * The Context key to handle global context for the {@link ChatClient}.\n * Only a single instance the {@link ChatClientContext} should exist to avoid issues resulting from multiple identical contexts,\n * e.g., a {@link ChatClient} instance added in one context, and then attempting to retrieve it from a different context.\n *\n */\nconst contextKey = Symbol.for('__ABLY_CHAT_CLIENT_CONTEXT__');\n\n/**\n * Extends GlobalThis interface with chat context.\n * The {@link ChatClientContext} is created once and stored in the global state to ensure a single context instance.\n * contextKey Ably Chat client context.\n */\ninterface GlobalThis {\n  [contextKey]?: React.Context<ChatClientContextValue>;\n}\n\n/**\n * Object to encapsulate global context.\n * Uses {@link GlobalThis} if defined.\n * Protects against creating multiple instances of the {@link ChatClientContext} due to misconfigurations\n * in the module bundler or package manager configurations.\n *\n */\nconst globalObjectForContext: GlobalThis = typeof globalThis === 'undefined' ? {} : (globalThis as GlobalThis);\n\n/**\n * Props for the chat client context provider.\n */\nexport interface ChatClientContextProviderProps {\n  /**\n   Instance of the {@link ChatClient}\n   */\n  client: ChatClient;\n}\n\n/**\n * Record of provider props for each chat client context provider, indexed by provider id.\n *\n */\nexport type ChatClientContextValue = Record<string, ChatClientContextProviderProps>;\n\n/**\n * Returns a {@link ChatClientContext}.\n * Retrieve the context from the global object if initialized,\n * else, initialize and store the context in the global object.\n * @returns Global context for {@link ChatClient}.\n */\nconst getChatContext = (): React.Context<ChatClientContextValue> => {\n  let context = globalObjectForContext[contextKey];\n\n  context ??= globalObjectForContext[contextKey] = React.createContext<ChatClientContextValue>({});\n\n  return context;\n};\n\n/**\n * Global context for {@link ChatClientProvider}.\n * Access point for {@link ChatClient} context in the application.\n */\nexport const ChatClientContext: React.Context<ChatClientContextValue> = getChatContext();\n","var has = Object.prototype.hasOwnProperty;\n\nfunction find(iter, tar, key) {\n\tfor (key of iter.keys()) {\n\t\tif (dequal(key, tar)) return key;\n\t}\n}\n\nexport function dequal(foo, bar) {\n\tvar ctor, len, tmp;\n\tif (foo === bar) return true;\n\n\tif (foo && bar && (ctor=foo.constructor) === bar.constructor) {\n\t\tif (ctor === Date) return foo.getTime() === bar.getTime();\n\t\tif (ctor === RegExp) return foo.toString() === bar.toString();\n\n\t\tif (ctor === Array) {\n\t\t\tif ((len=foo.length) === bar.length) {\n\t\t\t\twhile (len-- && dequal(foo[len], bar[len]));\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (ctor === Set) {\n\t\t\tif (foo.size !== bar.size) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor (len of foo) {\n\t\t\t\ttmp = len;\n\t\t\t\tif (tmp && typeof tmp === 'object') {\n\t\t\t\t\ttmp = find(bar, tmp);\n\t\t\t\t\tif (!tmp) return false;\n\t\t\t\t}\n\t\t\t\tif (!bar.has(tmp)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (ctor === Map) {\n\t\t\tif (foo.size !== bar.size) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor (len of foo) {\n\t\t\t\ttmp = len[0];\n\t\t\t\tif (tmp && typeof tmp === 'object') {\n\t\t\t\t\ttmp = find(bar, tmp);\n\t\t\t\t\tif (!tmp) return false;\n\t\t\t\t}\n\t\t\t\tif (!dequal(len[1], bar.get(tmp))) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (ctor === ArrayBuffer) {\n\t\t\tfoo = new Uint8Array(foo);\n\t\t\tbar = new Uint8Array(bar);\n\t\t} else if (ctor === DataView) {\n\t\t\tif ((len=foo.byteLength) === bar.byteLength) {\n\t\t\t\twhile (len-- && foo.getInt8(len) === bar.getInt8(len));\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (ArrayBuffer.isView(foo)) {\n\t\t\tif ((len=foo.byteLength) === bar.byteLength) {\n\t\t\t\twhile (len-- && foo[len] === bar[len]);\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (!ctor || typeof foo === 'object') {\n\t\t\tlen = 0;\n\t\t\tfor (ctor in foo) {\n\t\t\t\tif (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;\n\t\t\t\tif (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;\n\t\t\t}\n\t\t\treturn Object.keys(bar).length === len;\n\t\t}\n\t}\n\n\treturn foo !== foo && bar !== bar;\n}\n","import * as Ably from '@ably/pubsub-core';\nimport { dequal } from 'dequal';\n\nimport { ChatClient } from '../../core/chat-client.js';\nimport { ErrorCode } from '../../core/errors.js';\nimport { Logger } from '../../core/logger.js';\nimport { Room } from '../../core/room.js';\nimport { RoomOptions } from '../../core/room-options.js';\n\n/**\n * Reference counting entry for a room.\n */\ninterface RoomRefCountEntry {\n  count: number;\n  roomName: string;\n  options?: RoomOptions;\n  resolvedRoom?: Room;\n  resolutionError?: Ably.ErrorInfo;\n  pendingRelease?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Normalizes an array item by sorting the keys of the object and recursively sorting the items in the array.\n * @param item The item to normalize.\n * @returns The normalized item.\n */\nconst normalizeArrayItem = (item: unknown): unknown => {\n  if (item === null || typeof item !== 'object') {\n    return item;\n  }\n  if (Array.isArray(item)) {\n    return item.sort().map((nestedItem) => normalizeArrayItem(nestedItem));\n  }\n  // For objects in arrays, sort keys\n  const sortedObj: Record<string, unknown> = {};\n  const keys = Object.keys(item as Record<string, unknown>).sort();\n  for (const objKey of keys) {\n    sortedObj[objKey] = normalizeArrayItem((item as Record<string, unknown>)[objKey]);\n  }\n  return sortedObj;\n};\n\n/**\n * Replacer function for JSON.stringify that normalizes values to ensure consistent serialization.\n * Recursively sorts object keys and array items for deterministic output.\n * @param key The key being processed.\n * @param value The value being processed.\n * @returns The normalized value.\n */\nconst roomKeyReplacer = (key: string, value: unknown): unknown => {\n  // Handle undefined values consistently\n  if (value === undefined) {\n    return undefined;\n  }\n\n  // Handle null or non-object values\n  if (value === null || typeof value !== 'object') {\n    return value;\n  }\n\n  // Handle arrays - sort the items and recursively normalize\n  if (Array.isArray(value)) {\n    return value.sort().map((item) => normalizeArrayItem(item));\n  }\n\n  // Handle objects - sort the keys\n  const sortedObj: Record<string, unknown> = {};\n  const keys = Object.keys(value as Record<string, unknown>).sort();\n  for (const objKey of keys) {\n    sortedObj[objKey] = (value as Record<string, unknown>)[objKey];\n  }\n  return sortedObj;\n};\n\n/**\n * Creates a unique key for a room based on name and options.\n * Ensures that objects with the same properties but different key order produce the same key.\n * @param roomName The name of the room.\n * @param options The room options.\n * @returns A unique string key for the room.\n */\nconst createRoomKey = (roomName: string, options?: RoomOptions): string =>\n  JSON.stringify({ roomName, options }, roomKeyReplacer);\n\n/**\n * Reference counting manager for rooms within a ChatClientProvider.\n * This manages attach/release lifecycle based on reference counts.\n */\nexport class RoomReferenceManager {\n  private readonly _refCounts = new Map<string, RoomRefCountEntry>();\n  private readonly _client: ChatClient;\n  private readonly _logger: Logger;\n  private readonly _releaseDelayMs = 100; // Delay before actually releasing to allow for abort\n  private readonly _pendingReleases = new Map<string, Promise<void>>(); // Track pending releases by room name\n\n  constructor(client: ChatClient, logger: Logger) {\n    this._client = client;\n    this._logger = logger;\n  }\n\n  /**\n   * Get the client this manager is associated with.\n   * @returns The chat client.\n   */\n  get client(): ChatClient {\n    return this._client;\n  }\n\n  /**\n   * Increment reference count for a room. Attaches on first reference.\n   * @param roomName The name of the room.\n   * @param options The room options.\n   * @returns A promise that resolves to the room instance.\n   */\n  async addReference(roomName: string, options?: RoomOptions): Promise<Room> {\n    this._logger.trace('RoomReferenceManager.addReference();');\n    const key = createRoomKey(roomName, options);\n    const existing = this._refCounts.get(key);\n\n    if (existing) {\n      // If there's a pending release, abort it\n      if (existing.pendingRelease) {\n        clearTimeout(existing.pendingRelease);\n        existing.pendingRelease = undefined;\n        this._logger.debug('RoomReferenceManager.addReference(); aborted pending release', {\n          roomName,\n          options,\n        });\n      }\n\n      existing.count++;\n      this._logger.debug('RoomReferenceManager.addReference(); incremented ref count', {\n        roomName,\n        options,\n        count: existing.count,\n      });\n\n      // Always return the resolved room from the existing reference\n      // We should never call client.rooms.get() again as that would cause\n      // \"room already exists with different options\" errors\n      if (existing.resolvedRoom) {\n        return existing.resolvedRoom;\n      }\n\n      // If the room hasn't resolved yet, wait for it\n      // This shouldn't happen in normal circumstances since we await the room\n      // creation below, but it's a safety net\n      // We'll run a promise that checks every 100ms to see if the room has resolved\n      return new Promise((resolve, reject) => {\n        const interval = setInterval(() => {\n          if (existing.resolvedRoom) {\n            clearInterval(interval);\n            resolve(existing.resolvedRoom);\n          } else if (existing.resolutionError) {\n            clearInterval(interval);\n            reject(existing.resolutionError);\n          }\n        }, 100);\n      });\n    }\n\n    // Check if there's a pending release for this room name (regardless of options)\n    const pendingRelease = this._pendingReleases.get(roomName);\n    if (pendingRelease) {\n      this._logger.debug('RoomReferenceManager.addReference(); waiting for pending release to complete', {\n        roomName,\n        options,\n      });\n\n      try {\n        await pendingRelease;\n      } catch (error) {\n        this._logger.debug('RoomReferenceManager.addReference(); pending release failed, continuing', {\n          roomName,\n          options,\n          error,\n        });\n      }\n    }\n\n    // Check if there's already a room with the same name but different options\n    const existingWithDifferentOptions = [...this._refCounts.values()].find(\n      (entry) => entry.roomName === roomName && !dequal(entry.options, options),\n    );\n\n    if (existingWithDifferentOptions) {\n      // Only allow different options if:\n      // 1. There's a pending release for the existing room, OR\n      // 2. The reference count is 0 (meaning it's scheduled for release)\n      const hasPendingRelease = existingWithDifferentOptions.pendingRelease !== undefined;\n      const hasZeroRefCount = existingWithDifferentOptions.count <= 0;\n\n      if (!hasPendingRelease && !hasZeroRefCount) {\n        // Room is actively being used with different options - throw an error\n        throw new Ably.ErrorInfo(\n          `unable to get room reference; room \"${roomName}\" is already in use with different options`,\n          ErrorCode.RoomExistsWithDifferentOptions,\n          400,\n        );\n      }\n\n      this._logger.debug(\n        'RoomReferenceManager.addReference(); found existing room with different options, releasing it first',\n        {\n          roomName,\n          newOptions: options,\n          existingOptions: existingWithDifferentOptions.options,\n          hasPendingRelease,\n          hasZeroRefCount,\n        },\n      );\n\n      // Cancel any pending release for the existing room\n      if (existingWithDifferentOptions.pendingRelease) {\n        clearTimeout(existingWithDifferentOptions.pendingRelease);\n        existingWithDifferentOptions.pendingRelease = undefined;\n      }\n\n      // Remove the existing room reference immediately\n      const existingKey = createRoomKey(roomName, existingWithDifferentOptions.options);\n      this._refCounts.delete(existingKey);\n\n      // Create and track the release promise\n      const releasePromise = this._client.rooms\n        .release(roomName)\n        .catch((error: unknown) => {\n          this._logger.debug('RoomReferenceManager.addReference(); release of existing room failed', {\n            roomName,\n            error,\n          });\n        })\n        .finally(() => {\n          // Remove the pending release tracking when done\n          this._pendingReleases.delete(roomName);\n        });\n\n      // Track the pending release\n      this._pendingReleases.set(roomName, releasePromise);\n\n      // Wait for the release to complete\n      try {\n        await releasePromise;\n      } catch (error) {\n        this._logger.debug('RoomReferenceManager.addReference(); release of existing room failed, continuing', {\n          roomName,\n          error,\n        });\n      }\n    }\n\n    // First reference - create entry and attach\n    const entry: RoomRefCountEntry = {\n      count: 1,\n      roomName,\n      options,\n    };\n    this._refCounts.set(key, entry);\n\n    this._logger.debug('RoomReferenceManager.addReference(); first reference, attaching room', {\n      roomName,\n      options,\n    });\n\n    try {\n      const room = await this._client.rooms.get(roomName, options);\n      entry.resolvedRoom = room;\n\n      // Attach the room on first reference\n      void room.attach().catch((error: unknown) => {\n        this._logger.error('RoomReferenceManager.addReference(); error attaching room', {\n          roomName,\n          options,\n          error,\n        });\n      });\n\n      return room;\n    } catch (error: unknown) {\n      // If room creation failed, clean up the entry, but also set the resolution error\n      entry.resolutionError = error as Ably.ErrorInfo;\n      this._refCounts.delete(key);\n      this._logger.error('RoomReferenceManager.addReference(); error creating room', {\n        roomName,\n        options,\n        error,\n      });\n      throw error;\n    }\n  }\n\n  /**\n   * Decrement reference count for a room. Releases on last reference after a delay.\n   * @param roomName The name of the room.\n   * @param options The room options.\n   */\n  removeReference(roomName: string, options?: RoomOptions): void {\n    this._logger.trace('RoomReferenceManager.removeReference();');\n    const key = createRoomKey(roomName, options);\n    const existing = this._refCounts.get(key);\n\n    if (!existing) {\n      this._logger.debug('RoomReferenceManager.removeReference(); no existing reference found', {\n        roomName,\n        options,\n      });\n      return;\n    }\n\n    existing.count--;\n    this._logger.debug('RoomReferenceManager.removeReference(); decremented ref count', {\n      roomName,\n      options,\n      count: existing.count,\n    });\n\n    if (existing.count <= 0) {\n      // Schedule release after a delay to allow for abort\n      this._logger.debug('RoomReferenceManager.removeReference(); scheduling delayed release', {\n        roomName,\n        options,\n        delayMs: this._releaseDelayMs,\n      });\n\n      existing.pendingRelease = setTimeout(() => {\n        // Double-check that the entry still exists and should be released\n        const currentEntry = this._refCounts.get(key);\n        if (currentEntry && currentEntry.count <= 0) {\n          this._refCounts.delete(key);\n          this._logger.debug('RoomReferenceManager.removeReference(); executing delayed release', {\n            roomName,\n            options,\n          });\n\n          // Create a promise for the release operation and track it\n          const releasePromise = this._client.rooms\n            .release(roomName)\n            .catch((error: unknown) => {\n              this._logger.debug('RoomReferenceManager.removeReference(); release failed', {\n                roomName,\n                options,\n                error,\n              });\n            })\n            .finally(() => {\n              // Remove the pending release tracking when done\n              this._pendingReleases.delete(roomName);\n            });\n\n          // Track the pending release by room name\n          this._pendingReleases.set(roomName, releasePromise);\n        }\n      }, this._releaseDelayMs);\n    }\n  }\n\n  getReferenceCount(roomName: string, options?: RoomOptions): number {\n    this._logger.trace('RoomReferenceManager.getReferenceCount();');\n    const key = createRoomKey(roomName, options);\n    return this._refCounts.get(key)?.count ?? 0;\n  }\n}\n","import * as Ably from '@ably/pubsub-core';\nimport * as React from 'react';\n\nimport { ErrorCode } from '../../../core/errors.js';\nimport { ChatClientContext, ChatClientContextValue } from '../../contexts/chat-client-context.js';\nimport { RoomReferenceManager } from '../../helper/room-reference-manager.js';\n\n// Symbol to store the room reference manager in the context without conflicting with the string index\nexport const ROOM_REFERENCE_MANAGER_KEY = Symbol('roomReferenceManager');\n\n/**\n * Extended context value that includes the room reference manager.\n */\nexport interface ExtendedChatClientContextValue extends ChatClientContextValue {\n  [ROOM_REFERENCE_MANAGER_KEY]?: RoomReferenceManager;\n}\n\n/**\n * Hook to access the room reference manager from the current ChatClientProvider.\n * @returns The room reference manager instance\n * @throws An {@link Ably.ErrorInfo} if used outside of a ChatClientProvider\n */\nexport const useRoomReferenceManager = (): RoomReferenceManager => {\n  const context = React.useContext(ChatClientContext) as ExtendedChatClientContextValue;\n  const manager = context[ROOM_REFERENCE_MANAGER_KEY];\n  if (!manager) {\n    throw new Ably.ErrorInfo(\n      'unable to get room reference manager; useRoomReferenceManager must be used within a ChatClientProvider',\n      ErrorCode.ReactHookMustBeUsedWithinProvider,\n      400,\n    );\n  }\n  return manager;\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport * as React from 'react';\nimport { ReactNode, useRef } from 'react';\n\nimport { ChatClient } from '../../core/chat-client.js';\nimport { Logger } from '../../core/logger.js';\nimport { ChatClientContext } from '../contexts/chat-client-context.js';\nimport { RoomReferenceManager } from '../helper/room-reference-manager.js';\nimport {\n  ExtendedChatClientContextValue,\n  ROOM_REFERENCE_MANAGER_KEY,\n} from '../hooks/internal/use-room-reference-manager.js';\n\n/**\n * The default identifier for the {@link ChatClientContext}.\n */\nexport const DEFAULT_CHAT_CLIENT_ID = 'default';\n\n/**\n * Props for the {@link ChatClientProvider} component.\n */\nexport interface ChatClientProviderProps {\n  /**\n   * The child components to be rendered within this provider.\n   */\n  children?: ReactNode | ReactNode[] | null;\n\n  /**\n   * An instance of the {@link ChatClient} to be used in the provider.\n   */\n  client: ChatClient;\n}\n\n/**\n * Returns a React component that provides a {@link ChatClient} in a React context to the component subtree.\n * Updates the context value when the client prop changes.\n *\n * The provider manages room reference counting internally and will only detach rooms when no more references exist.\n *\n * **Important**: The `client` prop should be memoized to prevent unnecessary context updates.\n * Ideally, create the {@link ChatClient} and its underlying {@link Ably.PubSubRealtimeClient} client outside\n * of React components to avoid duplicate connections and ensure stable references.\n *\n * **Note**: All chat-related hooks must be used within this provider's component tree.\n * @param props - The props for the {@link ChatClientProvider} component\n * @param props.children - The child components to be rendered within this provider.\n * @param props.client - An instance of the {@link ChatClient} to be used in the provider\n * @returns A React element that provides the chat client context to its children\n * @example\n * ```tsx\n * import * as Ably from '@ably/pubsub-device';\n * import React, { useMemo } from 'react';\n * import { ChatClient } from '@ably/chat';\n * import { ChatClientProvider, useChatClient } from '@ably/chat/react';\n *\n * // Child component that uses chat functionality\n * const ChatComponent = () => {\n *   const { clientId } = useChatClient();\n *   return <div>Connected as: {clientId}</div>;\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // Main app component with provider\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *         <ChatComponent />\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const ChatClientProvider = ({ children, client }: ChatClientProviderProps) => {\n  const context = React.useContext(ChatClientContext);\n  const roomReferenceManagerRef = useRef<RoomReferenceManager | undefined>(undefined);\n\n  const value: ExtendedChatClientContextValue = React.useMemo(() => {\n    // Set the internal useReact option to true to enable React-specific agent.\n    (client as unknown as { addReactAgent(): void }).addReactAgent();\n\n    // Create or update the room reference manager\n    if (roomReferenceManagerRef.current?.client !== client) {\n      const clientLogger = (client as unknown as { logger: Logger }).logger;\n      roomReferenceManagerRef.current = new RoomReferenceManager(client, clientLogger);\n    }\n\n    // Add the agent for the UI kit\n    const uiKitVersion = globalThis.__ABLY_CHAT_REACT_UI_KIT_VERSION__;\n    if (typeof uiKitVersion === 'string') {\n      (\n        client as unknown as {\n          addAgentWithVersion(agent: string, version: string): void;\n        }\n      ).addAgentWithVersion('chat-react-ui-kit', uiKitVersion);\n    }\n\n    return {\n      ...context,\n      [DEFAULT_CHAT_CLIENT_ID]: { client: client },\n      [ROOM_REFERENCE_MANAGER_KEY]: roomReferenceManagerRef.current,\n    };\n  }, [client, context]);\n\n  return <ChatClientContext.Provider value={value}>{children}</ChatClientContext.Provider>;\n};\n","import * as Ably from '@ably/pubsub-core';\nimport React from 'react';\n\nimport { ChatClient } from '../../../core/chat-client.js';\nimport { ErrorCode } from '../../../core/errors.js';\nimport { ChatClientContext } from '../../contexts/chat-client-context.js';\nimport { DEFAULT_CHAT_CLIENT_ID } from '../../providers/chat-client-provider.js';\n\n/**\n * Hook to access the chat client provided by the current {@link ChatClientProvider}.\n * This hook must be used within a {@link ChatClientProvider}.\n * @throws An {@link Ably.ErrorInfo} When the hook is not used within a {@link ChatClientProvider}.\n * @returns The {@link ChatClient} instance provided by the context.\n */\nexport const useChatClientContext = (): ChatClient => {\n  const context = React.useContext(ChatClientContext)[DEFAULT_CHAT_CLIENT_ID];\n  if (!context) {\n    throw new Ably.ErrorInfo(\n      'unable to get chat client; useChatClient hook must be used within a chat client provider',\n      ErrorCode.ReactHookMustBeUsedWithinProvider,\n      400,\n    );\n  }\n  return context.client;\n};\n","import * as Ably from '@ably/pubsub-core';\nimport { useContext } from 'react';\n\nimport { ErrorCode } from '../../../core/errors.js';\nimport { ChatRoomContext, ChatRoomContextType } from '../../contexts/chat-room-context.js';\n\n/**\n * A hook that returns the current ChatRoomContext. This should be used within a ChatRoomProvider.\n * @internal\n * @param callingHook The name of the hook that is calling this function, for logging purposes.\n * @throws An {@link Ably.ErrorInfo} if the hook is not used within a ChatRoomProvider.\n * @returns The ChatRoomContext.\n */\nexport const useRoomContext = (callingHook: string): ChatRoomContextType => {\n  const context = useContext(ChatRoomContext);\n  if (!context) {\n    throw new Ably.ErrorInfo(\n      `unable to get room context; ${callingHook} hook must be used within a <ChatRoomProvider>`,\n      ErrorCode.ReactHookMustBeUsedWithinProvider,\n      400,\n    );\n  }\n\n  return context;\n};\n","import { useMemo } from 'react';\n\nimport { Logger } from '../../../core/logger.js';\nimport { useChatClientContext } from './use-chat-client-context.js';\nimport { useRoomContext } from './use-room-context.js';\n/**\n * A hook that provides access to the {@link Logger} instance of the {@link ChatClient}.\n * It will use the instance belonging to the {@link ChatClient} in the nearest {@link ChatClientProvider} in the component tree.\n * @internal\n * @returns Logger - The logger instance.\n */\nexport const useLogger = (): Logger => {\n  const chatClient = useChatClientContext();\n  return useMemo(() => (chatClient as unknown as { logger: Logger }).logger, [chatClient]);\n};\n\n/**\n * A hook that returns a logger with the room context pre-applied.\n * @internal\n * @returns Logger - The logger instance.\n */\nexport const useRoomLogger = (): Logger => {\n  const roomContext = useRoomContext('useRoomLogger');\n  const chatClient = useChatClientContext();\n\n  return useMemo(\n    () => (chatClient as unknown as { logger: Logger }).logger.withContext({ roomName: roomContext.roomName }),\n    [chatClient, roomContext],\n  );\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport { useEffect, useState } from 'react';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { type ChatClient } from '../../core/chat-client.js';\nimport { ConnectionStatus, ConnectionStatusChange } from '../../core/connection.js';\nimport { useChatClientContext } from './internal/use-chat-client-context.js';\nimport { useLogger } from './internal/use-logger.js';\n\n/**\n * The response from the {@link useChatClient} hook.\n */\nexport interface UseChatClientResponse {\n  /**\n   * The current clientId, if known.\n   *\n   * **Important** When using an Ably key for authentication, this value is determined immediately. If using a token,\n   * the clientId is not known until the client has successfully connected to and authenticated with\n   * the server. Use the `chatClient.connection.status` to check the connection status.\n   */\n  readonly clientId?: string;\n}\n\n/**\n * React hook to access the chat client provided by the current {@link ChatClientProvider}.\n *\n * This hook automatically tracks the clientId and updates when connection state changes,\n * ensuring the most current client ID is always available. The client ID may change\n * when the underlying Ably Realtime client reconnects with different authentication.\n *\n * **Note**: This hook must be used within a {@link ChatClientProvider} component tree.\n * @returns A {@link UseChatClientResponse} containing the current client ID\n * @throws An {@link Ably.ErrorInfo} When used outside of a {@link ChatClientProvider}\n * @example\n * ```tsx\n * import * as Ably from '@ably/pubsub-device';\n * import React from 'react';\n * import { ChatClient } from '@ably/chat';\n * import { ChatClientProvider, useChatClient } from '@ably/chat/react';\n *\n * // Component that displays current user information\n * const UserInfo = () => {\n *   const { clientId } = useChatClient();\n *   return (<p>Connected as: {clientId}</p>);\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with provider\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <UserInfo />\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useChatClient = (): UseChatClientResponse => {\n  const client = useChatClientContext();\n  const logger = useLogger();\n  const [clientId, setClientId] = useState(() => {\n    logger.debug('useChatClient(); setting initial clientId', { clientId: client.clientId });\n    return client.clientId;\n  });\n\n  // Right now, it's possible to change the clientId being used on then core SDK, but only by disconnecting\n  // and then reconnecting. So to ensure our clientId remains up to date, check it every time the SDK connects.\n  useEffect(() => {\n    logger.debug('useChatClient(); subscribing to connection status changes', {\n      clientId: client.clientId,\n    });\n\n    // Set the clientId again in case it's changed between original state and effects\n    setClientId(client.clientId);\n\n    const { off } = client.connection.onStatusChange((change: ConnectionStatusChange) => {\n      if (change.current === ConnectionStatus.Connected) {\n        logger.debug('useChatClient(); connection status is now connected', {\n          clientId: client.clientId,\n        });\n        setClientId(client.clientId);\n      }\n    });\n\n    return () => {\n      logger.debug('useChatClient(); unsubscribing from connection status changes');\n      off();\n    };\n  }, [client, logger]);\n\n  return {\n    clientId,\n  };\n};\n","import { useCallback, useEffect, useRef } from 'react';\n\n/**\n * The type of a callback function that can be stored in the reference.\n */\ntype Callback<CallbackArguments extends unknown[]> = (...args: CallbackArguments) => void;\n\n/**\n * A hook that creates a reference to an event listener callback function. It is used to stabilize the reference\n * across renders, so that listeners don't get unsubscribed and resubscribed on every render when passed in as a prop.\n *\n * For example, doing this:\n *\n * ```jsx\n * export function MySubscription() {\n * useHookWithListener(() => {})\n *\n * return <div>My Subscription</div>\n * }\n * ```\n *\n * Where the `useHookWithListener` hook is defined as:\n *\n * ```jsx\n * export function useHookWithListener(listener) {\n * const listenerRef = useEventListenerRef(listener);\n * useEffect(() => {\n * // Use the listenerRef\n * }, [listenerRef]);\n * }\n * ```\n *\n * Will ensure that the listener is not unsubscribed and resubscribed on every render (i.e. the useEffect will not be called\n * on every render).\n *\n * We allow for the callback to be undefined, as callbacks in the majority of our hooks are optional. In this instance we return undefined,\n * so that subscriptions will be unwound by the useEffect hook that's using them.\n * @internal\n * @template Arguments - The type of arguments accepted by the callback function.\n * @param callback - The callback function to be stored in the reference.\n * @returns A static callback function that wraps the provided callback function, or undefined if no callback is provided.\n */\nexport const useEventListenerRef = <Arguments extends unknown[]>(\n  callback?: Callback<Arguments>,\n): Callback<Arguments> | undefined => {\n  const ref = useRef<Callback<Arguments> | undefined>(callback);\n  useEffect(() => {\n    ref.current = callback;\n  });\n\n  const returnVal = useCallback((...args: Arguments) => {\n    if (ref.current) {\n      ref.current(...args);\n    }\n  }, []);\n\n  return callback ? returnVal : undefined;\n};\n","import * as Ably from '@ably/pubsub-core';\nimport { useEffect, useState } from 'react';\n\nimport { ConnectionStatus, ConnectionStatusChange, ConnectionStatusListener } from '../../core/connection.js';\nimport { useChatClientContext } from './internal/use-chat-client-context.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useLogger } from './internal/use-logger.js';\n\n/**\n * The options for the {@link useChatConnection} hook.\n */\nexport interface UseChatConnectionOptions {\n  /**\n   * A callback that will be called whenever the connection status changes.\n   * The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * useChatConnection({\n   *   onStatusChange: (change) => {\n   *     console.log(`Connection changed from ${change.previous} to ${change.current}`);\n   *   }\n   * });\n   * ```\n   */\n  onStatusChange?: ConnectionStatusListener;\n}\n\n/**\n * The response from the {@link useChatConnection} hook.\n */\nexport interface UseChatConnectionResponse {\n  /**\n   * The current status of the connection. Kept up to date by the hook.\n   */\n  currentStatus: ConnectionStatus;\n\n  /**\n   * An error that provides a reason why the connection has entered the new status, if applicable.\n   * Kept up to date by the hook.\n   */\n  error?: Ably.ErrorInfo;\n}\n\n/**\n * React hook that provides the current connection status and error between the client and Ably, and\n * allows the user to listen to connection status changes overtime.\n *\n * The hook will automatically clean up listeners when the component unmounts and\n * update the connection state whenever the underlying chat client changes.\n *\n * **Note**: This hook must be used within a {@link ChatClientProvider} component tree.\n * @param options - Optional configuration for the hook\n * @returns A {@link UseChatConnectionResponse} containing the current connection status and error\n * @throws An {@link Ably.ErrorInfo} When used outside of a {@link ChatClientProvider}\n * @example\n * ```tsx\n * import * as Ably from '@ably/pubsub-device';\n * import React from 'react';\n * import { ChatClient, ConnectionStatus } from '@ably/chat';\n * import { ChatClientProvider, useChatConnection } from '@ably/chat/react';\n *\n * // Component that displays connection status\n * const ConnectionStatus = () => {\n *   const { currentStatus, error } = useChatConnection({\n *     onStatusChange: (change) => {\n *       console.log(`Connection changed from ${change.previous} to ${change.current}`);\n *       if (change.error) {\n *         console.error('Connection error:', change.error);\n *       }\n *     }\n *   });\n *   return (\n *     <div>\n *       <div>\n *         Status: {currentStatus}\n *       </div>\n *       {error && (\n *         <div>\n *           Error: {error.message} (Code: {error.code})\n *         </div>\n *       )}\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with provider setup\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ConnectionStatus />\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useChatConnection = (options?: UseChatConnectionOptions): UseChatConnectionResponse => {\n  const chatClient = useChatClientContext();\n  const logger = useLogger();\n  logger.trace('useChatConnection();', options);\n\n  // Initialize states with the current values from chatClient\n  const [currentStatus, setCurrentStatus] = useState<ConnectionStatus>(chatClient.connection.status);\n  const [error, setError] = useState<Ably.ErrorInfo | undefined>(chatClient.connection.error);\n\n  // Update the states when the chatClient changes\n  useEffect(() => {\n    setError(chatClient.connection.error);\n    setCurrentStatus(chatClient.connection.status);\n  }, [chatClient]);\n\n  // Create stable references for the listeners\n  const onStatusChangeRef = useEventListenerRef(options?.onStatusChange);\n\n  // Apply the listener to the chatClient's connection status changes to keep the state update across re-renders\n  useEffect(() => {\n    logger.debug('useChatConnection(); applying internal listener');\n    const { off } = chatClient.connection.onStatusChange((change: ConnectionStatusChange) => {\n      // Update states with new values\n      setCurrentStatus(change.current);\n      setError(change.error);\n    });\n    // Cleanup listener on un-mount\n    return () => {\n      logger.debug('useChatConnection(); cleaning up listener');\n      off();\n    };\n  }, [chatClient.connection, logger]);\n\n  // Register the listener for the user-provided onStatusChange callback\n  useEffect(() => {\n    if (!onStatusChangeRef) return;\n    logger.debug('useChatConnection(); applying client listener');\n    const { off } = chatClient.connection.onStatusChange(onStatusChangeRef);\n\n    return () => {\n      logger.debug('useChatConnection(); cleaning up client listener');\n      off();\n    };\n  }, [chatClient.connection, logger, onStatusChangeRef]);\n\n  return {\n    currentStatus,\n    error,\n  };\n};\n","import { Logger } from '../../core/logger.js';\nimport { Room } from '../../core/room.js';\n\n/**\n * RoomPromise is a wrapper around a promise that resolves to a Room instance.\n *\n * It is designed to better integrate into the React lifecycle, and control whether an unmount\n * function needs to be called depending on where the promise resolution occurs relative to the\n * component lifecycle.\n */\nexport interface RoomPromise {\n  /**\n   * Returns a function to be called when the component is unmounted. If the room promise has resolved at the time,\n   * of calling, then the unmount function returned by the onResolve callback will be called.\n   *\n   * Multiple calls are no-op.\n   *\n   * This should be used in conjunction with React's useEffect hook to ensure that resources are cleaned up.\n   * @returns A function that should be called when the component is unmounted.\n   * @example\n   * ```ts\n   * useEffect(() => {\n   *   const roomPromise: RoomPromise;\n   *   return roomPromise.unmount();\n   * }, []);\n   */\n  unmount: () => () => void;\n}\n\n/**\n * A callback that can be returned by the onResolve callback to clean up any resources.\n */\ntype UnmountCallback = () => void;\n\n/**\n * A callback that is called when the promise resolves to a Room instance.\n */\nexport type RoomResolutionCallback = (room: Room) => UnmountCallback;\n\n/**\n * Default implementation of RoomPromise.\n */\nclass DefaultRoomPromise implements RoomPromise {\n  private readonly _logger: Logger;\n  private readonly _onResolve: RoomResolutionCallback;\n  private _onUnmount?: UnmountCallback;\n  private _unmounted = false;\n\n  /**\n   * Creates a new DefaultRoomPromise and starts the resolution of the promise.\n   * @param room  The promise that resolves to a Room instance.\n   * @param onResolve  The callback that is called when the promise resolves to a Room instance.\n   * @param logger  The logger to use for logging.\n   */\n  constructor(room: Promise<Room>, onResolve: RoomResolutionCallback, logger: Logger) {\n    this._onResolve = onResolve;\n    this._logger = logger;\n\n    this.mount(room).catch((error: unknown) => {\n      this._logger.trace('DefaultRoomPromise(); mount error', { error: error });\n    });\n  }\n\n  /**\n   * Wait for the room promise to resolve, then execute the onResolve callback, storing its response as an unmount function.\n   * If the component is unmounted before the promise resolves, then this will do nothing.\n   * @param promise The promise that resolves to a Room instance.\n   * @returns A promise that we simply resolve when it's done.\n   */\n  async mount(promise: Promise<Room>): Promise<void> {\n    this._logger.debug('DefaultRoomPromise(); mount');\n    try {\n      const room = await promise;\n      if (this._unmounted) {\n        return;\n      }\n\n      this._logger.debug('DefaultRoomPromise(); mount resolved');\n      this._onUnmount = this._onResolve(room);\n    } catch (error) {\n      this._logger.error('DefaultRoomPromise(); mount error', { error });\n    }\n  }\n\n  /**\n   * Returns a function to be called when the component is unmounted. If the room promise has resolved at the time\n   * of calling, then the unmount function returned by the onResolve callback will be called.\n   *\n   * Multiple calls are no-op.\n   *\n   * Example usage:\n   *\n   * ```ts\n   * useEffect(() => {\n   * const roomPromise = wrapRoomPromise(...);\n   * return roomPromise.unmount();\n   * }, []);\n   * ```\n   * @returns A function that should be called when the component is unmounted.\n   */\n  unmount() {\n    if (this._unmounted) {\n      return () => {\n        // noop\n      };\n    }\n\n    return () => {\n      this._logger.debug('DefaultRoomPromise(); unmount');\n      this._unmounted = true;\n      this._onUnmount?.();\n    };\n  }\n}\n\n/**\n * Provides a convenient way to wrap a promise that resolves to a Room instance, and execute a callback.\n * This should be used in conjunction with React's useEffect hook to ensure that resources are cleaned up.\n *\n * Example usage:\n *\n * ```ts\n * useEffect(() => {\n * const roomPromise = wrapRoomPromise(...);\n * return roomPromise.unmount();\n * }, []);\n * ```\n * @internal\n * @param room The promise that resolves to a Room instance.\n * @param onResolve The callback that is called when the promise resolves to a Room instance.\n * @param logger The logger to use for logging.\n * @returns A RoomPromise instance that can be used to clean up resources.\n */\nexport const wrapRoomPromise = (room: Promise<Room>, onResolve: RoomResolutionCallback, logger: Logger): RoomPromise =>\n  new DefaultRoomPromise(room, onResolve, logger);\n","import * as Ably from '@ably/pubsub-core';\n\nimport { Logger } from './logger.js';\nimport { StatusSubscription } from './subscription.js';\nimport EventEmitter, { emitterHasListeners, wrap } from './utils/event-emitter.js';\n\n/**\n * The different states that a room can be in throughout its lifecycle.\n */\nexport enum RoomStatus {\n  /**\n   * The library is currently initializing the room. This state is a temporary state used in React prior\n   * to the room being resolved.\n   */\n  Initializing = 'initializing',\n\n  /**\n   * A temporary state for when the room object is first initialized.\n   */\n  Initialized = 'initialized',\n\n  /**\n   * The library is currently attempting to attach the room.\n   */\n  Attaching = 'attaching',\n\n  /**\n   * The room is currently attached and receiving events.\n   */\n  Attached = 'attached',\n\n  /**\n   * The room is currently detaching and will not receive events.\n   */\n  Detaching = 'detaching',\n\n  /**\n   * The room is currently detached and will not receive events.\n   */\n  Detached = 'detached',\n\n  /**\n   * The room is in an extended state of detachment, but will attempt to re-attach when able.\n   */\n  Suspended = 'suspended',\n\n  /**\n   * The room is currently detached and will not attempt to re-attach. User intervention is required.\n   */\n  Failed = 'failed',\n\n  /**\n   * The room is in the process of releasing. Attempting to use a room in this state may result in undefined behavior.\n   */\n  Releasing = 'releasing',\n\n  /**\n   * The room has been released and is no longer usable.\n   */\n  Released = 'released',\n}\n\n/**\n * Represents a change in the status of the room.\n */\nexport interface RoomStatusChange {\n  /**\n   * The new status of the room.\n   */\n  current: RoomStatus;\n\n  /**\n   * The previous status of the room.\n   */\n  previous: RoomStatus;\n\n  /**\n   * An error that provides a reason why the room has\n   * entered the new status, if applicable.\n   */\n  error?: Ably.ErrorInfo;\n}\n\n/**\n * A function that can be called when the room status changes.\n * @param change The change in status.\n */\nexport type RoomStatusListener = (change: RoomStatusChange) => void;\n\n/**\n * Represents the status of a Room.\n */\nexport interface RoomLifecycle {\n  /**\n   * The current status of the room.\n   */\n  get status(): RoomStatus;\n\n  /**\n   * The current error, if any, that caused the room to enter the current status.\n   */\n  get error(): Ably.ErrorInfo | undefined;\n\n  /**\n   * Registers a listener that will be called whenever the room status changes.\n   * @param listener The function to call when the status changes.\n   * @returns An object that can be used to unregister the listener.\n   */\n  onChange(listener: RoomStatusListener): StatusSubscription;\n}\n\n/**\n * An internal interface for the status of a room, which can be used to separate critical\n * internal functionality from user listeners.\n * @internal\n */\nexport interface InternalRoomLifecycle extends RoomLifecycle {\n  /**\n   * Sets the status of the room.\n   * @param params The new status of the room.\n   */\n  setStatus(params: NewRoomStatus): void;\n}\n\n/**\n * A new room status that can be set.\n */\nexport interface NewRoomStatus {\n  /**\n   * The new status of the room.\n   */\n  status: RoomStatus;\n\n  /**\n   * An error that provides a reason why the room has\n   * entered the new status, if applicable.\n   */\n  error?: Ably.ErrorInfo;\n}\n\ntype RoomStatusEventsMap = Record<RoomStatus, RoomStatusChange>;\n\n/**\n * An implementation of the `Status` interface.\n * @internal\n */\nexport class DefaultRoomLifecycle implements InternalRoomLifecycle {\n  private _status: RoomStatus = RoomStatus.Initialized;\n  private _error?: Ably.ErrorInfo;\n  private readonly _logger: Logger;\n  private readonly _emitter = new EventEmitter<RoomStatusEventsMap>();\n\n  /**\n   * Constructs a new DefaultRoomLifecycle instance.\n   * @param logger An instance of the Logger.\n   */\n  constructor(logger: Logger) {\n    this._logger = logger;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  get status(): RoomStatus {\n    return this._status;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  get error(): Ably.ErrorInfo | undefined {\n    return this._error;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  onChange(listener: RoomStatusListener): StatusSubscription {\n    const wrapped = wrap(listener);\n    this._emitter.on(wrapped);\n\n    return {\n      off: () => {\n        this._emitter.off(wrapped);\n      },\n    };\n  }\n\n  setStatus(params: NewRoomStatus): void {\n    const change: RoomStatusChange = {\n      current: params.status,\n      error: params.error,\n      previous: this._status,\n    };\n\n    this._status = change.current;\n    this._error = change.error;\n    this._logger.info(`room status changed`, { ...change });\n    this._emitter.emit(change.current, change);\n  }\n\n  /**\n   * Disposes of the room lifecycle instance, removing all listeners.\n   * This method should be called when the room is being released to ensure proper cleanup.\n   * @internal\n   */\n  dispose(): void {\n    this._logger.trace('DefaultRoomLifecycle.dispose();');\n\n    // Remove all user-level listeners\n    this._emitter.off();\n\n    this._logger.debug('DefaultRoomLifecycle.dispose(); disposed successfully');\n  }\n\n  /**\n   * Checks if there are any listeners registered by users.\n   * @internal\n   * @returns true if there are listeners, false otherwise.\n   */\n  hasListeners(): boolean {\n    return emitterHasListeners(this._emitter);\n  }\n}\n","import * as Ably from '@ably/pubsub-core';\nimport { useEffect, useState } from 'react';\n\nimport { Room } from '../../../core/room.js';\nimport { RoomStatus, RoomStatusChange } from '../../../core/room-status.js';\nimport { wrapRoomPromise } from '../../helper/room-promise.js';\nimport { useEventListenerRef } from './use-event-listener-ref.js';\nimport { useRoomLogger } from './use-logger.js';\nimport { useRoomContext } from './use-room-context.js';\n\n/**\n * The response object for the useRoomStatus hook.\n */\nexport interface UseRoomStatusResponse {\n  /**\n   * The current status of the room.\n   */\n  readonly status: RoomStatus;\n\n  /**\n   * The error that caused the room to transition to an errored state.\n   */\n  readonly error?: Ably.ErrorInfo;\n}\n\n/**\n * The parameters for the useRoomStatus hook.\n */\nexport interface UseRoomStatusParams {\n  /**\n   * A listener for room status changes.\n   */\n  onRoomStatusChange?: (change: RoomStatusChange) => void;\n}\n\n/**\n * A hook that returns the current status of the room, and listens for changes to the room status.\n * @internal\n * @param params An optional user-provided listener for room status changes.\n * @returns The current status of the room, and an error if the room is in an errored state.\n */\nexport const useRoomStatus = (params?: UseRoomStatusParams): UseRoomStatusResponse => {\n  const context = useRoomContext('useRoomStatus');\n\n  const [status, setStatus] = useState<RoomStatus>(RoomStatus.Initializing);\n  const [error, setError] = useState<Ably.ErrorInfo | undefined>();\n  const logger = useRoomLogger();\n\n  // create stable references for the listeners and register the user-provided callbacks\n  const onRoomStatusChangeRef = useEventListenerRef(params?.onRoomStatusChange);\n\n  // create an internal listener to update the status\n  useEffect(() => {\n    const roomPromise = wrapRoomPromise(\n      context.room,\n      (room: Room) => {\n        logger.debug('useRoomStatus(); subscribing internal listener');\n        // Set instantaneous values\n        setStatus(room.status);\n        setError(room.error);\n\n        // Add the subscription\n        const { off } = room.onStatusChange((change) => {\n          logger.debug('useRoomStatus(); status change', change);\n          setStatus(change.current);\n          setError(change.error);\n        });\n\n        return () => {\n          logger.debug('useRoomStatus(); unsubscribing internal listener');\n          off();\n        };\n      },\n      logger,\n    );\n\n    return roomPromise.unmount();\n  }, [context, logger]);\n\n  useEffect(() => {\n    const roomPromise = wrapRoomPromise(\n      context.room,\n      (room: Room) => {\n        let off: (() => void) | undefined;\n        if (onRoomStatusChangeRef) {\n          logger.debug('useRoomStatus(); subscribing to status changes');\n          off = room.onStatusChange(onRoomStatusChangeRef).off;\n        }\n\n        logger.debug('useRoomStatus(); setting initial status', { status: room.status });\n        if (onRoomStatusChangeRef) {\n          logger.debug('useRoomStatus(); sending initial status event');\n          onRoomStatusChangeRef({\n            current: room.status,\n            previous: RoomStatus.Initializing,\n            error: room.error,\n          });\n        }\n\n        return () => {\n          logger.debug('useRoomStatus(); unmounting');\n          if (off) {\n            logger.debug('useRoomStatus(); unsubscribing from status changes');\n            off();\n          }\n        };\n      },\n      logger,\n    );\n\n    return roomPromise.unmount();\n  }, [context, logger, onRoomStatusChangeRef]);\n\n  return {\n    status,\n    error,\n  };\n};\n","import * as Ably from '@ably/pubsub-core';\nimport { useCallback, useEffect, useState } from 'react';\n\nimport { ErrorCode } from '../../core/errors.js';\nimport { Message } from '../../core/message.js';\nimport type {\n  DeleteMessageReactionParams,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  MessageReactions,\n  SendMessageReactionParams,\n} from '../../core/message-reactions.js'; // imported for typedoc links\nimport { MessageRawReactionListener, MessageReactionListener } from '../../core/message-reactions.js';\nimport {\n  HistoryParams,\n  MessageListener,\n  Messages,\n  MessageSubscriptionResponse,\n  OperationDetails,\n  SendMessageParams,\n  UpdateMessageParams,\n} from '../../core/messages.js';\nimport { PaginatedResult } from '../../core/query.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { Listenable } from '../types/listenable.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The response from the {@link useMessages} hook.\n */\nexport interface UseMessagesResponse extends ChatStatusResponse {\n  /**\n   * A shortcut to the {@link Messages.send} method.\n   *\n   * Send a message to the chat room using the Ably Chat API.\n   *\n   * **Important**: The Promise may resolve before OR after the message is received\n   * from the realtime channel. This means subscribers may see the message before\n   * the send operation completes.\n   *\n   * **NOTE**: This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param params - Message parameters containing the text and optional metadata/headers\n   * @returns A Promise that resolves to the sent {@link Message} object, or rejects with:\n   * - {@link Ably.ErrorInfo} when the message fails to send due to network issues, authentication problems, or rate limiting\n   * @example\n   * ```tsx\n   * const { sendMessage } = useMessages();\n   *\n   * const handleSendMessage = async () => {\n   *   try {\n   *     await sendMessage({\n   *       text: 'Hello world!',\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to send message:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly sendMessage: (params: SendMessageParams) => Promise<Message>;\n\n  /**\n   * A shortcut to the {@link Messages.get} method.\n   *\n   * Get a specific message by its unique serial identifier.\n   *\n   * This method retrieves a single message using its serial, which is a unique\n   * identifier assigned to each message when it's created.\n   *\n   * **NOTE**: This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique serial identifier of the message to retrieve\n   * @returns A Promise that resolves to the {@link Message} object, or rejects with:\n   * - {@link Ably.ErrorInfo} when the message is not found or network/server errors occur\n   * @example\n   * ```tsx\n   * const { getMessage } = useMessages();\n   *\n   * const handleGetMessage = async (messageSerial: string) => {\n   *   try {\n   *     const message = await getMessage(messageSerial);\n   *     console.log('Retrieved message:', message.text);\n   *     console.log('From:', message.clientId);\n   *   } catch (error) {\n   *     console.error('Failed to get message:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly getMessage: (serial: string) => Promise<Message>;\n\n  /**\n   * A shortcut to the {@link Messages.getVersions} method.\n   *\n   * Get all versions of a message by its serial, in oldest-first order.\n   *\n   * Returns the original create event followed by any subsequent update and delete events.\n   *\n   * **NOTE**: This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique serial identifier of the message.\n   * @returns A Promise that resolves to a {@link PaginatedResult} of {@link Message} objects representing each version,\n   * or rejects with:\n   * - {@link Ably.ErrorInfo} when the serial is null, undefined, or empty\n   * - {@link Ably.ErrorInfo} when the Ably Chat REST API request fails due to network or authorization errors\n   * @example\n   * ```tsx\n   * const { getVersions } = useMessages();\n   *\n   * const handleGetVersions = async (messageSerial: string) => {\n   *   try {\n   *     const versions = await getVersions(messageSerial);\n   *     for (const version of versions.items) {\n   *       console.log(version.action, version.text);\n   *     }\n   *   } catch (error) {\n   *     console.error('Failed to get message versions:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly getVersions: (serial: string) => Promise<PaginatedResult<Message>>;\n\n  /**\n   * A shortcut to the {@link Messages.update} method.\n   *\n   * Update a message in the chat room.\n   *\n   * This method modifies an existing message's content, metadata, or headers.\n   * The update creates a new version of the message while preserving the original\n   * serial identifier. Subscribers will receive an update event in real-time.\n   *\n   * **Important**: The Promise may resolve before OR after the update event is received\n   * from the realtime channel. Subscribers may see the update event before this method\n   * completes.\n   *\n   * **Note**:\n   * - This method uses PUT-like semantics. If metadata or headers are omitted\n   * from updateParams, they will be replaced with empty objects, not merged with existing values.\n   * - The returned Message instance represents the state after the update. If you\n   * have active subscriptions, use the event payloads from those subscriptions instead\n   * of the returned instance for consistency.\n   * - This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique identifier of the message to update\n   * @param updateParams - The new message content and properties\n   * @param details - Optional details to record about the update action\n   * @returns A Promise that resolves to the updated {@link Message} object with\n   *          `isUpdated` set to true and update metadata populated, or rejects with:\n   * - {@link Ably.ErrorInfo} when the message is not found, user lacks permissions,\n   *           or network/server errors occur\n   * @example\n   * ```tsx\n   * const { updateMessage } = useMessages();\n   *\n   * const handleUpdateMessage = async (serial: string, newText: string) => {\n   *   try {\n   *     await updateMessage(serial, {\n   *       text: newText\n   *     }, {\n   *       description: 'User edited message'\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to update message:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly updateMessage: (\n    serial: string,\n    updateParams: UpdateMessageParams,\n    details?: OperationDetails,\n  ) => Promise<Message>;\n\n  /**\n   * A shortcut to the {@link Messages.history} method.\n   *\n   * Get messages that have been previously sent to the chat room.\n   *\n   * This method retrieves historical messages based on the provided query options,\n   * allowing you to paginate through message history, filter by time ranges,\n   * and control the order of results.\n   *\n   * **NOTE**: This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param params - Query parameters to filter and control the message retrieval\n   * @returns A Promise that resolves to a {@link PaginatedResult} containing an array of {@link Message} objects\n   *          and methods for pagination control, or rejects with {@link ErrorCode.InvalidArgument} when the query fails due to invalid parameters\n   * @example\n   * ```tsx\n   * const { history } = useMessages();\n   *\n   * const loadHistory = async () => {\n   *   try {\n   *     const result = await history({\n   *       limit: 50,\n   *       orderBy: OrderBy.NewestFirst\n   *     });\n   *     console.log('Previous messages:', result.items);\n   *\n   *     // Paginate through additional pages if available\n   *     if (result.hasNext()) {\n   *       const nextPage = await result.next();\n   *       console.log('Next page:', nextPage?.items);\n   *     }\n   *   } catch (error) {\n   *     console.error('Failed to load history:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly history: (params: HistoryParams) => Promise<PaginatedResult<Message>>;\n\n  /**\n   * A shortcut to the {@link Messages.delete} method.\n   *\n   * Delete a message in the chat room.\n   *\n   * This method performs a \"soft delete\" on a message, marking it as deleted rather\n   * than permanently removing it. The deleted message will still be visible in message\n   * history but will be flagged as deleted. Subscribers will receive a deletion event\n   * in real-time.\n   *\n   * **Important**: The Promise may resolve before OR after the deletion event is received\n   * from the realtime channel. Subscribers may see the deletion event before this method\n   * completes.\n   *\n   * **Note**:\n   * - The returned Message instance represents the state after deletion. If you\n   * have active subscriptions, use the event payloads from those subscriptions instead\n   * of the returned instance for consistency.\n   * - This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique identifier of the message to delete\n   * @param details - Optional details to record about the delete action\n   * @returns A Promise that resolves to the deleted {@link Message} object with\n   *          `isDeleted` set to true and deletion metadata populated, or rejects with:\n   * - {@link Ably.ErrorInfo} when the message is not found, user lacks permissions,\n   *            or network/server errors occur\n   * @example\n   * ```tsx\n   * const { deleteMessage } = useMessages();\n   *\n   * const handleDeleteMessage = async (serial: string) => {\n   *   try {\n   *     await deleteMessage(serial, {\n   *       description: 'User deleted message'\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to delete message:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly deleteMessage: (serial: string, details?: OperationDetails) => Promise<Message>;\n\n  /**\n   * A shortcut to the {@link MessageReactions.send} method.\n   *\n   * Sends a reaction to a specific chat message.\n   *\n   * **Note**:\n   * - The behavior depends on the reaction type configured for the room.\n   * - This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique identifier of the message to react to\n   * @param params - The reaction parameters including the reaction name\n   * @returns A Promise that resolves when the reaction has been sent, or rejects with {@link Ably.ErrorInfo}\n   * @example\n   * ```tsx\n   * const { sendReaction } = useMessages();\n   *\n   * const handleSendReaction = async (messageSerial: string, emoji: string) => {\n   *   try {\n   *     await sendReaction(messageSerial, {\n   *       name: emoji\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to send reaction:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly sendReaction: (serial: string, params: SendMessageReactionParams) => Promise<void>;\n\n  /**\n   * A shortcut to the {@link MessageReactions.delete} method.\n   *\n   * Deletes a previously sent reaction from a chat message.\n   *\n   * The deletion behavior depends on the reaction type:\n   * - **Unique**: Removes the client's single reaction (name not required)\n   * - **Distinct**: Removes a specific reaction by name\n   * - **Multiple**: Removes all instances of a reaction by name\n   *\n   * **Note**: This method uses the Ably Chat REST API and so does not require the room\n   * to be attached to be called.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param serial - The unique identifier of the message to remove the reaction from\n   * @param params - Optional parameters specifying which reaction to delete\n   * @returns A Promise that resolves when the reaction has been deleted, or rejects with {@link Ably.ErrorInfo}\n   * @example\n   * ```tsx\n   * const { deleteReaction } = useMessages();\n   *\n   * const handleDeleteReaction = async (messageSerial: string, emoji: string) => {\n   *   try {\n   *     await deleteReaction(messageSerial, {\n   *       name: emoji\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to delete reaction:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly deleteReaction: (serial: string, params?: DeleteMessageReactionParams) => Promise<void>;\n\n  /**\n   * Retrieves the previous messages in the room.\n   *\n   * This method is available only if a {@link MessageListener} has been provided in the {@link UseMessagesParams}.\n   * Calling will return a promise that resolves to a paginated response of the previous messages received in the room,\n   * up until the listener was attached, in newest-to-oldest order.\n   *\n   * It is advised to call this method after any discontinuity event; to retrieve messages that may have been missed\n   * before the listener was re-attached.\n   *\n   * See the {@link MessageSubscriptionResponse.historyBeforeSubscribe} documentation for more details.\n   *\n   * This is removed when the component unmounts or when the previously provided listener is removed.\n   * @defaultValue - This will be undefined if no listener is provided in the {@link UseMessagesParams}.\n   */\n  readonly historyBeforeSubscribe?: MessageSubscriptionResponse['historyBeforeSubscribe'];\n}\n\nexport interface UseMessagesParams extends StatusParams, Listenable<MessageListener> {\n  /**\n   * An optional listener that can be provided to receive new messages in the room.\n   * The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * useMessages({\n   *   listener: (event) => {\n   *     console.log(`Message ${event.type}:`, event.message.text);\n   *   }\n   * });\n   * ```\n   */\n  listener?: MessageListener;\n\n  /**\n   * An optional listener that can be provided to receive reaction summaries to\n   * messages in the room. The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * useMessages({\n   *   reactionsListener: (event) => {\n   *     console.log('Reaction summary:', event.summary);\n   *   }\n   * });\n   * ```\n   */\n  reactionsListener?: MessageReactionListener;\n\n  /**\n   * An optional listener that can be provided to receive individual reactions\n   * to messages in the room. The listener is removed when the component\n   * unmounts.\n   * @example\n   * ```tsx\n   * useMessages({\n   *   rawReactionsListener: (event) => {\n   *     console.log('Raw reaction:', event.reaction.type);\n   *   }\n   * });\n   * ```\n   */\n  rawReactionsListener?: MessageRawReactionListener;\n}\n\n/**\n *\n * A hook that provides access to the {@link Messages} instance in the room.\n *\n * If a listener is provided, it will subscribe to new messages in the room,\n * and will also set the {@link UseMessagesResponse.historyBeforeSubscribe}.\n *\n * **Note**:\n * - This hook must be used within a {@link ChatRoomProvider} component tree.\n * - Room must be attached to receive message events, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for event listeners and room status callbacks\n * @returns A {@link UseMessagesResponse} containing message methods and room status\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Message listener and state management\n * ```tsx\n * import React, { useState } from 'react';\n * import { ChatClient, ChatMessageEventType, Message, ChatMessageEvent, MessageReactionSummaryEvent } from '@ably/chat';\n * import { ChatClientProvider, ChatRoomProvider, useMessages } from '@ably/chat/react';\n *\n * // Helper function to update local message state\n * const updateLocalMessageState = (messages: Message[], message: Message): Message[] => {\n *   // Find existing message in local state\n *   const existingIndex = messages.findIndex(m => m.serial === message.serial);\n *   let updatedMessages = [...messages];\n *\n *   if (existingIndex === -1) {\n *     // New message, add to local state\n *     updatedMessages.push(message);\n *   } else {\n *     // Update existing message using with() method\n *     updatedMessages[existingIndex] = updatedMessages[existingIndex].with(message);\n *   }\n *   // Sort by serial for deterministic ordering\n *   return updatedMessages.sort((a, b) => a.serial < b.serial ? -1 : (b.serial < a.serial ? 1 : 0));\n * };\n *\n * // Component that handles messages\n * const MessageHandler = () => {\n *   const [messages, setMessages] = useState<Message[]>([]);\n *\n *   const { sendMessage } = useMessages({\n *     listener: (event: ChatMessageEvent) => {\n *       console.log(`Message ${event.type}:`, event.message.text);\n *\n *       setMessages(prevMessages => {\n *         switch (event.type) {\n *           case ChatMessageEventType.Created:\n *           case ChatMessageEventType.Updated:\n *           case ChatMessageEventType.Deleted:\n *             return updateLocalMessageState(prevMessages, event.message);\n *           default:\n *             return prevMessages;\n *         }\n *       });\n *     },\n *     reactionsListener: (event: MessageReactionSummaryEvent) => {\n *       // Update message with new reaction data using with() method\n *       setMessages(prevMessages => {\n *         const messageIndex = prevMessages.findIndex(m => m.serial === event.messageSerial);\n *         if (messageIndex === -1) {\n *           // Message not found, return unchanged\n *           return prevMessages;\n *         }\n *\n *         // Update the specific message and return new array\n *         const updatedMessages = [...prevMessages];\n *         updatedMessages[messageIndex] = updatedMessages[messageIndex].with(event);\n *         return updatedMessages;\n *       });\n *     },\n *     onDiscontinuity: (error) => {\n *       console.error('Discontinuity detected:', error);\n *       // Clear local state and optionally re-fetch messages using historyBeforeSubscribe.\n *       setMessages([]);\n *     }\n *   });\n *\n *   return (\n *     <div>\n *       {messages.map(message => (\n *         <div key={message.serial}>\n *           <strong>{message.clientId}:</strong> {message.isDeleted ? <em>Deleted Message</em>: message.text}\n *             <div>\n *               {Object.entries(message.reactions.unique).map(([reaction, summary]) => (\n *                 <span key={`unique-${reaction}`}>{reaction} {summary.total}</span>\n *               ))}\n *               {Object.entries(message.reactions.distinct).map(([reaction, summary]) => (\n *                 <span key={`distinct-${reaction}`}>{reaction} {summary.total}</span>\n *               ))}\n *               {Object.entries(message.reactions.multiple).map(([reaction, summary]) => (\n *                 <span key={`multiple-${reaction}`}>{reaction} {summary.total}</span>\n *               ))}\n *             </div>\n *         </div>\n *       ))}\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"general-chat\">\n *         <MessageHandler />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n * ```\n */\nexport const useMessages = (params?: UseMessagesParams): UseMessagesResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n  const context = useRoomContext('useMessages');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n\n  const logger = useRoomLogger();\n  logger.trace('useMessages();', { params });\n\n  // we are storing the params in a ref so that we don't end up with an infinite loop should the user pass\n  // in an unstable reference\n  const listenerRef = useEventListenerRef(params?.listener);\n  const reactionsListenerRef = useEventListenerRef(params?.reactionsListener);\n  const rawReactionsListenerRef = useEventListenerRef(params?.rawReactionsListener);\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  const sendMessage = useCallback(\n    async (params: SendMessageParams) => {\n      const room = await context.room;\n      return room.messages.send(params);\n    },\n    [context],\n  );\n\n  const getMessage = useCallback(\n    async (serial: string) => {\n      const room = await context.room;\n      return room.messages.get(serial);\n    },\n    [context],\n  );\n\n  const getVersions = useCallback(\n    async (serial: string) => {\n      const room = await context.room;\n      return room.messages.getVersions(serial);\n    },\n    [context],\n  );\n\n  const deleteMessage = useCallback(\n    async (serial: string, details?: OperationDetails) => {\n      const room = await context.room;\n      return room.messages.delete(serial, details);\n    },\n    [context],\n  );\n\n  const history = useCallback(\n    async (params: HistoryParams) => {\n      const room = await context.room;\n      return room.messages.history(params);\n    },\n    [context],\n  );\n\n  const updateMessage = useCallback(\n    async (serial: string, updateParams: UpdateMessageParams, details?: OperationDetails) => {\n      const room = await context.room;\n      return room.messages.update(serial, updateParams, details);\n    },\n    [context],\n  );\n\n  const sendReaction: Messages['reactions']['send'] = useCallback(\n    async (serial: string, params: SendMessageReactionParams) => {\n      const room = await context.room;\n      return room.messages.reactions.send(serial, params);\n    },\n    [context],\n  );\n\n  const deleteReaction: Messages['reactions']['delete'] = useCallback(\n    async (serial: string, params?: DeleteMessageReactionParams) => {\n      const room = await context.room;\n      return room.messages.reactions.delete(serial, params);\n    },\n    [context],\n  );\n\n  const [historyBeforeSubscribe, setHistoryBeforeSubscribe] =\n    useState<MessageSubscriptionResponse['historyBeforeSubscribe']>();\n\n  useEffect(() => {\n    if (!listenerRef) return;\n\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        let unmounted = false;\n        logger.debug('useMessages(); applying listener');\n        const sub = room.messages.subscribe(listenerRef);\n\n        // set the historyBeforeSubscribe method if a listener is provided\n        setHistoryBeforeSubscribe(() => {\n          logger.debug('useMessages(); setting historyBeforeSubscribe state', {\n            status: room.status,\n            unmounted,\n          });\n          if (unmounted) {\n            return;\n          }\n\n          return async (params: Omit<HistoryParams, 'orderBy'>) => {\n            // If we've unmounted, then the subscription is gone and we can't call historyBeforeSubscribe\n            // So return a dummy object that should be thrown away anyway\n            logger.debug('useMessages(); historyBeforeSubscribe called');\n            if (unmounted) {\n              throw new Ably.ErrorInfo(\n                'unable to query messages; component unmounted',\n                ErrorCode.ReactComponentUnmounted,\n                400,\n              );\n            }\n            return sub.historyBeforeSubscribe(params);\n          };\n        });\n\n        return () => {\n          logger.debug('useMessages(); removing listener and historyBeforeSubscribe state');\n          unmounted = true;\n          sub.unsubscribe();\n          setHistoryBeforeSubscribe(undefined);\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger, listenerRef]);\n\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useMessages(); applying onDiscontinuity listener');\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n        return () => {\n          logger.debug('useMessages(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger, onDiscontinuityRef]);\n\n  useEffect(() => {\n    if (!reactionsListenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useMessages(); applying reactions listener');\n        const { unsubscribe } = room.messages.reactions.subscribe(reactionsListenerRef);\n        return () => {\n          logger.debug('useMessages(); removing reactions listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger, reactionsListenerRef]);\n\n  useEffect(() => {\n    if (!rawReactionsListenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useMessages(); applying raw reactions listener');\n        const { unsubscribe } = room.messages.reactions.subscribeRaw(rawReactionsListenerRef);\n        return () => {\n          logger.debug('useMessages(); removing raw reactions listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger, rawReactionsListenerRef]);\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    sendMessage,\n    getMessage,\n    getVersions,\n    updateMessage,\n    history,\n    deleteMessage,\n    sendReaction,\n    deleteReaction,\n    historyBeforeSubscribe,\n  };\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport { useEffect, useState } from 'react';\n\nimport { OccupancyListener } from '../../core/occupancy.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { Listenable } from '../types/listenable.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The options for the {@link useOccupancy} hook.\n */\nexport interface UseOccupancyParams extends StatusParams, Listenable<OccupancyListener> {\n  /**\n   * A listener that will be called whenever an occupancy event is received.\n   * The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * useOccupancy({\n   *   listener: (occupancyEvent) => {\n   *     console.log('Occupancy changed:', occupancyEvent.occupancy);\n   *   }\n   * });\n   * ```\n   */\n  listener?: OccupancyListener;\n}\n\n/**\n * The response type from the {@link useOccupancy} hook.\n */\nexport interface UseOccupancyResponse extends ChatStatusResponse {\n  /**\n   * The current number of users connected to the room, kept up to date by the hook.\n   */\n  readonly connections: number;\n\n  /**\n   * The current number of users present in the room, kept up to date by the hook.\n   */\n  readonly presenceMembers: number;\n}\n\n/**\n * React hook that provides real-time room occupancy information.\n *\n * This hook automatically tracks the number of connections and presence members in a room,\n * updating the counts in real-time as users join and leave. It integrates with the nearest\n * {@link ChatRoomProvider} and handles cleanup when the component unmounts.\n *\n * The hook provides both the current occupancy metrics as state values and allows you to\n * register listeners for occupancy change events.\n *\n * **Note**: This hook must be used within a {@link ChatRoomProvider} component tree.\n * **Note**: Room must be attached to receive real-time occupancy updates, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for event listeners and room status callbacks\n * @returns A {@link UseOccupancyResponse} containing current occupancy metrics and room status\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Basic usage\n * ```tsx\n * import React from 'react';\n * import { ChatClient, OccupancyEvent } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   useOccupancy\n * } from '@ably/chat/react';\n *\n * // Component that displays occupancy information\n * const RoomOccupancy = () => {\n *   const {\n *     connections,\n *     presenceMembers,\n *     connectionStatus,\n *     roomStatus\n *   } = useOccupancy({\n *     listener: (occupancyEvent: OccupancyEvent) => {\n *       console.log('Occupancy changed:', occupancyEvent.occupancy);\n *     },\n *     onDiscontinuity: (error) => {\n *       console.error('Discontinuity detected:', error);\n *     }\n *   });\n *\n *   return (\n *     <div>\n *       <div>👥 Total Connections: {connections}</div>\n *       <div>🟢 Present Members: {presenceMembers}</div>\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with providers\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"public-lobby\">\n *         <RoomOccupancy />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useOccupancy = (params?: UseOccupancyParams): UseOccupancyResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n  const context = useRoomContext('useOccupancy');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n\n  const logger = useRoomLogger();\n  logger.trace('useOccupancy();', { params });\n\n  const [occupancyMetrics, setOccupancyMetrics] = useState<{ connections: number; presenceMembers: number }>({\n    connections: 0,\n    presenceMembers: 0,\n  });\n\n  // create stable references for the listeners\n  const listenerRef = useEventListenerRef(params?.listener);\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  // if provided, subscribes the user provided discontinuity listener\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useOccupancy(); applying onDiscontinuity listener');\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n        return () => {\n          logger.debug('useOccupancy(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, onDiscontinuityRef, logger]);\n\n  // subscribe to occupancy events internally, to update the state metrics\n  useEffect(() => {\n    const roomPromise = wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useOccupancy(); applying internal listener');\n        // Set the initial metrics from current(), or 0 if not available\n        const currentOccupancy = room.occupancy.current;\n        setOccupancyMetrics({\n          connections: currentOccupancy?.connections ?? 0,\n          presenceMembers: currentOccupancy?.presenceMembers ?? 0,\n        });\n\n        const { unsubscribe } = room.occupancy.subscribe((occupancyEvent) => {\n          setOccupancyMetrics({\n            connections: occupancyEvent.occupancy.connections,\n            presenceMembers: occupancyEvent.occupancy.presenceMembers,\n          });\n        });\n        return () => {\n          logger.debug('useOccupancy(); cleaning up internal listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    );\n\n    return roomPromise.unmount();\n  }, [context, logger]);\n\n  // if provided, subscribes the user provided listener to occupancy events\n  useEffect(() => {\n    if (!listenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useOccupancy(); applying listener');\n        const { unsubscribe } = room.occupancy.subscribe(listenerRef);\n        return () => {\n          logger.debug('useOccupancy(); cleaning up listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [listenerRef, context, logger]);\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    connections: occupancyMetrics.connections,\n    presenceMembers: occupancyMetrics.presenceMembers,\n  };\n};\n","import * as Ably from '@ably/pubsub-core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { ConnectionStatus } from '../../core/connection.js';\nimport { Presence, PresenceData, PresenceStateChange, PresenceStateChangeListener } from '../../core/presence.js';\nimport { Room } from '../../core/room.js';\nimport { RoomStatus } from '../../core/room-status.js';\nimport { Subscription } from '../../core/subscription.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The options for the {@link usePresence} hook.\n */\nexport interface UsePresenceParams extends StatusParams {\n  /**\n   * The initial data to enter the room with when auto-entering (autoEnterLeave=true). Any JSON serializable data can be provided.\n   * This data is only used for the initial auto-enter when the component mounts. Changes to this value\n   * after the first render are ignored. To update presence data after the initial enter, use the\n   * `update` or `enter` methods returned by the hook.\n   * @example\n   * ```tsx\n   * // This will cause the hook to auto-enter presence with the provided data\n   * // autoEnterLeave is implicitly true\n   * const { presence, update } = usePresence({\n   *   initialData: { status: 'online', lastSeen: Date.now() }\n   * });\n   *\n   * // Subsequent data updates must be done via calls to enter/update\n   * await update({status: 'away'});\n   * ```\n   * @defaultValue undefined\n   */\n  initialData?: PresenceData;\n\n  /**\n   * Controls whether the hook should automatically enter presence when the component mounts and the room\n   * becomes attached, and automatically leave presence when the component unmounts.\n   *\n   * Also controls whether the hook will automatically re-enter presence if the room is detached and then re-attached.\n   *\n   * **Important** If {@link UsePresenceResponse.leave} is called, then the hook will NOT auto-enter. To re-enable\n   * auto-enter behavior, you must call {@link UsePresenceResponse.enter} or {@link UsePresenceResponse.update}.\n   * When set to false, you have full manual control over entering and leaving presence.\n   *\n   * Defaults to true if not provided.\n   * @defaultValue true\n   */\n  autoEnterLeave?: boolean;\n}\n\nexport interface UsePresenceResponse extends ChatStatusResponse {\n  /**\n   * A shortcut to the {@link Presence.update} method.\n   *\n   * Updates the presence data for the current user in the chat room.\n   * Emits an 'update' event to all subscribers. If the user is not already present, they will be entered automatically.\n   *\n   * **Note**:\n   * - The room must be attached before calling this method.\n   * - This method uses PUT-like semantics - the entire presence data is replaced with the new value.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   *\n   * **Important** When called, if {@link UsePresenceParams.autoEnterLeave} is set to true, the hook will attempt to\n   * auto-enter presence automatically when conditions are met.\n   * @param data - JSON-serializable data to replace the user's current presence data\n   * @returns Promise that resolves when the presence data has been updated,\n   *          or rejects with {@link chat-js!ErrorCode.RoomInInvalidState | RoomInInvalidState} if the room is not attached\n   */\n  readonly update: (data?: PresenceData) => Promise<void>;\n\n  /**\n   * A shortcut to the {@link Presence.enter} method, which can be used to manually enter presence when\n   * `autoEnterLeave` is false, or to explicitly re-enter presence with new data.\n   *\n   * Enters the current user into the chat room presence set.\n   * Emits an 'enter' event to all presence subscribers. Multiple calls will emit additional `update` events if the\n   * user is already present.\n   *\n   * **Note**: The room must be attached before calling this method.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   *\n   * **Important** When called, if {@link UsePresenceParams.autoEnterLeave} is set to true, the hook will attempt to\n   * auto-enter presence automatically when conditions are met.\n   * @param data - Optional JSON-serializable data to associate with the user's presence\n   * @returns Promise that resolves when the user has successfully entered,\n   *          or rejects with {@link chat-js!ErrorCode.RoomInInvalidState | RoomInInvalidState} if the room is not attached\n   * @example\n   * ```tsx\n   * // Manual control over presence with conditional logic\n   * const { enter, leave } = usePresence({ autoEnterLeave: false });\n   *\n   * useEffect(() => {\n   *   if (effectCondition) {\n   *     enter({ status: 'active' });\n   *   }\n   *\n   *   return () => {\n   *     if (effectCondition) {\n   *       leave();\n   *     }\n   *   };\n   * }, [effectCondition, enter, leave]);\n   * ```\n   */\n  readonly enter: (data?: PresenceData) => Promise<void>;\n\n  /**\n   * A shortcut to the {@link Presence.leave} method.\n   *\n   * Removes the current user from the chat room presence set.\n   * Emits a 'leave' event to all subscribers. If the user is not present, this is a no-op.\n   *\n   * **Note**: The room must be attached before calling this method.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   *\n   * **Important** When called, this will prevent the hook from automatically re-entering presence, even when `autoEnterLeave` is true.\n   *\n   * This is useful for manually controlling when presence is left.\n   * @param data - Optional final presence data to include with the leave event\n   * @returns Promise that resolves when the user has left the presence set,\n   *          or rejects with {@link chat-js!ErrorCode.RoomInInvalidState | RoomInInvalidState} if the room is not attached\n   * @example\n   * ```tsx\n   * // Manual control over presence with conditional logic\n   * const { enter, leave } = usePresence({ autoEnterLeave: false });\n   *\n   * useEffect(() => {\n   *   if (effectCondition) {\n   *     enter({ status: 'active' });\n   *   }\n   *\n   *   return () => {\n   *     if (effectCondition) {\n   *       leave();\n   *     }\n   *   };\n   * }, [effectCondition, enter, leave]);\n   * ```\n   * @example\n   * ```tsx\n   * // Enter presence automatically with some initial data\n   * const { leave, enter } = usePresence({ initialData: { status: 'online' } });\n   *\n   * // Leave presence explicitly, disabling auto re-entry\n   * await leave();\n   *\n   * // Re-enter presence again, re-enabling auto-entry if selected in the hook\n   * await enter({ status: 'online again' })\n   * ```\n   */\n  readonly leave: (data?: PresenceData) => Promise<void>;\n\n  /**\n   * The current presence state of this client.\n   */\n  readonly myPresenceState: {\n    /**\n     * Indicates if the user is currently present in the room.\n     */\n    present: boolean;\n\n    /**\n     * Indicates if an error occurred while trying to enter or leave presence.\n     */\n    error?: Ably.ErrorInfo;\n  };\n}\n\n// Internal interface for presence with state change subscription\ninterface PresenceWithStateChangeListener extends Presence {\n  onPresenceStateChange(listener: PresenceStateChangeListener): Subscription;\n}\n\n/**\n * A set of connection states that are considered inactive and where presence operations should not be attempted.\n */\nconst INACTIVE_CONNECTION_STATES = new Set<ConnectionStatus>([\n  ConnectionStatus.Suspended,\n  ConnectionStatus.Failed,\n  ConnectionStatus.Closing,\n  ConnectionStatus.Closed,\n]);\n\n/**\n * React hook that manages user presence in a chat room.\n *\n * This hook provides comprehensive presence functionality with both automatic and manual\n * control modes. It handles entering/leaving presence, updating presence data, and\n * tracking the current presence state with automatic recovery after disconnections.\n *\n * By default (`autoEnterLeave: true`), the hook automatically enters presence when the\n * component mounts and the room is attached, and leaves when unmounting. It also handles\n * automatic re-entry after room detachment/reattachment cycles.\n *\n * With `autoEnterLeave: false`, you have full manual control over presence lifecycle\n * using the returned `enter` and `leave` methods.\n *\n * **Important**: When using `autoEnterLeave`, avoid multiple instances of this hook within\n * the same ChatClientProvider, as they share the same underlying presence instance. For\n * multiple components updating presence data, either:\n * 1. Set `autoEnterLeave: false` and manage state manually\n * 2. Manage presence state at a higher level (e.g., context provider)\n *\n * **Note**: This hook must be used within a {@link ChatRoomProvider} component tree.\n * **Note**: Room must be attached and connection active for presence operations, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for initial data, auto-enter/leave behavior, and status callbacks\n * @returns A {@link UsePresenceResponse} containing presence methods and current state\n * @example\n * ```tsx\n * // Example with full manual control (no auto-enter/leave)\n * const ManualPresenceComponent = () => {\n *   const { enter, leave, update, myPresenceState } = usePresence({\n *     autoEnterLeave: false,\n *     initialData: { status: 'available' }\n *   });\n *\n *   const handleJoin = () => enter({ status: 'online' });\n *   const handleLeave = () => leave();\n *   const handleUpdateStatus = () => update({ status: 'busy' });\n *\n *   return (\n *     <div>\n *       <button onClick={handleJoin}>Join</button>\n *       <button onClick={handleLeave}>Leave</button>\n *       <button onClick={handleUpdateStatus}>Update Status</button>\n *       <div>Present: {myPresenceState.present}</div>\n *     </div>\n *   );\n * };\n * ```\n * @example\n * ```tsx\n * // Example with auto-enter but taking manual control via leave.\n * // This pattern is useful if you have multiple components in your app updating presence data.\n * const MixedControlComponent = () => {\n *   const { leave, update, myPresenceState } = usePresence({\n *     initialData: { status: 'online' }\n *   });\n *\n *   const handleGoOffline = () => {\n *     // Calling leave() prevents auto re-entry until enter() or update() is called\n *     leave({ status: 'offline' });\n *   };\n *\n *   const handleUpdatePresence = () => {\n *     // Calling update() re-enables auto-enter behavior\n *     update({ status: 'back online' });\n *   };\n *\n *   return (\n *     <div>\n *       <button onClick={handleGoOffline}>Go Offline</button>\n *       <button onClick={handleUpdatePresence}>Update Presence</button>\n *       <div>Present: {myPresenceState.present}</div>\n *     </div>\n *   );\n * };\n * ```\n * @example\n * ```tsx\n * // Example with manual mount/unmount behavior using enter/leave explicitly\n * const ManualMountComponent = () => {\n *   const { enter, leave, myPresenceState } = usePresence({\n *     autoEnterLeave: false,\n *     initialData: { status: 'ready' }\n *   });\n *\n *   // Manual mount behavior - enter presence when component mounts\n *   useEffect(() => {\n *     enter({ status: 'active' });\n *\n *     // Manual unmount behavior - leave presence when component unmounts\n *     return () => {\n *       leave({ status: 'disconnecting' });\n *     };\n *   }, [enter, leave]);\n *\n *   return <div>Present: {myPresenceState.present}</div>;\n * };\n * ```\n */\nexport const usePresence = (params?: UsePresenceParams): UsePresenceResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n\n  const context = useRoomContext('usePresence');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n  const logger = useRoomLogger();\n  logger.trace('usePresence();', { params });\n\n  // Default to true for autoEnterLeave if not provided\n  const shouldAutoEnterLeave = useMemo(() => params?.autoEnterLeave !== false, [params?.autoEnterLeave]);\n\n  const [myPresenceState, setMyPresenceState] = useState<{\n    present: boolean;\n    error?: Ably.ErrorInfo;\n  }>({\n    present: false,\n    error: undefined,\n  });\n\n  // store the roomStatus in a ref to ensure the correct value is used in the effect cleanup\n  const roomStatusAndConnectionStatusRef = useRef({ roomStatus, connectionStatus });\n\n  // create a stable reference for the onDiscontinuity listener\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  // Track the latest presence data - set initialData once on first render, then updated by manual calls\n  const latestDataRef = useRef<PresenceData>(params?.initialData);\n\n  // Track if leave() has been explicitly called - prevents auto re-enter\n  const hasExplicitlyLeftRef = useRef<boolean>(false);\n\n  // Track if we've ever successfully auto-entered (for first-time logic)\n  const hasAutoEnteredRef = useRef<boolean>(false);\n\n  // Track if room has been detached since last auto-enter (for recovery logic)\n  const roomWasDetachedRef = useRef<boolean>(false);\n\n  // If the context changes, then we'll assume auto-enter is required.\n  useEffect(() => {\n    hasAutoEnteredRef.current = false;\n    roomWasDetachedRef.current = false;\n  }, [context]);\n\n  // Keep track of the room and connection statuses\n  useEffect(() => {\n    roomStatusAndConnectionStatusRef.current = { roomStatus, connectionStatus };\n\n    // keep track of the room becoming detached\n    if (roomStatus === RoomStatus.Detached) {\n      roomWasDetachedRef.current = true;\n    }\n  }, [roomStatus, connectionStatus]);\n\n  // Subscribe to presence state changes\n  useEffect(() => {\n    logger.debug('usePresence(); subscribing to presence state changes');\n    return wrapRoomPromise(\n      context.room,\n      (room: Room) => {\n        // Subscribe to presence state changes\n        const subscription = (room.presence as PresenceWithStateChangeListener).onPresenceStateChange(\n          (stateChange: PresenceStateChange) => {\n            logger.debug('usePresence(); presence state changed', { stateChange });\n            setMyPresenceState({\n              ...stateChange.current,\n              error: stateChange.error,\n            });\n          },\n        );\n        return () => {\n          logger.debug('usePresence(); unsubscribing from presence state changes');\n          subscription.unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger]);\n\n  // enter the room when the hook is mounted (if autoEnterLeave is enabled)\n  useEffect(() => {\n    logger.debug('usePresence(); running auto-enter hook');\n    if (!shouldAutoEnterLeave) {\n      logger.debug('usePresence(); auto enter/leave disabled');\n      return () => {\n        // no-op\n      };\n    }\n\n    return wrapRoomPromise(\n      context.room,\n      (room: Room) => {\n        const canJoinPresence =\n          room.status === RoomStatus.Attached && !INACTIVE_CONNECTION_STATES.has(connectionStatus);\n\n        // Check if we should auto-enter: first time OR room was previously detached\n        const shouldAutoEnter = !hasAutoEnteredRef.current || roomWasDetachedRef.current;\n\n        // wait until the room is attached before attempting to enter, and ensure the connection is active\n        // also check if we haven't explicitly left presence and if we should auto-enter\n        if (!canJoinPresence || hasExplicitlyLeftRef.current || !shouldAutoEnter) {\n          logger.debug('usePresence(); skipping enter room', {\n            roomStatus,\n            connectionStatus,\n            hasExplicitlyLeft: hasExplicitlyLeftRef.current,\n            shouldAutoEnter,\n            hasAutoEntered: hasAutoEnteredRef.current,\n            roomWasDetached: roomWasDetachedRef.current,\n          });\n          return () => {\n            // no-op\n          };\n        }\n\n        // Enter the room using latest data - state updates are handled by presence.ts\n        logger.debug('usePresence(); entering room');\n        room.presence\n          .enter(latestDataRef.current)\n          .then(() => {\n            logger.debug('usePresence(); entered room');\n            // Mark that we've successfully auto-entered and reset the detachment flag\n            hasAutoEnteredRef.current = true;\n            roomWasDetachedRef.current = false;\n          })\n          .catch((error: unknown) => {\n            logger.error('usePresence(); error entering room', { error });\n          });\n\n        return () => {\n          const canLeavePresence =\n            room.status === RoomStatus.Attached &&\n            !INACTIVE_CONNECTION_STATES.has(roomStatusAndConnectionStatusRef.current.connectionStatus);\n\n          logger.debug('usePresence(); unmounting', {\n            canLeavePresence,\n            roomStatus,\n            connectionStatus,\n          });\n          if (canLeavePresence && !hasExplicitlyLeftRef.current) {\n            // Only auto-leave if we haven't already explicitly left\n            // Leave the room - state updates are handled by presence.ts\n            room.presence\n              .leave()\n              .then(() => {\n                logger.debug('usePresence(); left room');\n              })\n              .catch((error: unknown) => {\n                logger.error('usePresence(); error leaving room', { error });\n              });\n          }\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, connectionStatus, roomStatus, logger, shouldAutoEnterLeave]);\n\n  // if provided, subscribes the user provided onDiscontinuity listener\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room: Room) => {\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n        return () => {\n          logger.debug('usePresence(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, onDiscontinuityRef, logger]);\n\n  // memoize the methods to avoid re-renders and ensure the same instance is used\n  const update = useCallback(\n    async (data?: PresenceData) => {\n      latestDataRef.current = data;\n      // Reset the explicit leave flag when update is called explicitly\n      hasExplicitlyLeftRef.current = false;\n      const room = await context.room;\n      await room.presence.update(data);\n    },\n    [context],\n  );\n\n  const enter = useCallback(\n    async (data?: PresenceData) => {\n      latestDataRef.current = data;\n      // Reset the explicit leave flag when enter is called explicitly\n      hasExplicitlyLeftRef.current = false;\n      const room = await context.room;\n      await room.presence.enter(data);\n    },\n    [context],\n  );\n\n  const leave = useCallback(\n    async (data?: PresenceData) => {\n      // Mark that leave has been explicitly called\n      hasExplicitlyLeftRef.current = true;\n      const room = await context.room;\n      await room.presence.leave(data);\n    },\n    [context],\n  );\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    update: update,\n    enter: enter,\n    leave: leave,\n    myPresenceState,\n  };\n};\n","import * as Ably from '@ably/pubsub-core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { ErrorCode, errorInfoIs } from '../../core/errors.js';\nimport { PresenceListener, PresenceMember } from '../../core/presence.js';\nimport { Room } from '../../core/room.js';\nimport { RoomStatus } from '../../core/room-status.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { Listenable } from '../types/listenable.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The interval between retries when fetching presence data.\n */\nconst PRESENCE_GET_RETRY_INTERVAL_MS = 1500;\n\n/**\n * The maximum interval between retries when fetching presence data.\n */\nconst PRESENCE_GET_RETRY_MAX_INTERVAL_MS = 30000;\n\n/**\n * The maximum number of retries when fetching presence data with {@link Presence.get}.\n */\nconst PRESENCE_GET_MAX_RETRIES = 5;\n\n/**\n * The options for the {@link usePresenceListener} hook.\n */\nexport interface UsePresenceListenerParams extends StatusParams, Listenable<PresenceListener> {\n  /**\n   * The listener to be called when the presence state changes.\n   * The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * usePresenceListener({\n   *   listener: (presenceEvent) => {\n   *     console.log('Presence event:', presenceEvent.type, presenceEvent.member.clientId);\n   *   }\n   * });\n   * ```\n   */\n  listener?: PresenceListener;\n}\n\nexport interface UsePresenceListenerResponse extends ChatStatusResponse {\n  /**\n   * The current state of all the presence members, observed as a whole change, and only emitted while presence is not syncing.\n   */\n  readonly presenceData: PresenceMember[];\n\n  /**\n   * The error state of the presence listener.\n   * The hook keeps {@link presenceData} up to date asynchronously, so this error state is provided to allow\n   * the user to handle errors that may occur when fetching presence data.\n   * It will be set if there is an error fetching the initial presence data,\n   * or if there is an error when fetching presence data after a presence event.\n   * The error will be cleared once a new presence event is received and successfully processed.\n   */\n  readonly error?: Ably.ErrorInfo;\n}\n\n/**\n * React hook that provides real-time presence data for all users in a room.\n *\n * This hook automatically subscribes to presence events and maintains an up-to-date\n * list of all presence members in the room.\n *\n * **Note**:\n * - This hook must be used within a {@link ChatRoomProvider} component tree.\n * - Room must be attached to receive presence updates, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for event listeners and room status callbacks\n * @returns A {@link UsePresenceListenerResponse} containing current presence data and error state\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Basic usage\n * ```tsx\n * import React from 'react';\n * import { ChatClient, PresenceEvent } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   usePresenceListener\n * } from '@ably/chat/react';\n *\n * // Component that displays all presence members\n * const PresenceList = () => {\n *   const { presenceData, error } = usePresenceListener({\n *     listener: (presenceEvent: PresenceEvent) => {\n *       console.log(`Presence ${presenceEvent.type}:`, presenceEvent.member);\n *     },\n *   });\n *\n *   if (error) {\n *     return <div>Error: {error.message}</div>;\n *   }\n *\n *   return (\n *     <div>\n *       <p>Total Members: {presenceData.length}</p>\n *       <ul>\n *         {presenceData.map((member) => (\n *           <li key={member.clientId}>👤 {member.clientId}</li>\n *         ))}\n *       </ul>\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with providers\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"team-room\">\n *         <PresenceList />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const usePresenceListener = (params?: UsePresenceListenerParams): UsePresenceListenerResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n\n  const context = useRoomContext('usePresenceListener');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n\n  const logger = useRoomLogger();\n  logger.trace('usePresenceListener();');\n\n  const receivedEventNumber = useRef(0);\n  const triggeredEventNumber = useRef(0);\n  const retryTimeout = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const numRetries = useRef(0);\n  const latestPresentData = useRef<PresenceMember[]>([]);\n  const [presenceData, setPresenceData] = useState<PresenceMember[]>([]);\n  const errorRef = useRef<Ably.ErrorInfo | undefined>(undefined);\n\n  const [error, setError] = useState<Ably.ErrorInfo | undefined>();\n\n  // create stable references for the listeners\n  const listenerRef = useEventListenerRef(params?.listener);\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  const setErrorState = useCallback(\n    (error: Ably.ErrorInfo) => {\n      logger.debug('usePresenceListener(); setting error state', { error });\n      errorRef.current = error;\n      setError(error);\n    },\n    [logger],\n  );\n\n  const clearErrorState = useCallback(() => {\n    logger.debug('usePresenceListener(); clearing error state');\n    errorRef.current = undefined;\n    setError(undefined);\n  }, [logger]);\n\n  useEffect(() => {\n    // ensure we only process and return the latest presence data.\n    const updatePresenceData = () => {\n      receivedEventNumber.current += 1;\n\n      // clear the previous retry if we have received a new event\n      if (retryTimeout.current) {\n        clearTimeout(retryTimeout.current);\n        retryTimeout.current = undefined;\n        numRetries.current = 0;\n      }\n\n      // attempt to get the presence data\n      getAndSetState(receivedEventNumber.current);\n    };\n\n    const getAndSetState = (eventNumber: number) => {\n      wrapRoomPromise(\n        context.room,\n        (room: Room) => {\n          room.presence\n            .get({ waitForSync: true })\n            .then((presenceMembers) => {\n              logger.debug('usePresenceListener(); fetched presence data', { presenceMembers });\n\n              // clear the retry now we have resolved\n              if (retryTimeout.current) {\n                clearTimeout(retryTimeout.current);\n                retryTimeout.current = undefined;\n                numRetries.current = 0;\n              }\n\n              // ensure the current event is still the latest\n              if (triggeredEventNumber.current >= eventNumber) {\n                return;\n              }\n\n              triggeredEventNumber.current = eventNumber;\n\n              // update the presence data\n              latestPresentData.current = presenceMembers;\n              setPresenceData(presenceMembers);\n\n              // clear any previous errors as we have now resolved to the latest state\n              if (errorRef.current) {\n                clearErrorState();\n              }\n            })\n            .catch(() => {\n              const willReattempt = numRetries.current < PRESENCE_GET_MAX_RETRIES;\n\n              if (!willReattempt) {\n                // since we have reached the maximum number of retries, set the error state\n                logger.error('usePresenceListener(); failed to fetch presence data after max retries');\n                setErrorState(\n                  new Ably.ErrorInfo(\n                    'unable to fetch presence data; failed after max retries',\n                    ErrorCode.PresenceFetchFailed,\n                    500,\n                  ),\n                );\n                return;\n              }\n\n              // if we are currently waiting for a retry, do nothing as a new event has been received\n              if (retryTimeout.current) {\n                logger.debug('usePresenceListener(); waiting for retry but new event received');\n                return;\n              }\n\n              const waitBeforeRetry = Math.min(\n                PRESENCE_GET_RETRY_MAX_INTERVAL_MS,\n                PRESENCE_GET_RETRY_INTERVAL_MS * Math.pow(2, numRetries.current),\n              );\n\n              numRetries.current += 1;\n              logger.debug('usePresenceListener(); retrying to fetch presence data', {\n                numRetries: numRetries.current,\n              });\n\n              retryTimeout.current = setTimeout(() => {\n                retryTimeout.current = undefined;\n                receivedEventNumber.current += 1;\n                getAndSetState(receivedEventNumber.current);\n              }, waitBeforeRetry);\n            });\n\n          return () => {\n            // No-op\n          };\n        },\n        logger,\n      );\n    };\n\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        let unsubscribe: (() => void) | undefined;\n        // If the room isn't attached yet, we can't do the initial fetch\n        if (room.status === RoomStatus.Attached) {\n          room.presence\n            .get({ waitForSync: true })\n            .then((presenceMembers) => {\n              logger.debug('usePresenceListener(); fetched initial presence data', {\n                presenceMembers,\n              });\n              // on mount, fetch the initial presence data\n              latestPresentData.current = presenceMembers;\n              setPresenceData(presenceMembers);\n\n              // clear any previous errors\n              clearErrorState();\n            })\n            .catch((error: unknown) => {\n              const errorInfo = error as Ably.ErrorInfo;\n              if (errorInfoIs(errorInfo, ErrorCode.RoomInInvalidState)) return;\n\n              logger.error('usePresenceListener(); error fetching initial presence data', {\n                error,\n              });\n              setErrorState(errorInfo);\n            })\n            .finally(() => {\n              // subscribe to presence events\n              logger.debug('usePresenceListener(); subscribing internal listener to presence events');\n              const result = room.presence.subscribe(() => {\n                updatePresenceData();\n              });\n              unsubscribe = result.unsubscribe;\n            });\n        } else {\n          // subscribe to presence events\n          logger.debug('usePresenceListener(); not yet attached, subscribing internal listener to presence events');\n          const result = room.presence.subscribe(() => {\n            updatePresenceData();\n          });\n          unsubscribe = result.unsubscribe;\n        }\n\n        return () => {\n          if (unsubscribe) {\n            logger.debug('usePresenceListener(); cleaning up internal listener');\n            unsubscribe();\n          }\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, setErrorState, clearErrorState, logger]);\n\n  // subscribe the user provided listener to presence changes\n  useEffect(() => {\n    if (!listenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('usePresenceListener(); applying external listener');\n        const { unsubscribe } = room.presence.subscribe(listenerRef);\n\n        return () => {\n          logger.debug('usePresenceListener(); cleaning up external listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, listenerRef, logger]);\n\n  // subscribe the user provided onDiscontinuity listener\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('usePresenceListener(); applying onDiscontinuity listener');\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n\n        return () => {\n          logger.debug('usePresenceListener(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, onDiscontinuityRef, logger]);\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    error,\n    presenceData: presenceData,\n  };\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport { useCallback } from 'react';\n\nimport { ConnectionStatusChange } from '../../core/connection.js';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { Room } from '../../core/room.js';\nimport { RoomStatusChange } from '../../core/room-status.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The parameters for the {@link useRoom} hook.\n */\nexport interface UseRoomParams {\n  /**\n   * Callback for when the room status changes. The listener is removed when\n   * the component unmounts.\n   * @param change The change object.\n   * @example\n   * ```tsx\n   * useRoom({\n   *   onStatusChange: (change) => {\n   *     console.log(`Room status changed from ${change.previous} to ${change.current}`);\n   *   },\n   * });\n   *```\n   */\n  onStatusChange?: (change: RoomStatusChange) => void;\n\n  /**\n   * Callback for when the connection status changes. The listener is removed\n   * when the component unmounts.\n   * @param change The change object.\n   * @example\n   * ```tsx\n   * useRoom({\n   *   onConnectionStatusChange: (change) => {\n   *     console.log(`Connection changed from ${change.previous} to ${change.current}`);\n   *   },\n   * });\n   * ```\n   */\n  onConnectionStatusChange?: (change: ConnectionStatusChange) => void;\n}\n\n/**\n * The return type for the {@link useRoom} hook.\n */\nexport interface UseRoomResponse extends ChatStatusResponse {\n  /**\n   * The unique identifier of the room.\n   */\n  readonly roomName: string;\n\n  /**\n   * Shortcut to {@link Room.attach}. The {@link ChatRoomProvider} will handle attaching and detaching\n   * automatically, so this is only needed for manual control.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @example\n   * ```tsx\n   * const { attach, roomStatus } = useRoom();\n   *\n   * const handleManualAttach = async () => {\n   *   try {\n   *     await attach();\n   *     console.log('Room attached successfully');\n   *   } catch (error) {\n   *     console.error('Failed to attach room:', error);\n   *   }\n   * };\n   * ```\n   */\n  attach: () => Promise<void>;\n\n  /**\n   * Shortcut to {@link Room.detach}. The {@link ChatRoomProvider} will handle attaching and detaching\n   * automatically, so this is only needed for manual control.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @example\n   * ```tsx\n   * const { detach, roomStatus } = useRoom();\n   *\n   * const handleManualDetach = async () => {\n   *   try {\n   *     await detach();\n   *     console.log('Room detached successfully');\n   *   } catch (error) {\n   *     console.error('Failed to detach room:', error);\n   *   }\n   * };\n   * ```\n   */\n  detach: () => Promise<void>;\n}\n\n/**\n * React hook that provides access to room information and basic room operations.\n *\n * Typically, you won't need to call `attach()` or `detach()` manually since the\n * {@link ChatRoomProvider} handles room lifecycle automatically.\n *\n * **Note**: This hook must be used within a {@link ChatRoomProvider} component tree.\n * @param params - Optional parameters for status change callbacks\n * @returns A {@link UseRoomResponse} containing room data and operations\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Basic usage\n * ```tsx\n * import React from 'react';\n * import { ChatClient } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   useRoom\n * } from '@ably/chat/react';\n *\n * // Component that displays room information\n * const RoomInfo = () => {\n *   const { roomName, roomStatus, connectionStatus } = useRoom({\n *     onStatusChange: (change) => {\n *       console.log(`Room status changed from ${change.previous} to ${change.current}`);\n *     },\n *     onConnectionStatusChange: (change) => {\n *       console.log(`Connection changed from ${change.previous} to ${change.current}`);\n *     }\n *   });\n *\n *   return (\n *     <div>\n *       <div>Room: {roomName}</div>\n *       <div>Status: {roomStatus}</div>\n *       <div>Connection: {connectionStatus}</div>\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with providers\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"general-chat\">\n *         <RoomInfo />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useRoom = (params?: UseRoomParams): UseRoomResponse => {\n  const context = useRoomContext('useRoom');\n  const roomName = context.roomName;\n  const logger = useRoomLogger();\n  logger.debug('useRoom();');\n\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n\n  // room error and status callbacks\n  const roomStatus = useRoomStatus({\n    onRoomStatusChange: params?.onStatusChange,\n  });\n\n  const attach = useCallback(async () => {\n    const room = await context.room;\n    return room.attach();\n  }, [context]);\n  const detach = useCallback(async () => {\n    const room = await context.room;\n    return room.detach();\n  }, [context]);\n\n  return {\n    roomName: roomName,\n    attach: attach,\n    detach: detach,\n    roomStatus: roomStatus.status,\n    roomError: roomStatus.error,\n    connectionStatus: connectionStatus,\n    connectionError: connectionError,\n  };\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport { useCallback, useEffect } from 'react';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { RoomReactionListener, RoomReactions, SendReactionParams } from '../../core/room-reactions.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { Listenable } from '../types/listenable.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The parameters for the {@link useRoomReactions} hook.\n */\nexport interface UseRoomReactionsParams extends StatusParams, Listenable<RoomReactionListener> {\n  /**\n   * A listener that will be called whenever a reaction is sent to the room.\n   * @example\n   * ```tsx\n   * useRoomReactions({\n   *   listener: (reactionEvent) => {\n   *     console.log('Room reaction received:', reactionEvent.reaction.name, \" from \", reactionEvent.reaction.clientId);\n   *   }\n   * });\n   * ```\n   */\n  listener?: RoomReactionListener;\n}\n\n/**\n * The response type from the {@link useRoomReactions} hook.\n */\nexport interface UseRoomReactionsResponse extends ChatStatusResponse {\n  /**\n   * A shortcut to the {@link RoomReactions.send} method.\n   *\n   * Sends a room-level reaction.\n   *\n   * Room reactions are ephemeral events that are not associated with specific messages.\n   * They're commonly used for live interactions like floating emojis, applause, or other\n   * real-time feedback in chat rooms. Unlike message reactions, room reactions are not\n   * persisted and are only visible to users currently connected to the room.\n   *\n   * **Note**:\n   * - Room must be attached to send room reactions, typically the {@link ChatRoomProvider} handles this automatically.\n   * - It is possible (though unlikely) to receive your own reaction via subscription before this promise resolves.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @param params - The reaction parameters\n   * @returns Promise that resolves when the reaction has been sent, or rejects with:\n   * - {@link chat-js!ErrorCode.InvalidArgument | InvalidArgument} if name is not provided\n   * - {@link chat-js!ErrorCode.Disconnected | Disconnected} if not connected to Ably\n   * @example\n   * ```tsx\n   * const { sendRoomReaction } = useRoomReactions();\n   *\n   * const celebrateSuccess = async () => {\n   *   try {\n   *     await sendRoomReaction({\n   *       name: '🎉',\n   *       metadata: { reason: 'milestone_reached' }\n   *     });\n   *   } catch (error) {\n   *     console.error('Failed to send room reaction:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly sendRoomReaction: (params: SendReactionParams) => Promise<void>;\n}\n\n/**\n * React hook that provides access to room reaction functionality.\n *\n * This hook allows you to send reactions to the room (not to specific messages) and\n * subscribe to room reaction events. Room reactions are ephemeral messages (not persisted) that\n * all room participants can see, such as applause, cheers, or other real-time feedback.\n *\n * **Note**:\n * - This hook must be used within a {@link ChatRoomProvider} component tree.\n * - Room must be attached to send and receive room reactions, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for event listeners and room status callbacks\n * @returns A {@link UseRoomReactionsResponse} containing room reaction methods and status\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Basic usage\n * ```tsx\n * import React from 'react';\n * import { ChatClient, RoomReactionEvent } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   useRoomReactions\n * } from '@ably/chat/react';\n *\n * // Component that handles room reactions\n * const RoomReactionHandler = () => {\n *   const { sendRoomReaction } = useRoomReactions({\n *     listener: (reactionEvent: RoomReactionEvent) => {\n *       console.log('Room reaction received:', reactionEvent.reaction.name, \" from \", reactionEvent.reaction.clientId);\n *     }\n *   });\n *\n *   const handleSendRoomReaction = async (name: string) => {\n *     try {\n *       await sendRoomReaction({ name });\n *       console.log(`Sent ${name} reaction`);\n *     } catch (error) {\n *       console.error('Failed to send reaction:', error);\n *     }\n *   };\n *\n *   return (\n *     <div>\n *       <button onClick={() => handleSendRoomReaction('👏')}>👏 Clap</button>\n *       <button onClick={() => handleSendRoomReaction('🎉')}>🎉 Celebrate</button>\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // App component with providers\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"event-room\">\n *         <RoomReactionHandler />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useRoomReactions = (params?: UseRoomReactionsParams): UseRoomReactionsResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n\n  const context = useRoomContext('useRoomReactions');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n  const logger = useRoomLogger();\n  logger.trace('useRoomReactions();', { params });\n\n  // create stable references for the listeners\n  const listenerRef = useEventListenerRef(params?.listener);\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  // if provided, subscribes the user provided discontinuity listener\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useRoomReactions(); applying onDiscontinuity listener');\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n        return () => {\n          logger.debug('useRoomReactions(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, onDiscontinuityRef, logger]);\n\n  // if provided, subscribe the user provided listener to room reactions\n  useEffect(() => {\n    if (!listenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useRoomReactions(); applying listener');\n        const { unsubscribe } = room.reactions.subscribe(listenerRef);\n        return () => {\n          logger.debug('useRoomReactions(); removing listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, listenerRef, logger]);\n\n  const sendRoomReaction = useCallback(\n    async (params: SendReactionParams) => {\n      const room = await context.room;\n      return room.reactions.send(params);\n    },\n    [context],\n  );\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    sendRoomReaction,\n  };\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport * as Ably from '@ably/pubsub-core';\nimport { useCallback, useEffect, useState } from 'react';\n\nimport { RoomStatus } from '../../core/room-status.js';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { Typing, TypingListener, TypingMember } from '../../core/typing.js';\nimport { wrapRoomPromise } from '../helper/room-promise.js';\nimport { ChatStatusResponse } from '../types/chat-status-response.js';\nimport { Listenable } from '../types/listenable.js';\nimport { StatusParams } from '../types/status-params.js';\nimport { useEventListenerRef } from './internal/use-event-listener-ref.js';\nimport { useRoomLogger } from './internal/use-logger.js';\nimport { useRoomContext } from './internal/use-room-context.js';\nimport { useRoomStatus } from './internal/use-room-status.js';\nimport { useChatConnection } from './use-chat-connection.js';\n\n/**\n * The parameters for the {@link useTyping} hook.\n */\nexport interface TypingParams extends StatusParams, Listenable<TypingListener> {\n  /**\n   * A listener that will be called whenever a typing event is sent to the room.\n   * The listener is removed when the component unmounts.\n   * @example\n   * ```tsx\n   * useTyping({\n   *   listener: (typingEvent) => {\n   *     console.log('Typing event:', Array.from(typingEvent.currentlyTyping));\n   *   }\n   * });\n   * ```\n   */\n  listener?: TypingListener;\n}\n\nexport interface UseTypingResponse extends ChatStatusResponse {\n  /**\n   * A shortcut to the {@link Typing.keystroke} method.\n   *\n   * Sends a typing started event to notify other users that the current user is typing.\n   *\n   * Events are throttled according to the `heartbeatThrottleMs` room option to prevent\n   * excessive network traffic. If called within the throttle interval, the operation\n   * becomes a no-op. Multiple rapid calls are serialized to maintain consistency.\n   *\n   * **Note**:\n   * - The connection must be in the `connected` state.\n   * - Calls to `keystroke()` and `stop()` are serialized and resolve in order.\n   * - The most recent operation always determines the final typing state.\n   * - The room must be attached to send typing events, typically the {@link ChatRoomProvider} handles this automatically.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @returns Promise that resolves when the typing event has been sent, or rejects with:\n   * - {@link chat-js!ErrorCode.Disconnected | Disconnected} if not connected\n   * - {@link chat-js!ErrorCode.OperationSerializationFailed | OperationSerializationFailed} if mutex acquisition fails\n   * - {@link Ably.ErrorInfo} if the operation fails to send the event\n   * @example\n   * ```tsx\n   * const { keystroke } = useTyping();\n   *\n   * const handleKeyPress = async () => {\n   *   try {\n   *     await keystroke();\n   *     console.log('Typing indicator sent');\n   *   } catch (error) {\n   *     console.error('Failed to send keystroke:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly keystroke: () => Promise<void>;\n\n  /**\n   * A shortcut to the {@link Typing.stop} method.\n   *\n   * Sends a typing stopped event to notify other users that the current user has stopped typing.\n   *\n   * If the user is not currently typing, this operation is a no-op. Multiple rapid calls\n   * are serialized to maintain consistency, with the most recent operation determining\n   * the final state.\n   *\n   * **Note**:\n   * - The connection must be in the `connected` state.\n   * - Calls to `keystroke()` and `stop()` are serialized and resolve in order.\n   * - The room must be attached to send typing events, typically the {@link ChatRoomProvider} handles this automatically.\n   *\n   * This is a stable reference and will not be changed between renders for the same room.\n   * @returns Promise that resolves when the stop event has been sent, or rejects with:\n   * - {@link chat-js!ErrorCode.Disconnected | Disconnected} if not connected\n   * - {@link chat-js!ErrorCode.OperationSerializationFailed | OperationSerializationFailed} if mutex acquisition fails\n   * - {@link Ably.ErrorInfo} if the operation fails to send the event\n   * @example\n   * ```tsx\n   * const { stop } = useTyping();\n   *\n   * const handleStopTyping = async () => {\n   *   try {\n   *     await stop();\n   *     console.log('Stopped typing indicator');\n   *   } catch (error) {\n   *     console.error('Failed to stop typing:', error);\n   *   }\n   * };\n   * ```\n   */\n  readonly stop: () => Promise<void>;\n\n  /**\n   * A state value representing the set of client IDs that are currently typing in the room.\n   * It automatically updates based on typing events received from the room.\n   * @deprecated Use {@link UseTypingResponse.currentTypers | currentTypers} instead, which includes metadata such as user claims.\n   */\n  readonly currentlyTyping: Set<string>;\n\n  /**\n   * A state value representing the set of users currently typing in the room, with associated metadata.\n   * It automatically updates based on typing events received from the room.\n   */\n  readonly currentTypers: TypingMember[];\n}\n\n/**\n *\n * React hook that provides typing indicator functionality for chat rooms.\n *\n * The hook automatically tracks the set of users currently typing and provides\n * this as state that updates in real-time as users start and stop typing.\n *\n * **Note**:\n * - This hook must be used within a {@link ChatRoomProvider} component tree.\n * - The `Room` must be attached to send and receive typing indicators, typically the {@link ChatRoomProvider} handles this automatically.\n * @param params - Optional parameters for event listeners and room status callbacks\n * @returns A {@link UseTypingResponse} containing typing methods and current state\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @example Basic usage\n * ```tsx\n * import React, { useState } from 'react';\n * import { ChatClient, TypingSetEvent } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   useTyping\n * } from '@ably/chat/react';\n *\n * // Component that handles typing indicators\n * const TypingIndicator = () => {\n *   const { keystroke, stop, currentlyTyping } = useTyping({\n *     listener: (typingEvent: TypingSetEvent) => {\n *       console.log('Currently typing users:', Array.from(typingEvent.currentlyTyping));\n *     },\n *   });\n *\n *   const handleInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {\n *     const value = e.target.value;\n *     if (value.length > 0) {\n *       try {\n *         await keystroke();\n *         console.log('Started typing');\n *       } catch (error) {\n *         console.error('Failed to send keystroke:', error);\n *       }\n *     } else {\n *       try {\n *         await stop();\n *         console.log('Stopped typing');\n *       } catch (error) {\n *         console.error('Failed to stop typing:', error);\n *       }\n *     }\n *   };\n *\n *   return (\n *     <div>\n *       <input\n *         onChange={handleInputChange}\n *         placeholder=\"Type a message...\"\n *       />\n *       <div>Currently typing: {Array.from(currentlyTyping).join(', ')}</div>\n *     </div>\n *   );\n * };\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * const App = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"room-id\">\n *         <TypingIndicator />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n *\n * export default App;\n * ```\n */\nexport const useTyping = (params?: TypingParams): UseTypingResponse => {\n  const { currentStatus: connectionStatus, error: connectionError } = useChatConnection({\n    onStatusChange: params?.onConnectionStatusChange,\n  });\n\n  const context = useRoomContext('useTyping');\n  const { status: roomStatus, error: roomError } = useRoomStatus(params);\n  const logger = useRoomLogger();\n  logger.trace('useTyping();');\n\n  const [currentlyTyping, setCurrentlyTyping] = useState<Set<string>>(new Set());\n  const [currentTypers, setCurrentTypers] = useState<TypingMember[]>([]);\n\n  // Create a stable reference for the listeners\n  const listenerRef = useEventListenerRef(params?.listener);\n  const onDiscontinuityRef = useEventListenerRef(params?.onDiscontinuity);\n\n  useEffect(() => {\n    // Start with a clean slate - empty set\n    setCurrentlyTyping((prev) => {\n      // keep reference constant if it's already empty\n      if (prev.size === 0) return prev;\n      return new Set<string>();\n    });\n    setCurrentTypers((prev) => {\n      if (prev.length === 0) return prev;\n      return [];\n    });\n\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useTyping(); subscribing to typing events');\n        const { unsubscribe } = room.typing.subscribe((event) => {\n          // eslint-disable-next-line @typescript-eslint/no-deprecated\n          setCurrentlyTyping(event.currentlyTyping);\n          setCurrentTypers(event.currentTypers);\n        });\n\n        // If we're not attached, we can't call typing.current() right now\n        if (room.status === RoomStatus.Attached) {\n          // eslint-disable-next-line @typescript-eslint/no-deprecated\n          const typing = room.typing.current;\n          logger.debug('useTyping(); room attached, getting initial typers', { typing });\n          setCurrentlyTyping(typing);\n          setCurrentTypers(room.typing.currentTypers);\n        }\n\n        return () => {\n          logger.debug('useTyping(); unsubscribing from typing events');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, logger]);\n\n  // if provided, subscribes the user-provided onDiscontinuity listener\n  useEffect(() => {\n    if (!onDiscontinuityRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useTyping(); applying onDiscontinuity listener');\n        const { off } = room.onDiscontinuity(onDiscontinuityRef);\n        return () => {\n          logger.debug('useTyping(); removing onDiscontinuity listener');\n          off();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, onDiscontinuityRef, logger]);\n\n  // if provided, subscribe the user-provided listener to TypingEvents\n  useEffect(() => {\n    if (!listenerRef) return;\n    return wrapRoomPromise(\n      context.room,\n      (room) => {\n        logger.debug('useTyping(); applying listener');\n        const { unsubscribe } = room.typing.subscribe(listenerRef);\n        return () => {\n          logger.debug('useTyping(); removing listener');\n          unsubscribe();\n        };\n      },\n      logger,\n    ).unmount();\n  }, [context, listenerRef, logger]);\n\n  // memoize the methods to avoid re-renders, and ensure the same instance is used\n  const keystroke = useCallback(async () => {\n    const room = await context.room;\n    return room.typing.keystroke();\n  }, [context]);\n  const stop = useCallback(async () => {\n    const room = await context.room;\n    return room.typing.stop();\n  }, [context]);\n\n  return {\n    connectionStatus,\n    connectionError,\n    roomStatus,\n    roomError,\n    keystroke,\n    stop,\n    currentlyTyping,\n    currentTypers,\n  };\n};\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type * as Ably from '@ably/pubsub-core';\n// imported for docs linking\nimport React, { ReactNode, useEffect, useMemo, useState } from 'react';\n\nimport { Room } from '../../core/room.js';\nimport { RoomOptions } from '../../core/room-options.js';\nimport { ChatRoomContext, ChatRoomContextType } from '../contexts/chat-room-context.js';\nimport { useChatClientContext } from '../hooks/internal/use-chat-client-context.js';\nimport { useLogger } from '../hooks/internal/use-logger.js';\nimport { useRoomReferenceManager } from '../hooks/internal/use-room-reference-manager.js';\n\n/**\n * Props for the {@link ChatRoomProvider} component.\n */\nexport interface ChatRoomProviderProps {\n  /** The name of the room. */\n  name: string;\n\n  /**\n   * Overriding options to use when creating the room. See {@link RoomOptions} for details.\n   *\n   * **Important**:\n   * - The `options` should be memoized to prevent unnecessary room recreations. Passing a new object reference\n   * on each render will cause the room to be released and recreated.\n   * - Provided options are merged with the default options, so you only need to specify the options you want to change.\n   * - Room options cannot be changed after the room is created. Different options\n   * for the same room name will result in an error.\n   * @example\n   * ```tsx\n   * const MyRoomComponent = () => {\n   *   const [typing, setTyping] = useState(true);\n   *\n   *   const roomOptions = useMemo(() => ({\n   *     typing: { timeoutMs: 5000 },\n   *   }), []); // Stable reference - options don't change\n   *\n   *   return (\n   *     <ChatRoomProvider name=\"my-room\" options={roomOptions}>\n   *       <MyChat />\n   *     </ChatRoomProvider>\n   *   );\n   * };\n   * ```\n   */\n  options?: RoomOptions;\n\n  /** Children nodes. */\n  children?: ReactNode | ReactNode[] | null;\n}\n\n/**\n * React Context Provider that makes a specific {@link Room} available to child components.\n *\n * The provider automatically handles room attachment/detachment and provides the room\n * instance to child components through room-specific hooks like {@link useMessages},\n * {@link usePresence}, {@link useTyping}, etc.\n *\n * Multiple providers for the same room (with same options) share the same underlying\n * room instance through reference counting, making it safe to have multiple components\n * using the same room simultaneously.\n *\n * When the first {@link ChatRoomProvider} for a room mounts, it creates\n * and attaches the room. When the last provider unmounts, it releases the room.\n * @param props - The props for the ChatRoomProvider component.\n * @param props.name The name of the room.\n * @param props.options Overriding options to use when creating the room.\n * @param props.children The child components to be rendered within this provider.\n * @returns A React element that provides the room context to its children\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.ReactHookMustBeUsedWithinProvider | ReactHookMustBeUsedWithinProvider} When used outside of a {@link ChatRoomProvider}\n * @throws An {@link Ably.ErrorInfo} with {@link chat-js!ErrorCode.RoomExistsWithDifferentOptions | RoomExistsWithDifferentOptions} if room exists with different options\n * @example Basic usage\n * ```tsx\n * import * as Ably from '@ably/pubsub-device';\n * import React, { useMemo } from 'react';\n * import { ChatClient } from '@ably/chat';\n * import {\n *   ChatClientProvider,\n *   ChatRoomProvider,\n *   useMessages,\n *   useRoom,\n * } from '@ably/chat/react';\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // Child component using room functionality\n * const ChatInterface = () => {\n *   const { roomName } = useRoom();\n *   const { sendMessage } = useMessages();\n *\n *   return (\n *     <div>\n *       <h2>Chat Room: {roomName}</h2>\n *       <button onClick={() => sendMessage({ text: 'Hello!' })}>\n *         Send Message\n *       </button>\n *     </div>\n *   );\n * };\n *\n * const BasicExample = () => {\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"general-chat\">\n *         <ChatInterface />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n * ```\n * @example Providing custom room options\n * ```tsx\n * import { ChatClientProvider, ChatRoomProvider } from '@ably/chat/react';\n * import { ChatClient } from '@ably/chat';\n *\n * const chatClient: ChatClient; // existing ChatClient instance\n *\n * // Example with room options (properly memoized)\n * const CustomOptions = () => {\n *   // Memoize options to prevent room recreation\n *   const roomOptions = useMemo(() => ({\n *     typing: {\n *       timeoutMs: 10000 // 10 second typing timeout\n *     },\n *   }), []); // Empty dependency array = stable reference\n *\n *   return (\n *     <ChatClientProvider client={chatClient}>\n *       <ChatRoomProvider name=\"team-room\" options={roomOptions}>\n *         <ChatInterface />\n *       </ChatRoomProvider>\n *     </ChatClientProvider>\n *   );\n * };\n * ```\n */\nexport const ChatRoomProvider = ({ name: roomName, options, children }: ChatRoomProviderProps): React.ReactElement => {\n  const client = useChatClientContext();\n  const clientLogger = useLogger();\n  const logger = useMemo(() => clientLogger.withContext({ roomName }), [clientLogger, roomName]);\n  const roomReferenceManager = useRoomReferenceManager();\n\n  logger.debug(`ChatRoomProvider();`, { options });\n\n  // Set the initial room promise, we do this in a function to avoid rooms.get being called\n  // every time the component re-renders\n  // In StrictMode this will be called twice one after the other, but that's ok\n  const [value, setValue] = useState<ChatRoomContextType>(() => {\n    logger.debug(`ChatRoomProvider(); initializing value`, { options });\n    const room: Promise<Room> = client.rooms.get(roomName, options);\n    room.catch(() => void 0);\n    return { room: room, roomName: roomName, options: options, client: client };\n  });\n\n  // Create an effect that manages the room state using reference counting\n  useEffect(() => {\n    logger.debug(`ChatRoomProvider(); running lifecycle useEffect`);\n    let unmounted = false;\n\n    // Add reference and get the room\n    const roomPromise = roomReferenceManager.addReference(roomName, options);\n\n    // Update the context value with the new room promise\n    setValue((prev: ChatRoomContextType) => {\n      // If the room id and options haven't changed, then we don't need to do anything\n      if (prev.client === client && prev.roomName === roomName && prev.options === options) {\n        logger.debug(`ChatRoomProvider(); no change in room id or options`, { options });\n        return prev;\n      }\n\n      logger.debug(`ChatRoomProvider(); updating value`, { options });\n      return { room: roomPromise, roomName, options, client };\n    });\n\n    // Handle the room promise resolution\n    void roomPromise\n      .then(() => {\n        if (unmounted) {\n          logger.debug(`ChatRoomProvider(); unmounted before room resolved`);\n          return;\n        }\n        logger.debug(`ChatRoomProvider(); room resolved`);\n      })\n      .catch(() => void 0);\n\n    // Cleanup function\n    return () => {\n      unmounted = true;\n      logger.debug(`ChatRoomProvider(); cleaning up lifecycle useEffect`);\n\n      // Remove reference - this will handle release if it's the last reference\n      roomReferenceManager.removeReference(roomName, options);\n    };\n  }, [roomName, options, logger, client, roomReferenceManager]);\n\n  return <ChatRoomContext.Provider value={value}>{children}</ChatRoomContext.Provider>;\n};\n"],"names":["ChatRoomContext","createContext","ConnectionStatus","ErrorCode","errorInfoIs","errorInfo","error","contextKey","globalObjectForContext","ChatClientContext","context","React","has","find","iter","tar","key","dequal","foo","bar","ctor","len","tmp","normalizeArrayItem","item","nestedItem","sortedObj","keys","objKey","roomKeyReplacer","value","createRoomKey","roomName","options","RoomReferenceManager","client","logger","existing","resolve","reject","interval","pendingRelease","existingWithDifferentOptions","entry","hasPendingRelease","hasZeroRefCount","Ably","existingKey","releasePromise","room","currentEntry","ROOM_REFERENCE_MANAGER_KEY","useRoomReferenceManager","manager","DEFAULT_CHAT_CLIENT_ID","ChatClientProvider","children","roomReferenceManagerRef","useRef","clientLogger","uiKitVersion","jsx","useChatClientContext","useRoomContext","callingHook","useContext","useLogger","chatClient","useMemo","useRoomLogger","roomContext","useChatClient","clientId","setClientId","useState","useEffect","off","change","useEventListenerRef","callback","ref","returnVal","useCallback","args","useChatConnection","currentStatus","setCurrentStatus","setError","onStatusChangeRef","DefaultRoomPromise","onResolve","promise","wrapRoomPromise","RoomStatus","useRoomStatus","params","status","setStatus","onRoomStatusChangeRef","useMessages","connectionStatus","connectionError","roomStatus","roomError","listenerRef","reactionsListenerRef","rawReactionsListenerRef","onDiscontinuityRef","sendMessage","getMessage","serial","getVersions","deleteMessage","details","history","updateMessage","updateParams","sendReaction","deleteReaction","historyBeforeSubscribe","setHistoryBeforeSubscribe","unmounted","sub","unsubscribe","useOccupancy","occupancyMetrics","setOccupancyMetrics","currentOccupancy","occupancyEvent","INACTIVE_CONNECTION_STATES","usePresence","shouldAutoEnterLeave","myPresenceState","setMyPresenceState","roomStatusAndConnectionStatusRef","latestDataRef","hasExplicitlyLeftRef","hasAutoEnteredRef","roomWasDetachedRef","subscription","stateChange","canJoinPresence","shouldAutoEnter","canLeavePresence","update","data","enter","leave","PRESENCE_GET_RETRY_INTERVAL_MS","PRESENCE_GET_RETRY_MAX_INTERVAL_MS","PRESENCE_GET_MAX_RETRIES","usePresenceListener","receivedEventNumber","triggeredEventNumber","retryTimeout","numRetries","latestPresentData","presenceData","setPresenceData","errorRef","setErrorState","clearErrorState","updatePresenceData","getAndSetState","eventNumber","presenceMembers","waitBeforeRetry","useRoom","attach","detach","useRoomReactions","sendRoomReaction","useTyping","currentlyTyping","setCurrentlyTyping","currentTypers","setCurrentTypers","prev","event","typing","keystroke","stop","ChatRoomProvider","roomReferenceManager","setValue","roomPromise"],"mappings":"uqBAqCaA,EAAkBC,EAAAA,cAA+C,MAAS,EC3BhF,IAAKC,GAAAA,IAIVA,EAAA,YAAc,cAKdA,EAAA,WAAa,aAKbA,EAAA,UAAY,YAKZA,EAAA,aAAe,eAKfA,EAAA,UAAY,YAKZA,EAAA,OAAS,SAOTA,EAAA,QAAU,UAMVA,EAAA,OAAS,SA1CCA,IAAAA,GAAA,CAAA,CAAA,ECLAC,GAAAA,IAIVA,EAAAA,EAAA,WAAa,GAAA,EAAb,aAKAA,EAAAA,EAAA,gBAAkB,KAAA,EAAlB,kBAKAA,EAAAA,EAAA,gBAAkB,KAAA,EAAlB,kBAKAA,EAAAA,E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