popsub 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8FG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EACL,SAAS,EACT,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,eAAe,GAQhB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEnE,kGAAkG;AAClG,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC;AAEpC,gGAAgG;AAChG,MAAM,kBAAkB,GAAG,OAAO,CAAC;AAEnC,uGAAuG;AACvG,MAAM,eAAe,GAAG,MAAM,CAAC;AAE/B,0EAA0E;AAC1E,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAuEjC;;;;;;GAMG;AACH,MAAM,UAAU,IAAI;IAClB,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;IACjC,IAAI,OAAO,MAAM,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;QAC5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E,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1C,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACtB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC;YAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF","sourcesContent":["/**\n * The engine behind a `Client`: it owns the WebSocket and does what every\n * application would otherwise have to.\n *\n * It connects, logs in and authenticates, then serves the connection until\n * it ends. The close code decides what happens next: reconnect with\n * jittered backoff, or stop for good (`session_taken_over`,\n * `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected\n * credentials, and `token_expired` with token credentials). After\n * reconnecting it resubscribes every topic from the next `seq` it expects\n * (a topic the server lists as resumed for a durable session is instead\n * subscribed again from `resume` when the server holds the session's\n * topics, and otherwise left to the server unless a claim on it is still\n * unanswered; see below), resends confirmed publishes that never got their `published` under the\n * same request id and `message_id`, and sends QoS 0 publishes and\n * unsubscribes queued while disconnected.\n *\n * Every message is checked against the next `seq` its topic expects, so a\n * retry or a replay never reaches the application twice. A duplicate the\n * application acknowledged before (or any duplicate in automatic mode,\n * unless its acknowledgement is held back for a full buffer) is\n * acknowledged again, so a lost acknowledgement can't stall the topic.\n *\n * A durable session outlives the process. When a new process connects\n * with the same session id, the server lists the session's topics in\n * `authenticated.resumed` before the application has subscribed to\n * anything. The engine must never acknowledge a message the application\n * couldn't have received, so with a session id its `auth` carries\n * `hold_resumed: true`. A server that honours it answers `held: true` and\n * sends nothing on a resumed topic until the engine subscribes to it. Then\n * nothing is unclaimed, a subscribe to a resumed topic is an ordinary\n * subscribe, a pattern needs no subscribes by name, and after a reconnect\n * the engine subscribes again to every tracked topic the server lists as\n * resumed, with `from: \"resume\"`, because the server no longer does it.\n *\n * A server that doesn't know `hold_resumed` answers without `held` and\n * sends what it kept for the resumed topics at once. A resumed topic the engine\n * isn't tracking is unclaimed: its messages are dropped without an\n * acknowledgement, so the server keeps them for the session. Subscribing\n * to an unclaimed topic by name, or to a pattern that matches it, claims\n * it. A claimed topic is tracked, but its messages are still dropped\n * unacknowledged until the `subscribed` that answers the claim arrives,\n * because the subscribe replays them in order from `replay_from`. A\n * pattern claims a topic by sending one more `subscribe` for it by name\n * with `from: \"resume\"`, since the server skips topics the connection\n * holds when it handles the pattern itself. After a reconnect a claim\n * still unanswered is sent again even when the server lists the topic as\n * resumed. A topic the application never subscribes to stays unclaimed.\n *\n * A wildcard subscription (`orders/#`) is one pattern with one channel.\n * The server announces each topic it joins for the pattern with a\n * `subscribed` frame that has no id; the engine then tracks that topic\n * like any other, with its own next expected `seq` and acknowledgement\n * memory, owned by the pattern and feeding the pattern's channel. A\n * `subscribed` or `message` for an untracked topic is matched against the\n * patterns, and the oldest matching one owns it. After a reconnect the\n * tracked topics are resubscribed first, then each pattern is sent again\n * with `from: {\"seq\": 1}`, which joins only topics created meanwhile.\n * Subscribing again to a pattern the engine holds replaces the\n * subscription: the topics it owned move to the new channel and keep\n * their next expected `seq`, because the server sends nothing again for\n * topics the connection holds, and the earlier channel ends.\n *\n * A shared subscription (a topic read through a `group`) gets only some of\n * the topic's messages, out of order, so duplicates are found with a\n * bounded set of delivered `seq`s instead of a next expected one, nothing\n * moves on `subscribed.replay_from` or `truncated`, and after a reconnect\n * it always rejoins the group with `from: \"resume\"`.\n *\n * An `unsubscribed` frame with no id means the server ended the\n * subscription; every unsubscribe the engine sends carries an id so its\n * reply is never mistaken for that.\n *\n * The browser `WebSocket` API can't pause reading, so backpressure works in\n * two steps. While a subscription's buffer holds `subscriptionBuffer`\n * messages or more, automatic acknowledgements of new QoS 1 messages wait\n * until the application takes them; the server's per-subscription window\n * (`limits.max_inflight`) then stops sending to it, QoS 0 included. If the\n * buffer still reaches `subscriptionBuffer + max_inflight` (possible with\n * QoS 0 traffic, which no window paces), the engine drops the connection,\n * waits until the application has taken that buffer down to half of\n * `subscriptionBuffer`, reconnects, and resubscribes that topic from the\n * next `seq` it expects, so the log fills the gap. Memory per subscription\n * stays below `subscriptionBuffer + max_inflight` messages.\n *\n * Nor does the API show the server's WebSocket pings, so silence is\n * detected with the protocol's own `ping` request: after `heartbeat_secs`\n * with nothing from the server the engine sends `ping` with an id, and\n * again after each further `heartbeat_secs` of silence. Any frame,\n * including the `pong` reply, counts as hearing from the server. Once\n * `idle_timeout_secs + heartbeat_secs` pass with nothing at all, the\n * connection is given up and the engine reconnects.\n *\n * @module\n */\n\nimport { jitteredDelay } from \"./backoff.js\";\nimport type { ResolvedConfig } from \"./config.js\";\nimport { ACK_MEMORY, DeliveryTracker } from \"./dedup.js\";\nimport { Emitter } from \"./events.js\";\nimport { PopSubError } from \"./errors.js\";\nimport { Aborted, ConnectFailure, Handshake } from \"./handshake.js\";\nimport { isPattern, matchesPattern } from \"./pattern.js\";\nimport {\n closeCode,\n encodeFrame,\n errorCode,\n parseServerFrame,\n PROTOCOL_VERSION,\n publishFrame,\n shouldReconnect,\n type ClientMessage,\n type CloseCode,\n type Encoding,\n type Limits,\n type ServerFrame,\n type ServerMessage,\n type WireStartFrom,\n} from \"./protocol.js\";\nimport { Channel, Message, Subscription } from \"./subscription.js\";\n\n/** How many QoS 0 publishes and unsubscribes are held while disconnected; the oldest go first. */\nexport const OFFLINE_LIMIT = 10_000;\n\n/** How long to wait for anything from the server before the server has announced its limits. */\nconst DEFAULT_SILENCE_MS = 120_000;\n\n/** How long a connection may be silent before a `ping`, before the server has announced its limits. */\nconst DEFAULT_PING_MS = 30_000;\n\n/** The window size assumed before the server has announced its limits. */\nconst DEFAULT_MAX_INFLIGHT = 100;\n\n/** The result of a confirmed publish. */\nexport interface Published {\n /** The message's position in the topic. */\n seq: number;\n /** The id it was stored under. */\n messageId: string;\n}\n\n/** How to settle a caller's promise. */\ninterface Settle<T> {\n /** Fulfils it. */\n resolve(value: T): void;\n /** Rejects it. */\n reject(error: PopSubError): void;\n}\n\n/** A request waiting for its reply, by request id. */\ntype Pending =\n | { kind: \"subscribe\"; topic: string; generation: number }\n | { kind: \"unsubscribe\"; settle: Settle<void> }\n | { kind: \"publish\"; settle: Settle<Published> }\n | { kind: \"request\"; settle: Settle<ServerMessage> }\n | { kind: \"relogin\" }\n | { kind: \"reauth\" }\n | { kind: \"ping\" };\n\n/** One subscribed topic. */\ninterface Topic {\n /** Where its messages go. */\n channel: Channel;\n /** Where replay started when the application subscribed. */\n from: WireStartFrom;\n /** Which subscription this is, so a stale close can't remove a newer one. */\n generation: number;\n /** The next expected `seq` and acknowledgement memory. */\n tracker: DeliveryTracker;\n /** Whether its buffer overflowed, so deliveries are dropped until it is resubscribed. */\n overflowed: boolean;\n /** The wildcard pattern it was joined through, or `null` when subscribed by name. */\n owner: string | null;\n /** The shared subscription's group, or `null` for an ordinary subscription. */\n group: string | null;\n /**\n * Whether the server held this topic for the session before the\n * application subscribed, and the `subscribed` that answers the\n * application's subscribe hasn't arrived yet. Until it does, messages on\n * the topic are the server's own resume: they are dropped without an\n * acknowledgement, because the subscribe replays them.\n */\n claiming: boolean;\n}\n\n/** One wildcard subscription. */\ninterface Pattern {\n /** Where the messages of every topic it owns go. */\n channel: Channel;\n /** Which subscription this is; the oldest matching pattern owns a new topic. */\n generation: number;\n}\n\n/** How a served connection ended. */\ntype Ending = { kind: \"stop\" } | { kind: \"lost\"; code: CloseCode | null } | { kind: \"pause\" };\n\n/** The outcome of one connection attempt. */\ntype Attempt =\n | { kind: \"connected\"; handshake: Handshake; resumed: string[] }\n | { kind: \"failed\"; failure: ConnectFailure }\n | { kind: \"stopped\" };\n\n/**\n * Creates a version 4 UUID, with `crypto.randomUUID` where the runtime has\n * it (browsers only offer it on secure origins) and `getRandomValues`\n * otherwise.\n *\n * @returns The UUID.\n */\nexport function uuid(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * Turns an unexpected reply during connecting into a failure.\n *\n * @param reply - What the server sent instead of the expected reply.\n * @returns The failure; retryable only for the server's temporary refusals\n * and for replies of the wrong type.\n */\nfunction refusal(reply: ServerMessage): ConnectFailure {\n if (reply.type === \"error\") {\n const error = PopSubError.server(errorCode(reply.code), reply.message, reply.retry_after ?? null);\n return new ConnectFailure(error, error.isTemporary());\n }\n return new ConnectFailure(new PopSubError(\"protocol\", `unexpected ${reply.type} while connecting`), true);\n}\n\n/** The state and the run loop behind one `Client`. */\nexport class Engine {\n /** How to connect. */\n readonly #config: ResolvedConfig;\n /** Where events go. */\n readonly emitter = new Emitter();\n /** Subscribed topics. */\n readonly #topics = new Map<string, Topic>();\n /** Wildcard subscriptions, by pattern. */\n readonly #patterns = new Map<string, Pattern>();\n /**\n * Topics the server restored for the session that the application hasn't\n * subscribed to in this process. Their messages are dropped without an\n * acknowledgement, so the server keeps them for the session.\n */\n #unclaimed = new Set<string>();\n /**\n * Whether the server left the session's topics unattached on this\n * connection (`authenticated.held`). Then nothing arrives on a topic\n * until the engine subscribes to it, so nothing is unclaimed, and\n * `#restore` subscribes to the resumed topics itself.\n */\n #held = false;\n /** Subscribes waiting for `subscribed`, by topic. */\n readonly #subscribeWaiters = new Map<string, Settle<void>>();\n /** Requests waiting for a reply, by id. */\n readonly #pending = new Map<number, Pending>();\n /** Confirmed publishes not yet confirmed, by request id, in id order, for resending. */\n readonly #unconfirmed = new Map<number, ClientMessage>();\n /** QoS 0 publishes and unsubscribes to send once connected. */\n #offline: ClientMessage[] = [];\n /** The next request id. */\n #nextId = 1;\n /** The next subscription generation. */\n #nextGeneration = 1;\n /** Whether a connection has ever succeeded, so `clean_start` is only sent once. */\n #connectedOnce = false;\n /** How long to wait for anything from the server before giving up on the connection. */\n #silenceMs = DEFAULT_SILENCE_MS;\n /** How long a connection may be silent before a `ping`, and between `ping`s while it stays silent. */\n #pingMs = DEFAULT_PING_MS;\n /** The server's per-subscription window. */\n #maxInflight = DEFAULT_MAX_INFLIGHT;\n /** The served connection, while there is one. */\n #connection: Handshake | null = null;\n /** Ends the served connection, while there is one. */\n #endServe: ((ending: Ending) => void) | null = null;\n /** Re-checks whatever the run loop is waiting for; set by each wait. */\n #wake: (() => void) | null = null;\n /** Whether the application asked to close. */\n #closing = false;\n /** Why the client stopped, once it has. */\n #stopped: { code: CloseCode | null } | null = null;\n /** Settles when the first connection is up, or rejects with what stopped the client first. */\n readonly ready: Promise<void>;\n /** Settles `ready`. */\n #ready: Settle<void> | null = null;\n /** Settles when the run loop has finished and the client has stopped. */\n readonly finished: Promise<void>;\n /** Settles `finished`. */\n #finish: () => void = () => undefined;\n\n /**\n * Builds an engine and starts its run loop.\n *\n * @param config - How to connect.\n */\n constructor(config: ResolvedConfig) {\n this.#config = config;\n this.ready = new Promise<void>((resolve, reject) => {\n this.#ready = { resolve, reject };\n });\n this.ready.catch(() => undefined);\n this.finished = new Promise<void>((resolve) => {\n this.#finish = resolve;\n });\n void this.#run();\n }\n\n /**\n * Why the client stopped, if it has.\n *\n * @returns `{ code }` once stopped (the code is `null` when the\n * application closed it or it ran out of attempts), `null` while running.\n */\n get stopped(): { code: CloseCode | null } | null {\n return this.#stopped;\n }\n\n /**\n * Subscribes to a topic or a wildcard pattern, replacing any earlier\n * subscription to the same name. With a group it joins a shared\n * subscription to the topic.\n *\n * Subscribing again to a topic by name starts over from `from`.\n * Subscribing again to a pattern keeps the topics it owned (see\n * `#replacePattern`).\n *\n * A topic the server held for the session, subscribed by name or matched\n * by the pattern, is claimed: it is tracked with `claiming` set, so what\n * the server sent on its own is dropped until the `subscribed` that\n * answers the claim. A topic subscribed again while its claim is\n * unanswered stays `claiming`. For a pattern each claimed topic gets its own\n * subscribe by name with `from: \"resume\"`, sent after the pattern's.\n * While disconnected nothing is sent; `#restore` sends the claims on the\n * next connection.\n *\n * @param topic - The topic, or a pattern such as `orders/#`.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n * @returns The subscription, and a promise that settles when the server\n * confirms it.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n subscribe(\n topic: string,\n from: WireStartFrom,\n group: string | null = null,\n ): { subscription: Subscription; done: Promise<void> } {\n this.#throwIfStopped();\n const generation = this.#nextGeneration++;\n const channel = new Channel(topic, {\n taken: (message) => {\n this.#taken(message.topic, generation, message);\n },\n leave: () => {\n this.#forget(topic, generation);\n },\n });\n const wildcard = group === null && isPattern(topic);\n const stillClaiming = this.#topics.get(topic)?.claiming === true;\n if (wildcard && this.#patterns.has(topic)) {\n this.#replacePattern(topic, channel, generation);\n } else {\n this.#release(topic, null);\n }\n this.#subscribeWaiters\n .get(topic)\n ?.reject(new PopSubError(\"protocol\", `replaced by a later subscribe to '${topic}'`));\n let claimed: string[] = [];\n if (wildcard) {\n this.#patterns.set(topic, { channel, generation });\n claimed = this.#claimMatching(topic, channel, generation);\n } else {\n this.#topics.set(topic, {\n channel,\n from,\n generation,\n tracker: new DeliveryTracker(ACK_MEMORY, group !== null),\n overflowed: false,\n owner: null,\n group,\n claiming: this.#unclaimed.delete(topic) || stillClaiming,\n });\n }\n const done = new Promise<void>((resolve, reject) => {\n this.#subscribeWaiters.set(topic, { resolve, reject });\n });\n if (this.#connection !== null) {\n this.#sendSubscribe(topic, generation, from, group);\n for (const name of claimed) {\n this.#sendSubscribe(name, generation, \"resume\", null);\n }\n }\n return { subscription: new Subscription(channel), done };\n }\n\n /**\n * Unsubscribes from a topic, or from a pattern and every topic joined\n * through it. While disconnected the unsubscribes are queued and the\n * call succeeds at once.\n *\n * @param topic - The topic or pattern.\n * @returns A promise that settles with the server's reply to the\n * unsubscribe for `topic` itself.\n */\n unsubscribe(topic: string): Promise<void> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n const released = this.#release(topic, null);\n const [first, ...owned] = released.length === 0 ? [topic] : released;\n if (this.#connection === null) {\n for (const name of [first ?? topic, ...owned]) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n }\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"unsubscribe\", settle: { resolve, reject } });\n this.#send({ type: \"unsubscribe\", topic: first ?? topic }, id);\n for (const name of owned) {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n });\n }\n\n /**\n * Publishes at QoS 0. While disconnected the publish is queued.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n publish(topic: string, payload: string, encoding: Encoding | null = null): void {\n this.#throwIfStopped();\n this.#queueOffline(publishFrame(topic, payload, encoding));\n this.#flushOffline();\n }\n\n /**\n * Publishes at QoS 1 under a new `message_id`, resending it after every\n * reconnect until the server confirms it.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @returns A promise that settles with the `seq` and id once stored.\n */\n publishConfirmed(topic: string, payload: string, encoding: Encoding | null = null): Promise<Published> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n return new Promise<Published>((resolve, reject) => {\n const id = this.#takeId();\n const message: ClientMessage = {\n ...publishFrame(topic, payload, encoding),\n message_id: uuid(),\n qos: 1,\n };\n this.#pending.set(id, { kind: \"publish\", settle: { resolve, reject } });\n this.#unconfirmed.set(id, message);\n if (this.#connection !== null) {\n this.#send(message, id);\n }\n });\n }\n\n /**\n * Acknowledges a message (from `Message.ack`). While disconnected it is\n * only remembered, so a redelivery is acknowledged again.\n *\n * @param topic - The topic.\n * @param seq - The message's `seq`.\n */\n ack(topic: string, seq: number): void {\n this.#topics.get(topic)?.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic, seq });\n }\n\n /**\n * Sends a request that is never queued while disconnected and never\n * resent (the admin requests), and returns its reply.\n *\n * @param message - The request.\n * @returns A promise that settles with the reply, rejecting with a\n * `server` error for an `error` frame, or `connect` when disconnected\n * or when the connection drops first.\n */\n request(message: ClientMessage): Promise<ServerMessage> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n if (this.#connection === null) {\n return Promise.reject(\n new PopSubError(\"connect\", \"not connected; this request isn't queued while disconnected\"),\n );\n }\n return new Promise<ServerMessage>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"request\", settle: { resolve, reject } });\n this.#send(message, id);\n });\n }\n\n /**\n * Closes the connection and stops the client. Pending requests fail with\n * a `closed` error.\n *\n * @returns A promise that settles once the client has stopped.\n */\n close(): Promise<void> {\n if (this.#stopped === null) {\n this.#closing = true;\n this.#wake?.();\n }\n return this.finished;\n }\n\n /**\n * Runs until the client stops, then stops it. An unexpected exception\n * stops the client too, and becomes the cause of the error `ready`\n * rejects with, so the returned promise never rejects.\n */\n async #run(): Promise<void> {\n try {\n this.#stop(await this.#loop());\n } catch (error) {\n this.#stop(null, error);\n }\n }\n\n /**\n * Connects, serves the connection, reconnects with backoff, and settles\n * `ready` with the first outcome, until the client must stop.\n *\n * @returns The close code that stopped the client, or `null` when the\n * application closed it, it ran out of attempts, or connecting failed\n * in a way retrying can't fix.\n */\n async #loop(): Promise<CloseCode | null> {\n let attempt = 0;\n let lastError: PopSubError | null = null;\n while (!this.#closing) {\n const outcome = await this.#connectOnce();\n if (outcome.kind === \"stopped\") {\n break;\n }\n if (outcome.kind === \"connected\") {\n attempt = 0;\n this.#connectedOnce = true;\n this.#ready?.resolve();\n this.#ready = null;\n this.emitter.emit({ type: \"connected\", resumed: outcome.resumed });\n const ending = await this.#serve(outcome.handshake, outcome.resumed);\n if (ending.kind === \"stop\") {\n break;\n }\n this.#failRequests();\n if (ending.kind === \"pause\") {\n this.emitter.emit({ type: \"disconnected\", code: null, reconnecting: true });\n if (!(await this.#waitForRoom())) {\n break;\n }\n continue;\n }\n const reconnecting = this.#shouldReconnect(ending.code);\n this.emitter.emit({ type: \"disconnected\", code: ending.code, reconnecting });\n if (!reconnecting) {\n return ending.code;\n }\n } else {\n lastError = outcome.failure.error;\n if (!outcome.failure.retry) {\n this.#ready?.reject(outcome.failure.error);\n this.#ready = null;\n break;\n }\n }\n attempt += 1;\n const maxAttempts = this.#config.reconnect.maxAttempts;\n if (maxAttempts !== null && attempt > maxAttempts) {\n const reason = lastError === null ? \"\" : `; the last attempt failed: ${lastError.message}`;\n this.#ready?.reject(\n new PopSubError(\"connect\", `ran out of reconnect attempts${reason}`, { cause: lastError }),\n );\n this.#ready = null;\n break;\n }\n if (!(await this.#sleep(jitteredDelay(this.#config.reconnect, attempt)))) {\n break;\n }\n }\n return null;\n }\n\n /**\n * Decides whether to reconnect after a connection was lost.\n *\n * @param code - The server's close code, if it sent one.\n * @returns True to reconnect. An expired token only allows it with\n * password credentials, which log in again.\n */\n #shouldReconnect(code: CloseCode | null): boolean {\n if (code === null) {\n return true;\n }\n if (code === 4004) {\n return \"password\" in this.#config.credentials;\n }\n return shouldReconnect(code);\n }\n\n /**\n * Waits before the next attempt, unless the application closes the client.\n *\n * @param ms - How long to wait.\n * @returns False when the application closed the client while waiting.\n */\n #sleep(ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (this.#closing) {\n resolve(false);\n return;\n }\n const timer = setTimeout(() => {\n this.#wake = null;\n resolve(true);\n }, ms);\n this.#wake = () => {\n if (this.#closing) {\n clearTimeout(timer);\n this.#wake = null;\n resolve(false);\n }\n };\n });\n }\n\n /**\n * After a buffer overflowed, waits until every overflowed topic's buffer\n * is down to half of `subscriptionBuffer` (or the topic is gone).\n *\n * @returns False when the application closed the client while waiting.\n */\n #waitForRoom(): Promise<boolean> {\n const low = Math.floor(this.#config.subscriptionBuffer / 2);\n const drained = (): boolean =>\n [...this.#topics.values()].every((topic) => !topic.overflowed || topic.channel.size <= low);\n return new Promise((resolve) => {\n const check = (): void => {\n if (this.#closing) {\n this.#wake = null;\n resolve(false);\n } else if (drained()) {\n this.#wake = null;\n resolve(true);\n }\n };\n this.#wake = check;\n check();\n });\n }\n\n /**\n * Opens a connection, logs in if needed, and authenticates. With a\n * session id the `auth` asks the server to hold the session's topics\n * (`hold_resumed`), and `#held` records whether it did.\n *\n * @returns The authenticated connection with the topics the server\n * restored, a failure saying whether retrying could help, or `stopped`\n * when the application closed the client meanwhile.\n */\n async #connectOnce(): Promise<Attempt> {\n let handshake: Handshake;\n try {\n handshake = new Handshake(this.#config.url, this.#config.requestTimeoutMs);\n } catch (error) {\n const failure =\n error instanceof PopSubError ? error : new PopSubError(\"config\", String(error), { cause: error });\n return { kind: \"failed\", failure: new ConnectFailure(failure, false) };\n }\n this.#wake = () => {\n if (this.#closing) {\n handshake.abort();\n }\n };\n try {\n await handshake.opened();\n const credentials = this.#config.credentials;\n let token: string;\n if (\"token\" in credentials) {\n token = credentials.token;\n } else {\n const reply = await handshake.exchange(this.#takeId(), {\n type: \"login\",\n username: credentials.username,\n password: credentials.password,\n });\n if (reply.type !== \"logged_in\") {\n throw refusal(reply);\n }\n token = reply.token;\n }\n const auth: ClientMessage = { type: \"auth\", token, protocol: PROTOCOL_VERSION };\n if (this.#config.sessionId !== null) {\n auth.session_id = this.#config.sessionId;\n auth.hold_resumed = true;\n }\n if (this.#config.cleanStart && !this.#connectedOnce) {\n auth.clean_start = true;\n }\n const reply = await handshake.exchange(this.#takeId(), auth);\n if (reply.type !== \"authenticated\") {\n throw refusal(reply);\n }\n this.#applyLimits(reply.limits);\n this.#held = reply.held === true;\n return { kind: \"connected\", handshake, resumed: reply.resumed ?? [] };\n } catch (reason) {\n handshake.close();\n if (reason instanceof Aborted) {\n return { kind: \"stopped\" };\n }\n if (reason instanceof ConnectFailure) {\n return { kind: \"failed\", failure: reason };\n }\n const message = reason instanceof Error ? reason.message : String(reason);\n return {\n kind: \"failed\",\n failure: new ConnectFailure(new PopSubError(\"connect\", message, { cause: reason }), true),\n };\n } finally {\n this.#wake = null;\n }\n }\n\n /**\n * Reads the server's limits: when to `ping`, how much silence to allow,\n * and the window size.\n *\n * @param limits - The limits from `authenticated`.\n */\n #applyLimits(limits: Limits): void {\n const idle = Math.max(1, limits.idle_timeout_secs);\n const heartbeat = Math.max(1, limits.heartbeat_secs);\n this.#pingMs = heartbeat * 1000;\n this.#silenceMs = (idle + heartbeat) * 1000;\n if (Number.isFinite(limits.max_inflight) && limits.max_inflight > 0) {\n this.#maxInflight = limits.max_inflight;\n }\n }\n\n /**\n * Serves one connection until it ends. Works out which restored topics\n * are unclaimed (those the engine isn't tracking, or none when the server\n * holds the session's topics), restores subscriptions\n * and resends, then handles frames as they arrive. A timer sends `ping` while\n * the connection is silent and ends it as lost once the silence passes\n * `idle_timeout_secs + heartbeat_secs`.\n *\n * @param handshake - The authenticated connection.\n * @param resumed - Topics the server restored for the session.\n * @returns How the connection ended.\n */\n #serve(handshake: Handshake, resumed: string[]): Promise<Ending> {\n return new Promise<Ending>((resolve) => {\n let lastHeard = Date.now();\n let lastPing = lastHeard;\n const tick = Math.max(50, Math.min(1000, this.#pingMs / 4));\n const timer = setInterval(() => {\n const now = Date.now();\n if (now - lastHeard >= this.#silenceMs) {\n finish({ kind: \"lost\", code: null });\n } else if (now - lastHeard >= this.#pingMs && now - lastPing >= this.#pingMs) {\n lastPing = now;\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"ping\" });\n this.#send({ type: \"ping\" }, id);\n }\n }, tick);\n const live = (): boolean => this.#connection === handshake;\n const finish = (ending: Ending): void => {\n if (!live()) {\n return;\n }\n clearInterval(timer);\n this.#connection = null;\n this.#endServe = null;\n this.#wake = null;\n handshake.close();\n resolve(ending);\n };\n this.#connection = handshake;\n this.#endServe = finish;\n this.#wake = () => {\n if (this.#closing) {\n finish({ kind: \"stop\" });\n }\n };\n const early = handshake.handOver({\n text: (text) => {\n lastHeard = Date.now();\n lastPing = lastHeard;\n this.#onText(text);\n },\n closed: (code) => {\n finish({ kind: \"lost\", code: closeCode(code) });\n },\n });\n this.#unclaimed = new Set(resumed.filter((name) => !this.#held && !this.#topics.has(name)));\n this.#restore(resumed);\n for (const text of early) {\n if (!live()) {\n return;\n }\n this.#onText(text);\n }\n });\n }\n\n /**\n * Restores state on a new connection: resubscribes, resends unconfirmed\n * publishes, and sends queued frames.\n *\n * When the server holds the session's topics (`#held`), each topic it\n * lists as resumed that the engine tracks is subscribed again from\n * `resume`, which is one past the session's cursor. Otherwise\n * topics the server restored for the session are left to it, except\n * those whose buffer overflowed and those still waiting for the\n * `subscribed` that claims them, which are subscribed again the way the\n * application asked (`resume` for one owned by a pattern); every other\n * topic is subscribed again from the next `seq` it expects, so nothing\n * still in the log is missed.\n * A shared subscription always rejoins its group with `resume`, because\n * the group's position is on the server. Wildcard patterns are sent\n * after the topics, in name order, from `{\"seq\": 1}`: the server skips\n * topics the connection holds, so that joins only topics created during\n * the disconnect, from their first message.\n *\n * @param resumed - Topics the server restored.\n */\n #restore(resumed: string[]): void {\n const restored = new Set(resumed);\n for (const [name, topic] of this.#topics) {\n if (topic.group !== null) {\n this.#sendSubscribe(name, topic.generation, \"resume\", topic.group);\n } else if (topic.claiming) {\n this.#sendSubscribe(name, topic.generation, topic.owner === null ? topic.from : \"resume\", null);\n } else if (!restored.has(name) || topic.overflowed) {\n const next = topic.tracker.nextExpected;\n this.#sendSubscribe(name, topic.generation, next === null ? topic.from : { seq: next }, null);\n } else if (this.#held) {\n this.#sendSubscribe(name, topic.generation, \"resume\", null);\n }\n topic.overflowed = false;\n }\n for (const name of [...this.#patterns.keys()].sort()) {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined) {\n this.#sendSubscribe(name, pattern.generation, { seq: 1 }, null);\n }\n }\n for (const [id, message] of this.#unconfirmed) {\n this.#send(message, id);\n }\n this.#flushOffline();\n }\n\n /**\n * Sends a subscribe and records it as pending.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription it is for.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n */\n #sendSubscribe(topic: string, generation: number, from: WireStartFrom, group: string | null): void {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"subscribe\", topic, generation });\n this.#send(\n group === null ? { type: \"subscribe\", topic, from } : { type: \"subscribe\", topic, from, group },\n id,\n );\n }\n\n /**\n * Queues a frame to send once connected, dropping the oldest beyond `OFFLINE_LIMIT`.\n *\n * @param message - A QoS 0 publish or an unsubscribe.\n */\n #queueOffline(message: ClientMessage): void {\n if (this.#offline.length >= OFFLINE_LIMIT) {\n this.#offline.shift();\n }\n this.#offline.push(message);\n }\n\n /** Sends every queued frame, if connected. Unsubscribes get an id. */\n #flushOffline(): void {\n if (this.#connection === null) {\n return;\n }\n const queued = this.#offline;\n this.#offline = [];\n for (const message of queued) {\n this.#send(message, message.type === \"unsubscribe\" ? this.#takeId() : undefined);\n }\n }\n\n /**\n * Sends a frame if connected. A frame sent while the socket is closing is\n * lost with it; the close that follows decides what is resent.\n *\n * @param message - The frame.\n * @param id - The request id, when a reply is expected.\n */\n #send(message: ClientMessage, id?: number): void {\n const socket = this.#connection?.socket;\n if (socket?.readyState !== WebSocket.OPEN) {\n return;\n }\n socket.send(encodeFrame(message, id));\n }\n\n /**\n * Takes a request id.\n *\n * @returns A new id.\n */\n #takeId(): number {\n const id = this.#nextId;\n this.#nextId += 1;\n return id;\n }\n\n /**\n * Stops tracking one topic. A topic subscribed by name has its\n * subscription ended; a topic owned by a pattern only stops, and the\n * pattern's subscription carries on.\n *\n * @param topic - The topic.\n * @returns Whether it was tracked.\n */\n #dropTopic(topic: string): boolean {\n const entry = this.#topics.get(topic);\n if (entry === undefined) {\n return false;\n }\n this.#topics.delete(topic);\n if (entry.owner === null) {\n entry.channel.end();\n }\n return true;\n }\n\n /**\n * Starts tracking a topic the server joined for one of this client's\n * wildcard subscriptions. When several patterns match, the oldest owns it.\n *\n * @param name - The topic.\n * @param start - The first `seq` the server will send, or `null` when unknown.\n * @returns The tracked topic, or `undefined` when no pattern matches.\n */\n #adopt(name: string, start: number | null): Topic | undefined {\n let owner: string | null = null;\n let oldest: Pattern | null = null;\n for (const [pattern, entry] of this.#patterns) {\n if (matchesPattern(pattern, name) && (oldest === null || entry.generation < oldest.generation)) {\n owner = pattern;\n oldest = entry;\n }\n }\n if (owner === null || oldest === null) {\n return undefined;\n }\n const tracker = new DeliveryTracker();\n tracker.nextExpected = start;\n const topic: Topic = {\n channel: oldest.channel,\n from: { seq: start ?? 1 },\n generation: oldest.generation,\n tracker,\n overflowed: false,\n owner,\n group: null,\n claiming: false,\n };\n this.#topics.set(name, topic);\n return topic;\n }\n\n /**\n * Moves a held pattern to a new subscription. The topics it owned are\n * pointed at the new channel and generation and keep their trackers, so\n * each keeps the next `seq` it expects: the server sends nothing again\n * for topics the connection holds. The earlier channel ends; what it\n * still holds can be taken or dropped without any effect on the topics.\n * Acknowledgements held back for the earlier channel's full buffer are\n * sent now, because nothing will report those messages as taken to the\n * new subscription.\n *\n * @param pattern - The pattern, which must be held.\n * @param channel - The new subscription's channel.\n * @param generation - The new subscription.\n */\n #replacePattern(pattern: string, channel: Channel, generation: number): void {\n this.#patterns.get(pattern)?.channel.end();\n for (const [name, topic] of this.#topics) {\n if (topic.owner !== pattern) {\n continue;\n }\n topic.channel = channel;\n topic.generation = generation;\n for (const seq of topic.tracker.deferred) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n }\n topic.tracker.deferred.clear();\n }\n }\n\n /**\n * Claims every unclaimed topic of the session a pattern matches: each\n * stops being unclaimed and is tracked as owned by the pattern, with\n * `claiming` set until its own `subscribed` arrives.\n *\n * @param pattern - The pattern.\n * @param channel - The pattern's channel.\n * @param generation - The pattern's subscription.\n * @returns The claimed topics in name order, each of which needs a\n * subscribe by name with `from: \"resume\"`.\n */\n #claimMatching(pattern: string, channel: Channel, generation: number): string[] {\n const claimed = [...this.#unclaimed].filter((name) => matchesPattern(pattern, name)).sort();\n for (const name of claimed) {\n this.#unclaimed.delete(name);\n this.#topics.set(name, {\n channel,\n from: \"resume\",\n generation,\n tracker: new DeliveryTracker(),\n overflowed: false,\n owner: pattern,\n group: null,\n claiming: true,\n });\n }\n return claimed;\n }\n\n /**\n * Stops tracking a subscription and ends it: a topic subscribed by name,\n * or a wildcard pattern together with every topic joined through it.\n *\n * @param name - The topic or pattern.\n * @param generation - Only release it if it is still this subscription;\n * `null` releases whatever is there.\n * @returns What to unsubscribe from on the server: the name first, and\n * for a pattern the topics it owned. Empty when nothing was released.\n */\n #release(name: string, generation: number | null): string[] {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined && (generation === null || pattern.generation === generation)) {\n this.#patterns.delete(name);\n pattern.channel.end();\n const names = [name];\n for (const [topic, entry] of this.#topics) {\n if (entry.owner === name) {\n this.#topics.delete(topic);\n names.push(topic);\n }\n }\n return names;\n }\n const topic = this.#topics.get(name);\n if (topic?.owner === null && (generation === null || topic.generation === generation)) {\n this.#topics.delete(name);\n topic.channel.end();\n return [name];\n }\n return [];\n }\n\n /**\n * Unsubscribes without waiting, when the application closes a\n * subscription, if the topic or pattern still belongs to it. A pattern's\n * owned topics are unsubscribed with it.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription being closed.\n */\n #forget(topic: string, generation: number): void {\n const released = this.#release(topic, generation);\n if (released.length === 0) {\n return;\n }\n this.#subscribeWaiters.get(topic)?.reject(PopSubError.closed(null));\n this.#subscribeWaiters.delete(topic);\n for (const name of released) {\n if (this.#connection === null) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n } else {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n }\n this.#wake?.();\n }\n\n /**\n * Called when the application takes a message: sends an acknowledgement\n * held back for a full buffer, and lets a paused client reconnect once\n * there is room.\n *\n * @param topic - The topic.\n * @param generation - The subscription the message came from.\n * @param message - The message taken.\n */\n #taken(topic: string, generation: number, message: Message): void {\n const entry = this.#topics.get(topic);\n if (entry?.generation === generation && entry.tracker.deferred.delete(message.seq)) {\n entry.tracker.acked.insert(message.seq);\n this.#send({ type: \"ack\", topic, seq: message.seq });\n }\n this.#wake?.();\n }\n\n /**\n * Parses a frame and acts on it; frames this client doesn't know are ignored.\n *\n * @param text - The frame's text.\n */\n #onText(text: string): void {\n const frame = parseServerFrame(text);\n if (frame !== null) {\n this.#onFrame(frame);\n }\n }\n\n /**\n * Acts on a frame from the server. A reply's pending entry is removed by\n * its id first, so a `pong` needs nothing more: hearing it at all is what\n * keeps the connection from being given up as silent. A `subscribed` for\n * a topic being claimed ends the claim and starts its next expected `seq`\n * over at `replay_from`.\n *\n * @param frame - The frame.\n */\n #onFrame(frame: ServerFrame): void {\n const id = typeof frame.id === \"number\" ? frame.id : null;\n const pending = id === null ? undefined : this.#pending.get(id);\n if (id !== null) {\n this.#pending.delete(id);\n }\n if (pending?.kind === \"request\") {\n if (frame.type === \"error\") {\n pending.settle.reject(\n PopSubError.server(errorCode(frame.code), frame.message, frame.retry_after ?? null),\n );\n } else {\n pending.settle.resolve(frame);\n }\n return;\n }\n const unprompted = frame.id === undefined || frame.id === null;\n switch (frame.type) {\n case \"message\":\n this.#deliver(frame);\n break;\n case \"subscribed\": {\n if (!this.#patterns.has(frame.topic)) {\n const tracked = this.#topics.get(frame.topic);\n if (tracked === undefined) {\n this.#adopt(frame.topic, frame.replay_from);\n } else {\n if (tracked.claiming) {\n tracked.claiming = false;\n tracked.tracker.nextExpected = null;\n }\n tracked.tracker.moveTo(frame.replay_from);\n }\n }\n const waiter = this.#subscribeWaiters.get(frame.topic);\n if (waiter !== undefined) {\n this.#subscribeWaiters.delete(frame.topic);\n waiter.resolve();\n }\n break;\n }\n case \"unsubscribed\":\n if (pending?.kind === \"unsubscribe\") {\n pending.settle.resolve();\n } else if (unprompted && this.#dropTopic(frame.topic)) {\n this.emitter.emit({ type: \"unsubscribed\", topic: frame.topic });\n }\n break;\n case \"published\":\n if (pending?.kind === \"publish\" && id !== null) {\n this.#unconfirmed.delete(id);\n pending.settle.resolve({ seq: frame.seq, messageId: frame.message_id });\n }\n break;\n case \"truncated\":\n this.#topics.get(frame.topic)?.tracker.moveTo(frame.first_available);\n this.emitter.emit({ type: \"truncated\", topic: frame.topic, firstAvailable: frame.first_available });\n break;\n case \"stalled\":\n this.emitter.emit({ type: \"stalled\", topic: frame.topic, seq: frame.seq });\n break;\n case \"auth_expiring\":\n this.emitter.emit({ type: \"authExpiring\", expiresAtMs: frame.expires_at_ms });\n if (\"password\" in this.#config.credentials) {\n const loginId = this.#takeId();\n this.#pending.set(loginId, { kind: \"relogin\" });\n const { username, password } = this.#config.credentials;\n this.#send({ type: \"login\", username, password }, loginId);\n }\n break;\n case \"logged_in\":\n if (pending?.kind === \"relogin\") {\n const authId = this.#takeId();\n this.#pending.set(authId, { kind: \"reauth\" });\n this.#send({ type: \"auth\", token: frame.token, protocol: PROTOCOL_VERSION }, authId);\n }\n break;\n case \"authenticated\":\n if (pending?.kind === \"reauth\") {\n this.emitter.emit({ type: \"authRefreshed\" });\n }\n break;\n case \"pong\":\n break;\n case \"error\":\n this.#onError(pending, id, frame);\n break;\n default:\n break;\n }\n }\n\n /**\n * Routes an error frame to the request it answers, or to the events. A\n * refused subscribe ends that subscription; a refused resubscribe of a\n * topic owned by a pattern only stops tracking that topic.\n *\n * @param pending - The request it answers, if its id matched one.\n * @param id - Its request id, if it had one.\n * @param frame - The error frame.\n */\n #onError(\n pending: Pending | undefined,\n id: number | null,\n frame: Extract<ServerMessage, { type: \"error\" }>,\n ): void {\n const code = errorCode(frame.code);\n const error = PopSubError.server(code, frame.message, frame.retry_after ?? null);\n switch (pending?.kind) {\n case \"subscribe\": {\n const released = this.#release(pending.topic, pending.generation).length > 0;\n const owned = this.#topics.get(pending.topic);\n if (!released && owned?.owner != null && owned.generation === pending.generation) {\n this.#topics.delete(pending.topic);\n }\n if (released) {\n const waiter = this.#subscribeWaiters.get(pending.topic);\n this.#subscribeWaiters.delete(pending.topic);\n waiter?.reject(error);\n }\n break;\n }\n case \"unsubscribe\":\n pending.settle.reject(error);\n break;\n case \"publish\":\n if (id !== null) {\n this.#unconfirmed.delete(id);\n }\n pending.settle.reject(error);\n break;\n case \"ping\":\n break;\n default:\n this.emitter.emit({ type: \"serverError\", code, message: frame.message });\n break;\n }\n }\n\n /**\n * Hands a delivered message to its subscription, dropping duplicates,\n * acknowledging as the ack mode says, and holding back when the buffer is\n * full. A message for an untracked topic is adopted by the oldest\n * matching wildcard pattern; when none matches it is acknowledged and dropped.\n *\n * A message on a topic the server holds for the session that the\n * application hasn't subscribed to here, or whose subscribe is still\n * unanswered, is dropped without an acknowledgement: the server keeps it\n * and replays it when the application's subscribe is handled.\n *\n * @param delivery - The delivered message.\n */\n #deliver(delivery: Extract<ServerMessage, { type: \"message\" }>): void {\n const { topic: name, seq } = delivery;\n const qos: 0 | 1 = delivery.qos === 1 ? 1 : 0;\n if (this.#unclaimed.has(name)) {\n return;\n }\n const topic = this.#topics.get(name) ?? this.#adopt(name, null);\n if (topic === undefined) {\n if (qos === 1) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n if (topic.overflowed || topic.claiming) {\n return;\n }\n const automatic = this.#config.ackMode === \"auto\";\n if (topic.tracker.isDuplicate(seq)) {\n if (qos === 1 && topic.tracker.reacksDuplicate(seq, automatic)) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n const buffered = topic.channel.size;\n if (buffered >= this.#config.subscriptionBuffer + this.#maxInflight) {\n topic.overflowed = true;\n this.#endServe?.({ kind: \"pause\" });\n return;\n }\n topic.tracker.accept(seq);\n let acker: (() => void) | null = null;\n if (qos === 1) {\n if (!automatic) {\n acker = () => {\n this.ack(name, seq);\n };\n } else if (buffered < this.#config.subscriptionBuffer) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n } else {\n topic.tracker.deferred.add(seq);\n }\n }\n topic.channel.push(\n new Message(\n {\n topic: name,\n seq,\n messageId: delivery.message_id,\n payload: delivery.payload,\n encoding: delivery.encoding === \"base64\" ? \"base64\" : null,\n qos,\n publishedAtMs: delivery.published_at_ms,\n },\n acker,\n ),\n );\n }\n\n /**\n * Fails every admin request still waiting when a connection ends: the\n * server may or may not have carried it out. `ping`s, token refreshes and\n * subscribes of the old connection are forgotten; subscribes are sent\n * again by `#restore`.\n */\n #failRequests(): void {\n for (const [id, pending] of this.#pending) {\n if (pending.kind === \"request\") {\n this.#pending.delete(id);\n pending.settle.reject(\n new PopSubError(\n \"connect\",\n \"the connection dropped before the reply; the request may or may not have been carried out\",\n ),\n );\n } else if (\n pending.kind === \"ping\" ||\n pending.kind === \"relogin\" ||\n pending.kind === \"reauth\" ||\n pending.kind === \"subscribe\"\n ) {\n this.#pending.delete(id);\n }\n }\n }\n\n /**\n * Throws if the client has stopped.\n *\n * @throws PopSubError of kind `closed` with the close code that stopped it.\n */\n #throwIfStopped(): void {\n if (this.#stopped !== null) {\n throw PopSubError.closed(this.#stopped.code);\n }\n }\n\n /**\n * Stops the client for good: records why, fails everything waiting, ends\n * every subscription, and removes every event listener.\n *\n * @param code - The close code that stopped it, if any.\n * @param cause - The unexpected exception that stopped it, if any.\n */\n #stop(code: CloseCode | null, cause?: unknown): void {\n this.#endServe?.({ kind: \"stop\" });\n this.#wake = null;\n this.#stopped = { code };\n const error = PopSubError.closed(code);\n this.#ready?.reject(\n cause === undefined\n ? error\n : new PopSubError(\n \"closed\",\n `the client stopped unexpectedly: ${cause instanceof Error ? cause.message : \"unknown error\"}`,\n { cause },\n ),\n );\n this.#ready = null;\n for (const waiter of this.#subscribeWaiters.values()) {\n waiter.reject(error);\n }\n this.#subscribeWaiters.clear();\n for (const pending of this.#pending.values()) {\n if (pending.kind === \"unsubscribe\" || pending.kind === \"publish\" || pending.kind === \"request\") {\n pending.settle.reject(error);\n }\n }\n this.#pending.clear();\n this.#unconfirmed.clear();\n this.#offline = [];\n for (const topic of this.#topics.values()) {\n topic.channel.end();\n }\n this.#topics.clear();\n for (const pattern of this.#patterns.values()) {\n pattern.channel.end();\n }\n this.#patterns.clear();\n this.#unclaimed.clear();\n this.emitter.clear();\n this.#finish();\n }\n}\n"]}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The error every failing client call rejects or throws with.
3
+ *
4
+ * @module
5
+ */
6
+ import type { CloseCode, ErrorCode } from "./protocol.js";
7
+ /**
8
+ * Why a call failed.
9
+ *
10
+ * - `server`: the server refused the request; `code` says why.
11
+ * - `closed`: the client has stopped for good; `closeCode` is the close code
12
+ * that stopped it, or `null` when the application closed it or it ran out
13
+ * of reconnect attempts.
14
+ * - `timeout`: the request didn't complete within `requestTimeoutMs`.
15
+ * - `connect`: the server couldn't be reached, or the connection dropped
16
+ * before an admin request's reply.
17
+ * - `protocol`: the server sent something the client didn't expect.
18
+ * - `config`: the configuration is invalid.
19
+ */
20
+ export type ErrorKind = "server" | "closed" | "timeout" | "connect" | "protocol" | "config";
21
+ /** The extra fields a `PopSubError` may carry. */
22
+ export interface PopSubErrorDetails {
23
+ /** The server's error code, for `server` errors. */
24
+ code?: ErrorCode | null;
25
+ /** Seconds to wait before trying again, for `locked_out` and `rate_limited`. */
26
+ retryAfter?: number | null;
27
+ /** The close code that stopped the client, for `closed` errors. */
28
+ closeCode?: CloseCode | null;
29
+ /** The error or other value that led to this one, if any. */
30
+ cause?: unknown;
31
+ }
32
+ /** A failed client call. */
33
+ export declare class PopSubError extends Error {
34
+ /** What kind of failure this is. */
35
+ readonly kind: ErrorKind;
36
+ /** The server's error code, for `server` errors, otherwise `null`. */
37
+ readonly code: ErrorCode | null;
38
+ /** Seconds to wait before retrying, for limits, otherwise `null`. */
39
+ readonly retryAfter: number | null;
40
+ /** The close code that stopped the client, for `closed` errors, otherwise `null`. */
41
+ readonly closeCode: CloseCode | null;
42
+ /**
43
+ * Builds an error.
44
+ *
45
+ * @param kind - What kind of failure it is.
46
+ * @param message - What went wrong, for people.
47
+ * @param details - The code, retry delay or close code, where they apply.
48
+ */
49
+ constructor(kind: ErrorKind, message: string, details?: PopSubErrorDetails);
50
+ /**
51
+ * Builds the error for a refusal from the server.
52
+ *
53
+ * @param code - The error code.
54
+ * @param message - The server's message.
55
+ * @param retryAfter - Seconds to wait, when the server sent one.
56
+ * @returns The error.
57
+ */
58
+ static server(code: ErrorCode, message: string, retryAfter?: number | null): PopSubError;
59
+ /**
60
+ * Builds the error for calls on a client that has stopped.
61
+ *
62
+ * @param closeCode - The close code that stopped it, if any.
63
+ * @returns The error.
64
+ */
65
+ static closed(closeCode: CloseCode | null): PopSubError;
66
+ /**
67
+ * Builds the error for a request that took longer than the request timeout.
68
+ *
69
+ * @returns The error.
70
+ */
71
+ static timeout(): PopSubError;
72
+ /**
73
+ * Whether retrying the same call later might succeed.
74
+ *
75
+ * @returns True for timeouts, connection failures and the server's
76
+ * temporary refusals (`rate_limited`, `locked_out`,
77
+ * `storage_unavailable`, `session_unavailable`, `internal`).
78
+ */
79
+ isTemporary(): boolean;
80
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The error every failing client call rejects or throws with.
3
+ *
4
+ * @module
5
+ */
6
+ /** The server error codes that may succeed if the same request is retried later. */
7
+ const TEMPORARY_CODES = new Set([
8
+ "rate_limited",
9
+ "locked_out",
10
+ "storage_unavailable",
11
+ "session_unavailable",
12
+ "internal",
13
+ ]);
14
+ /** A failed client call. */
15
+ export class PopSubError extends Error {
16
+ /** What kind of failure this is. */
17
+ kind;
18
+ /** The server's error code, for `server` errors, otherwise `null`. */
19
+ code;
20
+ /** Seconds to wait before retrying, for limits, otherwise `null`. */
21
+ retryAfter;
22
+ /** The close code that stopped the client, for `closed` errors, otherwise `null`. */
23
+ closeCode;
24
+ /**
25
+ * Builds an error.
26
+ *
27
+ * @param kind - What kind of failure it is.
28
+ * @param message - What went wrong, for people.
29
+ * @param details - The code, retry delay or close code, where they apply.
30
+ */
31
+ constructor(kind, message, details = {}) {
32
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
33
+ this.name = "PopSubError";
34
+ this.kind = kind;
35
+ this.code = details.code ?? null;
36
+ this.retryAfter = details.retryAfter ?? null;
37
+ this.closeCode = details.closeCode ?? null;
38
+ }
39
+ /**
40
+ * Builds the error for a refusal from the server.
41
+ *
42
+ * @param code - The error code.
43
+ * @param message - The server's message.
44
+ * @param retryAfter - Seconds to wait, when the server sent one.
45
+ * @returns The error.
46
+ */
47
+ static server(code, message, retryAfter = null) {
48
+ return new PopSubError("server", `the server refused the request (${code}): ${message}`, {
49
+ code,
50
+ retryAfter,
51
+ });
52
+ }
53
+ /**
54
+ * Builds the error for calls on a client that has stopped.
55
+ *
56
+ * @param closeCode - The close code that stopped it, if any.
57
+ * @returns The error.
58
+ */
59
+ static closed(closeCode) {
60
+ const why = closeCode === null ? "" : ` (close code ${String(closeCode)})`;
61
+ return new PopSubError("closed", `the client is closed${why}`, { closeCode });
62
+ }
63
+ /**
64
+ * Builds the error for a request that took longer than the request timeout.
65
+ *
66
+ * @returns The error.
67
+ */
68
+ static timeout() {
69
+ return new PopSubError("timeout", "the request timed out");
70
+ }
71
+ /**
72
+ * Whether retrying the same call later might succeed.
73
+ *
74
+ * @returns True for timeouts, connection failures and the server's
75
+ * temporary refusals (`rate_limited`, `locked_out`,
76
+ * `storage_unavailable`, `session_unavailable`, `internal`).
77
+ */
78
+ isTemporary() {
79
+ switch (this.kind) {
80
+ case "timeout":
81
+ case "connect":
82
+ return true;
83
+ case "server":
84
+ return this.code !== null && TEMPORARY_CODES.has(this.code);
85
+ default:
86
+ return false;
87
+ }
88
+ }
89
+ }
90
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AA+BH,oFAAoF;AACpF,MAAM,eAAe,GAA2B,IAAI,GAAG,CAAY;IACjE,cAAc;IACd,YAAY;IACZ,qBAAqB;IACrB,qBAAqB;IACrB,UAAU;CACX,CAAC,CAAC;AAEH,4BAA4B;AAC5B,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,oCAAoC;IAC3B,IAAI,CAAY;IACzB,sEAAsE;IAC7D,IAAI,CAAmB;IAChC,qEAAqE;IAC5D,UAAU,CAAgB;IACnC,qFAAqF;IAC5E,SAAS,CAAmB;IAErC;;;;;;OAMG;IACH,YAAY,IAAe,EAAE,OAAe,EAAE,UAA8B,EAAE;QAC5E,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;QACnF,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC;QACjC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,IAAI,CAAC;QAC7C,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,OAAe,EAAE,aAA4B,IAAI;QAC9E,OAAO,IAAI,WAAW,CAAC,QAAQ,EAAE,mCAAmC,IAAI,MAAM,OAAO,EAAE,EAAE;YACvF,IAAI;YACJ,UAAU;SACX,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,SAA2B;QACvC,MAAM,GAAG,GAAG,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC;QAC3E,OAAO,IAAI,WAAW,CAAC,QAAQ,EAAE,uBAAuB,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,WAAW,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;IAC7D,CAAC;IAED;;;;;;OAMG;IACH,WAAW;QACT,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;YAClB,KAAK,SAAS,CAAC;YACf,KAAK,SAAS;gBACZ,OAAO,IAAI,CAAC;YACd,KAAK,QAAQ;gBACX,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC9D;gBACE,OAAO,KAAK,CAAC;QACjB,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The error every failing client call rejects or throws with.\n *\n * @module\n */\n\nimport type { CloseCode, ErrorCode } from \"./protocol.js\";\n\n/**\n * Why a call failed.\n *\n * - `server`: the server refused the request; `code` says why.\n * - `closed`: the client has stopped for good; `closeCode` is the close code\n * that stopped it, or `null` when the application closed it or it ran out\n * of reconnect attempts.\n * - `timeout`: the request didn't complete within `requestTimeoutMs`.\n * - `connect`: the server couldn't be reached, or the connection dropped\n * before an admin request's reply.\n * - `protocol`: the server sent something the client didn't expect.\n * - `config`: the configuration is invalid.\n */\nexport type ErrorKind = \"server\" | \"closed\" | \"timeout\" | \"connect\" | \"protocol\" | \"config\";\n\n/** The extra fields a `PopSubError` may carry. */\nexport interface PopSubErrorDetails {\n /** The server's error code, for `server` errors. */\n code?: ErrorCode | null;\n /** Seconds to wait before trying again, for `locked_out` and `rate_limited`. */\n retryAfter?: number | null;\n /** The close code that stopped the client, for `closed` errors. */\n closeCode?: CloseCode | null;\n /** The error or other value that led to this one, if any. */\n cause?: unknown;\n}\n\n/** The server error codes that may succeed if the same request is retried later. */\nconst TEMPORARY_CODES: ReadonlySet<ErrorCode> = new Set<ErrorCode>([\n \"rate_limited\",\n \"locked_out\",\n \"storage_unavailable\",\n \"session_unavailable\",\n \"internal\",\n]);\n\n/** A failed client call. */\nexport class PopSubError extends Error {\n /** What kind of failure this is. */\n readonly kind: ErrorKind;\n /** The server's error code, for `server` errors, otherwise `null`. */\n readonly code: ErrorCode | null;\n /** Seconds to wait before retrying, for limits, otherwise `null`. */\n readonly retryAfter: number | null;\n /** The close code that stopped the client, for `closed` errors, otherwise `null`. */\n readonly closeCode: CloseCode | null;\n\n /**\n * Builds an error.\n *\n * @param kind - What kind of failure it is.\n * @param message - What went wrong, for people.\n * @param details - The code, retry delay or close code, where they apply.\n */\n constructor(kind: ErrorKind, message: string, details: PopSubErrorDetails = {}) {\n super(message, details.cause === undefined ? undefined : { cause: details.cause });\n this.name = \"PopSubError\";\n this.kind = kind;\n this.code = details.code ?? null;\n this.retryAfter = details.retryAfter ?? null;\n this.closeCode = details.closeCode ?? null;\n }\n\n /**\n * Builds the error for a refusal from the server.\n *\n * @param code - The error code.\n * @param message - The server's message.\n * @param retryAfter - Seconds to wait, when the server sent one.\n * @returns The error.\n */\n static server(code: ErrorCode, message: string, retryAfter: number | null = null): PopSubError {\n return new PopSubError(\"server\", `the server refused the request (${code}): ${message}`, {\n code,\n retryAfter,\n });\n }\n\n /**\n * Builds the error for calls on a client that has stopped.\n *\n * @param closeCode - The close code that stopped it, if any.\n * @returns The error.\n */\n static closed(closeCode: CloseCode | null): PopSubError {\n const why = closeCode === null ? \"\" : ` (close code ${String(closeCode)})`;\n return new PopSubError(\"closed\", `the client is closed${why}`, { closeCode });\n }\n\n /**\n * Builds the error for a request that took longer than the request timeout.\n *\n * @returns The error.\n */\n static timeout(): PopSubError {\n return new PopSubError(\"timeout\", \"the request timed out\");\n }\n\n /**\n * Whether retrying the same call later might succeed.\n *\n * @returns True for timeouts, connection failures and the server's\n * temporary refusals (`rate_limited`, `locked_out`,\n * `storage_unavailable`, `session_unavailable`, `internal`).\n */\n isTemporary(): boolean {\n switch (this.kind) {\n case \"timeout\":\n case \"connect\":\n return true;\n case \"server\":\n return this.code !== null && TEMPORARY_CODES.has(this.code);\n default:\n return false;\n }\n }\n}\n"]}
@@ -0,0 +1,111 @@
1
+ /**
2
+ * What the client reports about its connection and subscriptions, and the
3
+ * listener registry that delivers it.
4
+ *
5
+ * @module
6
+ */
7
+ import type { CloseCode, ErrorCode } from "./protocol.js";
8
+ /** A connection is up and authenticated. */
9
+ export interface ConnectedEvent {
10
+ /** The event's name. */
11
+ type: "connected";
12
+ /** Topics the server restored for the durable session. */
13
+ resumed: string[];
14
+ }
15
+ /** The connection went down. */
16
+ export interface DisconnectedEvent {
17
+ /** The event's name. */
18
+ type: "disconnected";
19
+ /** The server's close code, or `null` when it sent none the client knows. */
20
+ code: CloseCode | null;
21
+ /** Whether the client will try to reconnect. */
22
+ reconnecting: boolean;
23
+ }
24
+ /** Messages on a topic were trimmed before the client got them. */
25
+ export interface TruncatedEvent {
26
+ /** The event's name. */
27
+ type: "truncated";
28
+ /** The topic. */
29
+ topic: string;
30
+ /** The oldest `seq` still available; delivery continues from here. */
31
+ firstAvailable: number;
32
+ }
33
+ /**
34
+ * A QoS 1 message ran out of retries. The server sends the topic nothing
35
+ * more until the client acknowledges something or subscribes again.
36
+ */
37
+ export interface StalledEvent {
38
+ /** The event's name. */
39
+ type: "stalled";
40
+ /** The topic. */
41
+ topic: string;
42
+ /** The message that was never acknowledged. */
43
+ seq: number;
44
+ }
45
+ /**
46
+ * The token expires soon. With password credentials the client refreshes
47
+ * it on its own; with a bare token the connection closes when it expires.
48
+ */
49
+ export interface AuthExpiringEvent {
50
+ /** The event's name. */
51
+ type: "authExpiring";
52
+ /** When it expires, in milliseconds since the Unix epoch. */
53
+ expiresAtMs: number;
54
+ }
55
+ /** The client got a new token and the connection carries on. */
56
+ export interface AuthRefreshedEvent {
57
+ /** The event's name. */
58
+ type: "authRefreshed";
59
+ }
60
+ /**
61
+ * The server ended a subscription because the user may no longer read the
62
+ * topic. Its `Subscription` ends and the client won't resubscribe.
63
+ */
64
+ export interface UnsubscribedEvent {
65
+ /** The event's name. */
66
+ type: "unsubscribed";
67
+ /** The topic. */
68
+ topic: string;
69
+ }
70
+ /** The server reported an error that answers no request, such as a failed QoS 0 publish. */
71
+ export interface ServerErrorEvent {
72
+ /** The event's name. */
73
+ type: "serverError";
74
+ /** What went wrong. */
75
+ code: ErrorCode;
76
+ /** What went wrong, for people. */
77
+ message: string;
78
+ }
79
+ /** Something that happened to the connection or a subscription. */
80
+ export type ClientEvent = ConnectedEvent | DisconnectedEvent | TruncatedEvent | StalledEvent | AuthExpiringEvent | AuthRefreshedEvent | UnsubscribedEvent | ServerErrorEvent;
81
+ /** A function called with every event. */
82
+ export type ClientEventListener = (event: ClientEvent) => void;
83
+ /**
84
+ * Calls every registered listener with each event. A listener that throws
85
+ * doesn't stop the others or the client: its error is rethrown from a
86
+ * microtask, where the runtime reports it as an uncaught error.
87
+ */
88
+ export declare class Emitter {
89
+ #private;
90
+ /**
91
+ * Registers a listener.
92
+ *
93
+ * @param listener - Called with every event from now on.
94
+ * @returns A function that removes the listener.
95
+ */
96
+ on(listener: ClientEventListener): () => void;
97
+ /**
98
+ * Removes a listener.
99
+ *
100
+ * @param listener - The listener passed to `on`.
101
+ */
102
+ off(listener: ClientEventListener): void;
103
+ /** Removes every listener. */
104
+ clear(): void;
105
+ /**
106
+ * Calls every listener with an event.
107
+ *
108
+ * @param event - The event.
109
+ */
110
+ emit(event: ClientEvent): void;
111
+ }
package/dist/events.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * What the client reports about its connection and subscriptions, and the
3
+ * listener registry that delivers it.
4
+ *
5
+ * @module
6
+ */
7
+ /**
8
+ * Calls every registered listener with each event. A listener that throws
9
+ * doesn't stop the others or the client: its error is rethrown from a
10
+ * microtask, where the runtime reports it as an uncaught error.
11
+ */
12
+ export class Emitter {
13
+ /** The registered listeners. */
14
+ #listeners = new Set();
15
+ /**
16
+ * Registers a listener.
17
+ *
18
+ * @param listener - Called with every event from now on.
19
+ * @returns A function that removes the listener.
20
+ */
21
+ on(listener) {
22
+ this.#listeners.add(listener);
23
+ return () => {
24
+ this.off(listener);
25
+ };
26
+ }
27
+ /**
28
+ * Removes a listener.
29
+ *
30
+ * @param listener - The listener passed to `on`.
31
+ */
32
+ off(listener) {
33
+ this.#listeners.delete(listener);
34
+ }
35
+ /** Removes every listener. */
36
+ clear() {
37
+ this.#listeners.clear();
38
+ }
39
+ /**
40
+ * Calls every listener with an event.
41
+ *
42
+ * @param event - The event.
43
+ */
44
+ emit(event) {
45
+ for (const listener of [...this.#listeners]) {
46
+ try {
47
+ listener(event);
48
+ }
49
+ catch (error) {
50
+ queueMicrotask(() => {
51
+ throw error;
52
+ });
53
+ }
54
+ }
55
+ }
56
+ }
57
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiGH;;;;GAIG;AACH,MAAM,OAAO,OAAO;IAClB,gCAAgC;IACvB,UAAU,GAAG,IAAI,GAAG,EAAuB,CAAC;IAErD;;;;;OAKG;IACH,EAAE,CAAC,QAA6B;QAC9B,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC9B,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACrB,CAAC,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,QAA6B;QAC/B,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC;IAED,8BAA8B;IAC9B,KAAK;QACH,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,KAAkB;QACrB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC5C,IAAI,CAAC;gBACH,QAAQ,CAAC,KAAK,CAAC,CAAC;YAClB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,cAAc,CAAC,GAAG,EAAE;oBAClB,MAAM,KAAK,CAAC;gBACd,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * What the client reports about its connection and subscriptions, and the\n * listener registry that delivers it.\n *\n * @module\n */\n\nimport type { CloseCode, ErrorCode } from \"./protocol.js\";\n\n/** A connection is up and authenticated. */\nexport interface ConnectedEvent {\n /** The event's name. */\n type: \"connected\";\n /** Topics the server restored for the durable session. */\n resumed: string[];\n}\n\n/** The connection went down. */\nexport interface DisconnectedEvent {\n /** The event's name. */\n type: \"disconnected\";\n /** The server's close code, or `null` when it sent none the client knows. */\n code: CloseCode | null;\n /** Whether the client will try to reconnect. */\n reconnecting: boolean;\n}\n\n/** Messages on a topic were trimmed before the client got them. */\nexport interface TruncatedEvent {\n /** The event's name. */\n type: \"truncated\";\n /** The topic. */\n topic: string;\n /** The oldest `seq` still available; delivery continues from here. */\n firstAvailable: number;\n}\n\n/**\n * A QoS 1 message ran out of retries. The server sends the topic nothing\n * more until the client acknowledges something or subscribes again.\n */\nexport interface StalledEvent {\n /** The event's name. */\n type: \"stalled\";\n /** The topic. */\n topic: string;\n /** The message that was never acknowledged. */\n seq: number;\n}\n\n/**\n * The token expires soon. With password credentials the client refreshes\n * it on its own; with a bare token the connection closes when it expires.\n */\nexport interface AuthExpiringEvent {\n /** The event's name. */\n type: \"authExpiring\";\n /** When it expires, in milliseconds since the Unix epoch. */\n expiresAtMs: number;\n}\n\n/** The client got a new token and the connection carries on. */\nexport interface AuthRefreshedEvent {\n /** The event's name. */\n type: \"authRefreshed\";\n}\n\n/**\n * The server ended a subscription because the user may no longer read the\n * topic. Its `Subscription` ends and the client won't resubscribe.\n */\nexport interface UnsubscribedEvent {\n /** The event's name. */\n type: \"unsubscribed\";\n /** The topic. */\n topic: string;\n}\n\n/** The server reported an error that answers no request, such as a failed QoS 0 publish. */\nexport interface ServerErrorEvent {\n /** The event's name. */\n type: \"serverError\";\n /** What went wrong. */\n code: ErrorCode;\n /** What went wrong, for people. */\n message: string;\n}\n\n/** Something that happened to the connection or a subscription. */\nexport type ClientEvent =\n | ConnectedEvent\n | DisconnectedEvent\n | TruncatedEvent\n | StalledEvent\n | AuthExpiringEvent\n | AuthRefreshedEvent\n | UnsubscribedEvent\n | ServerErrorEvent;\n\n/** A function called with every event. */\nexport type ClientEventListener = (event: ClientEvent) => void;\n\n/**\n * Calls every registered listener with each event. A listener that throws\n * doesn't stop the others or the client: its error is rethrown from a\n * microtask, where the runtime reports it as an uncaught error.\n */\nexport class Emitter {\n /** The registered listeners. */\n readonly #listeners = new Set<ClientEventListener>();\n\n /**\n * Registers a listener.\n *\n * @param listener - Called with every event from now on.\n * @returns A function that removes the listener.\n */\n on(listener: ClientEventListener): () => void {\n this.#listeners.add(listener);\n return () => {\n this.off(listener);\n };\n }\n\n /**\n * Removes a listener.\n *\n * @param listener - The listener passed to `on`.\n */\n off(listener: ClientEventListener): void {\n this.#listeners.delete(listener);\n }\n\n /** Removes every listener. */\n clear(): void {\n this.#listeners.clear();\n }\n\n /**\n * Calls every listener with an event.\n *\n * @param event - The event.\n */\n emit(event: ClientEvent): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener(event);\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n}\n"]}