import { ConnectionLifecycle, ConnectionStatus, ConnectionStatusListener, OnConnectionStatusChangeResponse, } from '@ably/chat'; import { ErrorInfo } from 'ably'; import { nanoid } from 'nanoid'; import { jsonRpcBlocking, registerCallback } from './jsonrpc'; export class RpcConnectionStatus implements ConnectionStatus { private readonly _instanceId: string; constructor(instanceId: string) { this._instanceId = instanceId; } get current(): ConnectionLifecycle { const { response } = jsonRpcBlocking.request('ConnectionStatus#current', { refId: this._instanceId }); return response; } get error(): ErrorInfo | undefined { const { response } = jsonRpcBlocking.request('ConnectionStatus#error', { refId: this._instanceId }); return response; } onChange(listener: ConnectionStatusListener): OnConnectionStatusChangeResponse { const callbackId = nanoid(); registerCallback(callbackId, listener); const { refId } = jsonRpcBlocking.request('ConnectionStatus.onChange', { refId: this._instanceId, callbackId, }); return new RpcOnConnectionStatusChangeResponse(refId); } offAll(): void { jsonRpcBlocking.request('ConnectionStatus.offAll', { refId: this._instanceId }); } } export class RpcOnConnectionStatusChangeResponse implements OnConnectionStatusChangeResponse { private readonly _instanceId: string; constructor(instanceId: string) { this._instanceId = instanceId; // it is common to destructure this object when received from the subscription function, // so we need to bind its functions to preserve reference to this this.off = this.off.bind(this); } off(): void { jsonRpcBlocking.request('OnConnectionStatusChangeResponse.off', { refId: this._instanceId }); } }