export { ClientConnection }; export type { MuxChannel, MuxConnection }; import { ChannelClosedError } from '../channel-errors.js'; import { type ChannelTransport, type ChannelTransports } from '../constants.js'; import type { AckResultStatus, ChannelFrame, DecodedFrame, ReconciledPayload } from '../shared-ws.js'; /** Ping-then-pong-deadline loop. Each transport owns one for its wire; the upgrade probe * flow constructs a transient instance for the probed wire until the swap commits. */ declare class Heartbeat { private readonly intervalMs; private readonly pongTimeoutMs; private readonly send; private readonly onDead; private pingTimer; private pongTimer; constructor(intervalMs: number, pongTimeoutMs: number, send: () => void, onDead: () => void); start(): void; resetPong(): void; stop(): void; } type OutboundFrameKind = 'reconcile' | 'control' | 'flow-control' | 'ack' | 'data' | 'heartbeat'; type OutboundFrame = { kind: OutboundFrameKind; frame: Uint8Array; }; interface MuxChannel { readonly id: string; readonly isClosed: boolean; _onTransportOpen(batched: boolean): void; /** Entry point for every per-channel wire frame (data + per-channel ctrl). The * channel splits ctrl vs data internally. Connection-level frames (PING/PONG/ * FIN/RECONCILED) and channel-termination ctrls (ABORT/ERROR) stay with the * connection — they involve connection-side cleanup. */ _dispatchFrame(frame: ChannelFrame): void; _onTransportClose(err?: Error): void; } interface MuxConnection { send(channel: MuxChannel, data: string): number; sendPublishAckReq(channel: MuxChannel, data: string, onQueued: (seq: number) => void): void; sendPublishBinaryAckReq(channel: MuxChannel, data: Uint8Array, onQueued: (seq: number) => void): void; sendTextAckReq(channel: MuxChannel, data: string, onQueued: (seq: number) => void): void; sendBinaryAckReq(channel: MuxChannel, data: Uint8Array, onQueued: (seq: number) => void): void; sendBinary(channel: MuxChannel, data: Uint8Array): void; sendAckRes(channel: MuxChannel, ackedSeq: number, result: string, status?: AckResultStatus): void; sendAbort(channel: MuxChannel): void; sendCloseRequest(channel: MuxChannel, timeoutMs: number): void; sendCloseAck(channel: MuxChannel): void; sendByteWindowUpdate(channel: MuxChannel, bytes: number): void; sendMsgWindowUpdate(channel: MuxChannel, count: number): void; sendBdpPing(channel: MuxChannel): void; sendBdpPingAck(channel: MuxChannel): void; sendBroadcastSubscribe(channel: MuxChannel, binary: boolean): void; sendBroadcastUnsubscribe(channel: MuxChannel, binary: boolean): void; unregister(channel: MuxChannel, err?: Error): void; } type ReconcileBatch = { reconcileFrame: OutboundFrame; movedBufferedFrames: OutboundFrame[]; }; type ReconcileBufferedFramesMode = 'batch-on-reconcile' | 'release-after-reconciled'; type ClientConnectionOptions = { transports: ChannelTransports; fetchImpl: typeof fetch; /** Server-issued sticky-routing token (e.g. Cloudflare DO pinning). Sent as URL param + header. */ sessionToken?: string; /** Client-side cache-key extension — distinct values get distinct `ClientConnection` instances. Never sent on the wire. */ connectionKey?: string; /** User headers (config.headers + per-call `withContext({ headers })`) merged into every transport fetch. */ headers?: Record; /** Override the idle-close delay after all channels close. Default: 60 000 ms. Pass 0 to dispose immediately. */ idleTimeout?: number; }; type ClientChannelTransport = { readonly type: ChannelTransport; readonly sendReconcileOnOpen: boolean; readonly reconcileMode: ReconcileBufferedFramesMode; /** True iff client→server frames are per-POST batched instead of pushed onto * one streaming body — signals the channel to use a larger initial window. */ readonly batched: boolean; start(): void; hasWire(): boolean; isConnecting(): boolean; /** Send a connection-level ping on this wire. Heartbeat's send callback calls this. */ sendPing(): void; sendFrame(frame: OutboundFrame): void; abandonActiveTransport(): void; closeAbandonedTransport(): void; applyReconciledSettings(ctrl: ReconciledPayload): void; /** Connection constructs the Heartbeat (with the funnel-bound onDead) and hands it over. * Transport's frame receive path routes PONG to it directly (`heartbeat?.resetPong()`). */ attachHeartbeat(hb: Heartbeat): void; detachHeartbeat(): void; hasHeartbeat(): boolean; dispose(): void; }; declare class ClientConnection implements MuxConnection { private static cache; static getOrCreate(telefuncUrl: string, channel: MuxChannel, options: ClientConnectionOptions): ClientConnection; private readonly cacheKey; private readonly telefuncUrl; private readonly connectionOptions; private transport; private state; /** Sticky after a permanent upgrade abort — survives every state transition until dispose. */ private upgradeDisabled; /** Server-allowed transports from the last settled RECONCILED. Kept so `maybeStartUpgrade` * can run from both `handleReconciled` and `_onTransportOpen` — transport-open and the * first RECONCILED can arrive in either order on the SSE path. */ private serverTransports; /** RECONCILE sent, awaiting RECONCILED. SSE sets it true during connecting since the * initial reconcile is baked into the openStream POST body. Bounded by `reconcileTimer`: * written only via `enterReconciling`/`exitReconciling` so the deadline can never outlive * the state it guards. */ private reconciling; private reconcileTimer; private ttl; private get closed(); private get connected(); private get committing(); /** The flip is an EVENT inside `committing`, not a transition out of it: `flipped ≡ transport === to`. */ private get flipped(); /** Sends are gated from the barrier's emission until its COMMITTED lands. */ private get upgradeGatesSends(); private sessionId; private nextIndex; private reconcileIxes; private channels; private channelIndex; private sendBuffer; private lastSeqByChannel; private replayBuffers; private reconnectTimeoutMs; private idleTimeoutMs; private pingIntervalMs; private clientReplayBufferBytes; private clientReplayBufferBinaryBytes; private constructor(); private enterOpen; /** Owns the reconnect timer's lifecycle so callers can't forget to cancel a prior one. */ private enterReconnecting; private enterClosed; private enterUpgradeStaging; private armAttemptDeadline; private enterUpgradeCommitting; private exitUpgradeAttempt; private exitUpgradeCommitting; private canSendImmediately; private enterChannelPending; private enterChannelOpen; private enterChannelReleasing; private register; private registerReconcileTimer; /** Coalesces sync-burst registrations into one RECONCILE round-trip. */ private scheduleRegisterReconcile; /** Send the queued RECONCILE on the live wire. No-op when nothing's queued. While the wire * can't take it (connecting, awaiting RECONCILED, mid-upgrade) the obligation is KEPT, not * consumed — `registerReconcileTimer` stays non-null as the marker (which also keeps * `canSendImmediately` false so data frames buffer behind the RECONCILE), and the * transitions that make the wire sendable re-invoke this: `_onTransportOpen`, a settled * RECONCILED, upgrade-attempt exit, and handoff completion. */ private flushPendingRegisterReconcile; /** Cancel without sending — wire is dying. Drops releasing entries so they don't * leak onto the post-reconnect RECONCILE. */ private cancelPendingRegisterReconcile; private cancelRegisterReconcileTimer; private releaseUnconfirmedReleasing; unregister(channel: MuxChannel, err?: ChannelClosedError): void; send(channel: MuxChannel, data: string): number; sendPublishAckReq(channel: MuxChannel, data: string, onQueued: (seq: number) => void): void; sendPublishBinaryAckReq(channel: MuxChannel, data: Uint8Array, onQueued: (seq: number) => void): void; sendTextAckReq(channel: MuxChannel, data: string, onQueued: (seq: number) => void): void; sendBinaryAckReq(channel: MuxChannel, data: Uint8Array, onQueued: (seq: number) => void): void; /** Shared ack-req issuance — encodes via `buildFrame`, invokes `onQueued(seq)` so the * channel registers the pending ack *before* the frame hits the wire (so an * immediate `ACK_RES` can't be lost), then ships or buffers the frame. Mirrors * `IndexedPeer.sendTextAckReq` on the server side. */ private sendAckReq; sendBinary(channel: MuxChannel, data: Uint8Array): void; sendAckRes(channel: MuxChannel, ackedSeq: number, result: string, status?: AckResultStatus): void; sendAbort(channel: MuxChannel): void; sendCloseRequest(channel: MuxChannel, timeoutMs: number): void; sendCloseAck(channel: MuxChannel): void; sendByteWindowUpdate(channel: MuxChannel, bytes: number): void; sendMsgWindowUpdate(channel: MuxChannel, count: number): void; sendBdpPing(channel: MuxChannel): void; sendBdpPingAck(channel: MuxChannel): void; sendBroadcastSubscribe(channel: MuxChannel, binary: boolean): void; sendBroadcastUnsubscribe(channel: MuxChannel, binary: boolean): void; _onTransportOpen(transport: ClientChannelTransport): void; _onTransportFrame(frame: DecodedFrame, source: ClientChannelTransport, byteLength: number): void; private dispatchFrame; /** Every frame arriving mid-handoff lands here — the one charge site. Before the flip the probe * is nobody's wire, so even a join limb waits: acting on one would settle a swap that has not * happened. After it, limbs apply and the rest waits, partitioned by the wire it came from. */ private ingestDuringHandoff; /** True if the frame was one of the join's limbs, and has been applied. */ private applyJoinLimb; private onJoinTimeout; /** Idempotent. Detaches first either way so a fresh install can never leak the prior. */ private installHeartbeat; private dropWire; /** Funnel for pong-timeouts. Suppress while reconciling — pings are delayed by the round-trip; * `reconcileTimer` (armed by `enterReconciling`) is the liveness bound for that window. */ private handlePongTimeout; /** Enter the await-RECONCILED window and arm its liveness bound. A follow-up RECONCILE for * late registrations re-enters and restarts the deadline from scratch. */ private enterReconciling; /** Leave the await-RECONCILED window: RECONCILED settled, the wire was lost, or disposed. */ private exitReconciling; /** RECONCILED never arrived on a silently-stalled wire — same outcome as a missed pong: * drop the wire and let `handleTransportLoss` reconnect. */ private onReconcileTimeout; private handleUpgradeFin; private tryCompleteUpgrade; /** Tears down whichever upgrade phase is in flight. Returns the join's record when the flip had * already happened — its buffered frames are then the caller's to drain — and null otherwise. */ private teardownUpgrade; private retireOldWire; private pruneSendBufferForReleasedChannels; _onTransportClosed(transport: ClientChannelTransport, { rejectedByServer }?: { rejectedByServer?: boolean | undefined; }): void; private handleReconciled; private maybeStartUpgrade; private fallbackToSse; private isTransportUpgradeAllowed; private probeAndUpgrade; private stageProbe; /** The probe is nobody's transport yet, so it has no heartbeat of its own: this one keeps it * alive until the flip adopts it, and any death — its own or the attempt's — closes both. */ private keepProbeAlive; private commitBarrier; private flip; private recoverWedgedOldWire; private drainBufferedFramesToWire; private handleTransportLoss; private startTtlIfIdle; private dispose; buildReconcileFrame(): OutboundFrame; /** The old wire's last frame. Channels the server has not acknowledged yet are left out: the * staged probe has no record of them, so they reconcile again after the handoff. */ private buildBarrierFrame; private collectOpenEntries; drainBufferedFramesForReconcile(isInitialBatch: boolean): OutboundFrame[]; stageReconcileBatch(isInitialBatch?: boolean): ReconcileBatch; private sendReconcileBatch; private appendReconcileBatch; private applyReconciled; private releaseDeferredOmitted; private closeRemoteChannel; private closeAll; /** Dedup against double-delivery. Transports are TCP-ordered and replay sends a contiguous slice * starting at our reported `lastSeq + 1`, so duplicates shouldn't occur in normal operation. */ private trackSeq; private drainBufferedFrames; private releaseChannel; }