cross-tab-worker-databus 0.10.0 → 0.20.6
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.
- package/CHANGELOG.md +222 -0
- package/README.md +1 -0
- package/README.zh.md +1 -0
- package/dist/centrifuge.js +1 -1
- package/dist/centrifuge.shared.worker.js +4 -2
- package/dist/centrifuge.shared.worker.js.map +2 -2
- package/dist/centrifuge.worker.js +4 -2
- package/dist/centrifuge.worker.js.map +2 -2
- package/dist/{chunk-ZOPNTR4E.js → chunk-LPS4XOK4.js} +177 -19
- package/dist/{chunk-ZOPNTR4E.js.map → chunk-LPS4XOK4.js.map} +2 -2
- package/dist/cjs/centrifuge.cjs +176 -18
- package/dist/cjs/centrifuge.cjs.map +2 -2
- package/dist/cjs/hooks.cjs +4 -1
- package/dist/cjs/hooks.cjs.map +2 -2
- package/dist/cjs/index.cjs +326 -67
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/cjs/vue.cjs +7 -1
- package/dist/cjs/vue.cjs.map +2 -2
- package/dist/core/data-bus.d.ts +35 -0
- package/dist/core/data-bus.d.ts.map +1 -1
- package/dist/core/publication.d.ts.map +1 -1
- package/dist/core/replay-persistence.d.ts.map +1 -1
- package/dist/core/trace.d.ts +11 -1
- package/dist/core/trace.d.ts.map +1 -1
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js +4 -1
- package/dist/hooks.js.map +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +151 -50
- package/dist/index.js.map +2 -2
- package/dist/vue.d.ts.map +1 -1
- package/dist/vue.js +7 -1
- package/dist/vue.js.map +2 -2
- package/dist/websocket.d.ts.map +1 -1
- package/docs/README.md +1 -0
- package/docs/api.md +11 -4
- package/docs/architecture.md +4 -0
- package/docs/capabilities.md +2 -2
- package/docs/configuration.md +21 -1
- package/docs/release-checklist.md +20 -0
- package/docs/roadmap.md +144 -2
- package/docs/zh/README.md +1 -0
- package/docs/zh/api.md +11 -4
- package/docs/zh/architecture.md +4 -0
- package/docs/zh/capabilities.md +2 -2
- package/docs/zh/configuration.md +21 -1
- package/docs/zh/release-checklist.md +20 -0
- package/docs/zh/roadmap.md +132 -2
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/core/replay-persistence.ts", "../src/websocket.ts"],
|
|
4
|
-
"sourcesContent": ["import type { DataBusMessage } from './types';\n\n/** Optional persistence backend for replay history. */\nexport interface DataBusReplayPersistence<TData = unknown> {\n load(): Promise<ReadonlyArray<DataBusMessage<TData>>>;\n append(message: DataBusMessage<TData>): Promise<void>;\n /** Remove all persisted replay history. */\n clear?(): Promise<void>;\n /** Remove persisted replay history for one exact topic. */\n clearTopic?(topic: string): Promise<void>;\n /** Remove persisted messages older than the given epoch-millisecond cutoff. */\n clearBefore?(timestamp: number): Promise<void>;\n}\n\nexport interface IndexedDbReplayPersistenceOptions {\n dbName?: string;\n maxPerTopic: number;\n}\n\n/** Create a browser IndexedDB-backed replay store. */\nexport function createIndexedDbReplayPersistence<TData = unknown>(\n options: IndexedDbReplayPersistenceOptions\n): DataBusReplayPersistence<TData> {\n const indexedDb = globalThis.indexedDB;\n if (!indexedDb) throw new Error('IndexedDB is unavailable in this environment.');\n const dbName = options.dbName ?? 'cross-tab-worker-databus';\n const storeName = 'replay';\n const maxPerTopic = options.maxPerTopic;\n if (!Number.isSafeInteger(maxPerTopic) || maxPerTopic <= 0) {\n throw new TypeError(`maxPerTopic must be a positive safe integer, got ${String(maxPerTopic)}.`);\n }\n let dbPromise: Promise<IDBDatabase> | null = null;\n const open = (): Promise<IDBDatabase> => {\n if (dbPromise) return dbPromise;\n dbPromise = new Promise((resolve, reject) => {\n const request = indexedDb.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'topic' });\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error('Failed to open replay database.'));\n });\n return dbPromise;\n };\n return {\n async load() {\n const db = await open();\n return new Promise((resolve, reject) => {\n const request = db.transaction(storeName, 'readonly').objectStore(storeName).getAll();\n request.onsuccess = () => resolve(request.result.flatMap(record => record.messages as DataBusMessage<TData>[]));\n request.onerror = () => reject(request.error ?? new Error('Failed to load replay history.'));\n });\n },\n async append(message) {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction(storeName, 'readwrite');\n const store = transaction.objectStore(storeName);\n const request = store.get(message.topic);\n request.onsuccess = () => {\n const messages = ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(message).slice(-maxPerTopic);\n store.put({ topic: message.topic, messages });\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to read replay history.'));\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error ?? new Error('Failed to persist replay history.'));\n });\n },\n async clear() {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction(storeName, 'readwrite');\n transaction.objectStore(storeName).clear();\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error ?? new Error('Failed to clear replay history.'));\n });\n },\n async clearTopic(topic) {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction(storeName, 'readwrite');\n transaction.objectStore(storeName).delete(topic);\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error ?? new Error('Failed to clear topic replay history.'));\n });\n },\n async clearBefore(timestamp) {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction(storeName, 'readwrite');\n const store = transaction.objectStore(storeName);\n const request = store.getAll();\n request.onsuccess = () => {\n for (const record of request.result as Array<{ topic: string; messages: DataBusMessage<TData>[] }>) {\n const messages = record.messages.filter(message => (message.timestamp ?? 0) >= timestamp);\n if (messages.length === 0) store.delete(record.topic);\n else if (messages.length !== record.messages.length) store.put({ topic: record.topic, messages });\n }\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to read replay history.'));\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error ?? new Error('Failed to prune replay history.'));\n });\n }\n };\n}\n", "/**\n * WebSocketTransport \u2014 a dependency-free transport over a plain WebSocket.\n *\n * Validates the `DataBusTransport` abstraction with a second, minimal backend:\n * any WebSocket server that speaks the tiny JSON protocol below can back the\n * same cross-tab clustering stack (owner dedup, sticky routes, EVENT fan-out)\n * that the Centrifuge backend uses.\n *\n * Wire protocol (JSON text frames):\n * - client \u2192 server: `{\"op\":\"subscribe\"|\"unsubscribe\"|\"publish\",\"topic\":...,\"data\":...}`\n * - server \u2192 client: `{\"topic\":...,\"data\":...}` for publications; anything\n * without a string `topic` field is ignored (forward-compatible).\n */\nimport { CrossTabDataBus } from './core/data-bus';\nimport { parseDataBusPublication } from './core/publication';\nimport type { CrossTabDataBusOptions } from './core/data-bus';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\n DataBusPublishOptions,\n DataBusMessage,\n MaybePromise,\n WorkerStatus\n} from './core/types';\n\n/** Minimal WebSocket surface used by the transport. Matches the browser\n * `WebSocket` subset the transport touches; injectable for tests and runtimes. */\nexport interface WebSocketLike {\n /** Current connection state; 1 (OPEN) means frames may be sent. */\n readonly readyState?: number;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n}\n\n/** Connection configuration for {@link WebSocketTransport}. */\nexport interface WebSocketDataBusConfig {\n /** WebSocket endpoint, e.g. `wss://example.test/ws`. */\n url: string;\n /** Subprotocol(s) passed to the WebSocket handshake. */\n protocols?: string | string[];\n /** Custom socket factory. Defaults to the global `WebSocket`; injectable\n * for tests and non-browser runtimes. */\n webSocketFactory?: (url: string, protocols?: string | string[]) => WebSocketLike;\n}\n\n/** Options for creating a fully-configured CrossTabDataBus with a WebSocket transport. */\nexport interface CreateWebSocketDataBusOptions<TData = unknown>\n extends Omit<\n CrossTabDataBusOptions<WebSocketDataBusConfig, TData>,\n 'autoStart' | 'clusterKey' | 'initialConfig' | 'transport'\n > {\n /** WebSocket connection configuration. */\n connection: WebSocketDataBusConfig;\n /** Cluster key for cross-tab coordination. Defaults to the connection URL. */\n clusterKey?: string;\n}\n\nconst WS_OPEN = 1;\n\n/** Transport that talks a minimal JSON protocol over a plain WebSocket.\n * Connection lifecycle maps directly to the DataBus status vocabulary:\n * open \u2192 `connected`, close \u2192 `disconnected`, error \u2192 `error` (which the\n * DataBus treats as its auto-recovery trigger). The transport holds no\n * reconnection logic of its own \u2014 reopening is the DataBus's job. */\nexport class WebSocketTransport<TData = unknown>\n implements DataBusTransport<WebSocketDataBusConfig, TData>\n{\n private socket: WebSocketLike | null = null;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. A factory failure is\n * reported through `onStatus('error')` so the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket) return;\n this.handlers = handlers;\n // The factory may live on the constructor connection (createWebSocketDataBus\n // path) or on the runtime config (direct transport use) \u2014 accept both.\n const factory = config.webSocketFactory ?? this.connection.webSocketFactory ?? defaultWebSocketFactory;\n const protocols = config.protocols ?? this.connection.protocols;\n let socket: WebSocketLike;\n try {\n socket = factory(config.url, protocols);\n } catch (error) {\n handlers.onStatus('error');\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\n // Re-assert every topic so a reopened socket (recovery path) restores\n // the server-side subscriptions without DataBus involvement.\n for (const topic of this.subscribedTopics) {\n this.sendFrame({ op: 'subscribe', topic });\n }\n handlers.onStatus('connected');\n };\n socket.onclose = () => handlers.onStatus('disconnected');\n socket.onerror = () => handlers.onStatus('error');\n socket.onmessage = event => this.handleMessage(event.data);\n this.socket = socket;\n }\n\n /** Idempotent: re-subscribing an active topic re-sends the frame but does\n * not duplicate the local tracking entry. */\n subscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.add(topic);\n this.sendFrame({ op: 'subscribe', topic });\n }\n\n /** Idempotent: unsubscribing an unknown topic is a no-op. */\n unsubscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.delete(topic);\n this.sendFrame({ op: 'unsubscribe', topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown, options?: DataBusPublishOptions): MaybePromise<void> {\n if (data instanceof ArrayBuffer) {\n this.sendBinaryFrame(topic, data, options?.messageId, options?.timestamp);\n return;\n }\n this.sendFrame({\n op: 'publish',\n topic,\n data,\n ...(options?.messageId === undefined ? {} : { messageId: options.messageId }),\n ...(options?.timestamp === undefined ? {} : { timestamp: options.timestamp })\n });\n }\n\n /** Close the socket and drop all state. Safe to call multiple times. */\n stop(): MaybePromise<void> {\n const socket = this.socket;\n this.socket = null;\n this.handlers = null;\n this.subscribedTopics.clear();\n socket?.close();\n }\n\n /** Send one JSON frame. Frames are dropped with an `onError` report when\n * the socket is not open \u2014 subscribe frames are re-sent on open, so the\n * only real loss is a publish during a disconnect window. */\n private sendFrame(payload: { op: string; topic: string; data?: unknown; messageId?: string; timestamp?: number }): void {\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error(`WebSocket is not open; dropped \"${payload.op}\" frame.`));\n return;\n }\n this.socket.send(JSON.stringify(payload));\n }\n\n private sendBinaryFrame(topic: string, data: ArrayBuffer, messageId?: string, timestamp?: number): void {\n if (messageId !== undefined || timestamp !== undefined) {\n // Binary frames retain their compact legacy shape; metadata is sent as a\n // JSON envelope so IDs are never silently lost.\n this.sendFrame({\n op: 'publish',\n topic,\n data: Array.from(new Uint8Array(data)),\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n });\n return;\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publish\" frame.'));\n return;\n }\n const topicBytes = new TextEncoder().encode(topic);\n if (topicBytes.length > 0xffff) {\n this.handlers?.onError(new Error('WebSocket topic is too long for a binary frame.'));\n return;\n }\n const frame = new Uint8Array(3 + topicBytes.length + data.byteLength);\n frame[0] = 0xc7;\n new DataView(frame.buffer).setUint16(1, topicBytes.length);\n frame.set(topicBytes, 3);\n frame.set(new Uint8Array(data), 3 + topicBytes.length);\n this.socket.send(frame.buffer);\n }\n\n /** Parse a server frame. Only objects carrying a string `topic` are\n * publications; malformed JSON and unknown shapes are ignored so a chatty\n * server cannot crash the message path. */\n private handleMessage(raw: unknown): void {\n let parsed: unknown;\n if (raw instanceof ArrayBuffer) {\n const bytes = new Uint8Array(raw);\n if (bytes[0] !== 0xc7 || bytes.length < 3) return;\n const topicLength = new DataView(raw).getUint16(1);\n if (bytes.length < 3 + topicLength) return;\n const topic = new TextDecoder().decode(bytes.subarray(3, 3 + topicLength));\n const data = bytes.slice(3 + topicLength).buffer;\n this.handlers?.onMessage({ topic, data: data as TData });\n return;\n }\n if (typeof raw !== 'string') return;\n try {\n parsed = JSON.parse(raw);\n } catch {\n this.handlers?.onError(new Error('WebSocket server sent a non-JSON frame.'));\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n const publication = parseDataBusPublication<TData>(parsed);\n if (publication) this.handlers?.onMessage(publication as DataBusMessage<TData>);\n }\n}\n\n/** Resolve the platform WebSocket, or null in runtimes without one (SSR/Node). */\nfunction defaultWebSocketFactory(url: string, protocols?: string | string[]): WebSocketLike {\n if (typeof WebSocket === 'undefined') {\n throw new Error('WebSocketTransport requires a WebSocket implementation.');\n }\n return new WebSocket(url, protocols) as unknown as WebSocketLike;\n}\n\n/** Create a CrossTabDataBus backed by a plain WebSocket transport.\n * Cross-tab clustering (owner dedup, sticky routes, failover) works identically\n * to the Centrifuge backend \u2014 only the transport I/O differs. */\nexport function createWebSocketDataBus<TData = unknown>(\n options: CreateWebSocketDataBusOptions<TData>\n): CrossTabDataBus<WebSocketDataBusConfig, TData> {\n const { clusterKey, connection, ...dataBusOptions } = options;\n return new CrossTabDataBus({\n ...dataBusOptions,\n autoStart: true,\n clusterKey: clusterKey ?? connection.url,\n initialConfig: connection,\n transport: new WebSocketTransport<TData>(connection)\n });\n}\n\n/** Re-export for convenience: the status type used by the transport. */\nexport type { WorkerStatus };\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAoBO,SAAS,iCACd,SACiC;AACjC,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,+CAA+C;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY;AAClB,QAAM,cAAc,QAAQ;AAC5B,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,GAAG;AAC1D,UAAM,IAAI,UAAU,oDAAoD,OAAO,WAAW,CAAC,GAAG;AAAA,EAChG;AACA,MAAI,YAAyC;AAC7C,QAAM,OAAO,MAA4B;AACvC,QAAI,UAAW,QAAO;AACtB,
|
|
4
|
+
"sourcesContent": ["import type { DataBusMessage } from './types';\n\n/** Optional persistence backend for replay history. */\nexport interface DataBusReplayPersistence<TData = unknown> {\n load(): Promise<ReadonlyArray<DataBusMessage<TData>>>;\n append(message: DataBusMessage<TData>): Promise<void>;\n /** Remove all persisted replay history. */\n clear?(): Promise<void>;\n /** Remove persisted replay history for one exact topic. */\n clearTopic?(topic: string): Promise<void>;\n /** Remove persisted messages older than the given epoch-millisecond cutoff. */\n clearBefore?(timestamp: number): Promise<void>;\n}\n\nexport interface IndexedDbReplayPersistenceOptions {\n dbName?: string;\n maxPerTopic: number;\n}\n\n/** Create a browser IndexedDB-backed replay store. */\nexport function createIndexedDbReplayPersistence<TData = unknown>(\n options: IndexedDbReplayPersistenceOptions\n): DataBusReplayPersistence<TData> {\n const indexedDb = globalThis.indexedDB;\n if (!indexedDb) throw new Error('IndexedDB is unavailable in this environment.');\n const dbName = options.dbName ?? 'cross-tab-worker-databus';\n const storeName = 'replay';\n const maxPerTopic = options.maxPerTopic;\n if (!Number.isSafeInteger(maxPerTopic) || maxPerTopic <= 0) {\n throw new TypeError(`maxPerTopic must be a positive safe integer, got ${String(maxPerTopic)}.`);\n }\n let dbPromise: Promise<IDBDatabase> | null = null;\n const invalidate = (db: IDBDatabase): void => {\n if (dbPromise) {\n void dbPromise.then(current => {\n if (current === db) {\n current.close();\n dbPromise = null;\n }\n }, () => undefined);\n }\n };\n // IndexedDB transactions are atomic, but a read-modify-write append can\n // still lose updates when callers start several appends concurrently.\n // Serialize all mutations per adapter instance while keeping reads free.\n let mutationQueue: Promise<void> = Promise.resolve();\n const serializeMutation = (mutation: () => Promise<void>): Promise<void> => {\n const next = mutationQueue.then(mutation, mutation);\n mutationQueue = next.catch(() => undefined);\n return next;\n };\n const open = (): Promise<IDBDatabase> => {\n if (dbPromise) return dbPromise;\n const pending = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDb.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'topic' });\n request.onsuccess = () => {\n const db = request.result;\n // A schema upgrade in another tab invalidates this connection. Close\n // it and clear the cached promise so the next operation reopens a\n // usable connection instead of repeatedly targeting a dead database.\n db.onversionchange = () => {\n db.close();\n if (dbPromise) dbPromise = null;\n };\n resolve(db);\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to open replay database.'));\n });\n dbPromise = pending;\n // Do not permanently cache a rejected open promise. IndexedDB can fail\n // transiently (quota, private-mode initialization, a closing connection,\n // or a browser shutdown); the next operation must be able to retry.\n void pending.catch(() => {\n if (dbPromise === pending) dbPromise = null;\n });\n return pending;\n };\n return {\n async load() {\n const db = await open();\n return new Promise((resolve, reject) => {\n let request: IDBRequest;\n try {\n request = db.transaction(storeName, 'readonly').objectStore(storeName).getAll();\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n request.onsuccess = () => resolve((request.result as Array<{ messages: DataBusMessage<TData>[] }>).flatMap(record => record.messages));\n request.onerror = () => {\n invalidate(db);\n reject(request.error ?? new Error('Failed to load replay history.'));\n };\n });\n },\n append(message) {\n return serializeMutation(async () => {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n const store = transaction.objectStore(storeName);\n const request = store.get(message.topic);\n request.onsuccess = () => {\n const messages = ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(message).slice(-maxPerTopic);\n store.put({ topic: message.topic, messages });\n };\n request.onerror = () => { invalidate(db); reject(request.error ?? new Error('Failed to read replay history.')); };\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(transaction.error ?? new Error('Failed to persist replay history.')); };\n });\n });\n },\n clear() {\n return serializeMutation(async () => {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n transaction.objectStore(storeName).clear();\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(transaction.error ?? new Error('Failed to clear replay history.')); };\n });\n });\n },\n clearTopic(topic) {\n return serializeMutation(async () => {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n transaction.objectStore(storeName).delete(topic);\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(transaction.error ?? new Error('Failed to clear topic replay history.')); };\n });\n });\n },\n clearBefore(timestamp) {\n return serializeMutation(async () => {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n const store = transaction.objectStore(storeName);\n const request = store.getAll();\n request.onsuccess = () => {\n for (const record of request.result as Array<{ topic: string; messages: DataBusMessage<TData>[] }>) {\n const messages = record.messages.filter(message => message.timestamp === undefined || message.timestamp >= timestamp);\n if (messages.length === 0) store.delete(record.topic);\n else if (messages.length !== record.messages.length) store.put({ topic: record.topic, messages });\n }\n };\n request.onerror = () => { invalidate(db); reject(request.error ?? new Error('Failed to read replay history.')); };\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(transaction.error ?? new Error('Failed to prune replay history.')); };\n });\n });\n }\n };\n}\n", "/**\n * WebSocketTransport \u2014 a dependency-free transport over a plain WebSocket.\n *\n * Validates the `DataBusTransport` abstraction with a second, minimal backend:\n * any WebSocket server that speaks the tiny JSON protocol below can back the\n * same cross-tab clustering stack (owner dedup, sticky routes, EVENT fan-out)\n * that the Centrifuge backend uses.\n *\n * Wire protocol (JSON text frames):\n * - client \u2192 server: `{\"op\":\"subscribe\"|\"unsubscribe\"|\"publish\",\"topic\":...,\"data\":...}`\n * - server \u2192 client: `{\"topic\":...,\"data\":...}` for publications; anything\n * without a string `topic` field is ignored (forward-compatible).\n */\nimport { CrossTabDataBus } from './core/data-bus';\nimport { parseDataBusPublication } from './core/publication';\nimport type { CrossTabDataBusOptions } from './core/data-bus';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\n DataBusPublishOptions,\n DataBusMessage,\n MaybePromise,\n WorkerStatus\n} from './core/types';\n\n/** Minimal WebSocket surface used by the transport. Matches the browser\n * `WebSocket` subset the transport touches; injectable for tests and runtimes. */\nexport interface WebSocketLike {\n /** Current connection state; 1 (OPEN) means frames may be sent. */\n readonly readyState?: number;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n}\n\n/** Connection configuration for {@link WebSocketTransport}. */\nexport interface WebSocketDataBusConfig {\n /** WebSocket endpoint, e.g. `wss://example.test/ws`. */\n url: string;\n /** Subprotocol(s) passed to the WebSocket handshake. */\n protocols?: string | string[];\n /** Custom socket factory. Defaults to the global `WebSocket`; injectable\n * for tests and non-browser runtimes. */\n webSocketFactory?: (url: string, protocols?: string | string[]) => WebSocketLike;\n}\n\n/** Options for creating a fully-configured CrossTabDataBus with a WebSocket transport. */\nexport interface CreateWebSocketDataBusOptions<TData = unknown>\n extends Omit<\n CrossTabDataBusOptions<WebSocketDataBusConfig, TData>,\n 'autoStart' | 'clusterKey' | 'initialConfig' | 'transport'\n > {\n /** WebSocket connection configuration. */\n connection: WebSocketDataBusConfig;\n /** Cluster key for cross-tab coordination. Defaults to the connection URL. */\n clusterKey?: string;\n}\n\nconst WS_OPEN = 1;\n\n/** Transport that talks a minimal JSON protocol over a plain WebSocket.\n * Connection lifecycle maps directly to the DataBus status vocabulary:\n * open \u2192 `connected`, close \u2192 `disconnected`, error \u2192 `error` (which the\n * DataBus treats as its auto-recovery trigger). The transport holds no\n * reconnection logic of its own \u2014 reopening is the DataBus's job. */\nexport class WebSocketTransport<TData = unknown>\n implements DataBusTransport<WebSocketDataBusConfig, TData>\n{\n private socket: WebSocketLike | null = null;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. A factory failure is\n * reported through `onStatus('error')` so the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket) return;\n this.handlers = handlers;\n // The factory may live on the constructor connection (createWebSocketDataBus\n // path) or on the runtime config (direct transport use) \u2014 accept both.\n const factory = config.webSocketFactory ?? this.connection.webSocketFactory ?? defaultWebSocketFactory;\n const protocols = config.protocols ?? this.connection.protocols;\n let socket: WebSocketLike;\n try {\n socket = factory(config.url, protocols);\n } catch (error) {\n handlers.onStatus('error');\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\n // Re-assert every topic so a reopened socket (recovery path) restores\n // the server-side subscriptions without DataBus involvement.\n for (const topic of this.subscribedTopics) {\n this.sendFrame({ op: 'subscribe', topic });\n }\n handlers.onStatus('connected');\n };\n socket.onclose = () => handlers.onStatus('disconnected');\n socket.onerror = () => handlers.onStatus('error');\n socket.onmessage = event => { void this.handleMessage(event.data); };\n this.socket = socket;\n }\n\n /** Idempotent: re-subscribing an active topic re-sends the frame but does\n * not duplicate the local tracking entry. */\n subscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.add(topic);\n this.sendFrame({ op: 'subscribe', topic });\n }\n\n /** Idempotent: unsubscribing an unknown topic is a no-op. */\n unsubscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.delete(topic);\n this.sendFrame({ op: 'unsubscribe', topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown, options?: DataBusPublishOptions): MaybePromise<void> {\n if (data instanceof ArrayBuffer) {\n this.sendBinaryFrame(topic, data, options?.messageId, options?.timestamp);\n return;\n }\n this.sendFrame({\n op: 'publish',\n topic,\n data,\n ...(options?.messageId === undefined ? {} : { messageId: options.messageId }),\n ...(options?.timestamp === undefined ? {} : { timestamp: options.timestamp })\n });\n }\n\n /** Close the socket and drop all state. Safe to call multiple times. */\n stop(): MaybePromise<void> {\n const socket = this.socket;\n this.socket = null;\n this.handlers = null;\n this.subscribedTopics.clear();\n socket?.close();\n }\n\n /** Send one JSON frame. Frames are dropped with an `onError` report when\n * the socket is not open \u2014 subscribe frames are re-sent on open, so the\n * only real loss is a publish during a disconnect window. */\n private sendFrame(payload: { op: string; topic: string; data?: unknown; messageId?: string; timestamp?: number }): void {\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error(`WebSocket is not open; dropped \"${payload.op}\" frame.`));\n return;\n }\n this.socket.send(JSON.stringify(payload));\n }\n\n private sendBinaryFrame(topic: string, data: ArrayBuffer, messageId?: string, timestamp?: number): void {\n if (messageId !== undefined || timestamp !== undefined) {\n // Binary frames retain their compact legacy shape; metadata is sent as a\n // JSON envelope so IDs are never silently lost.\n this.sendFrame({\n op: 'publish',\n topic,\n data: Array.from(new Uint8Array(data)),\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n });\n return;\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publish\" frame.'));\n return;\n }\n const topicBytes = new TextEncoder().encode(topic);\n if (topicBytes.length > 0xffff) {\n this.handlers?.onError(new Error('WebSocket topic is too long for a binary frame.'));\n return;\n }\n const frame = new Uint8Array(3 + topicBytes.length + data.byteLength);\n frame[0] = 0xc7;\n new DataView(frame.buffer).setUint16(1, topicBytes.length);\n frame.set(topicBytes, 3);\n frame.set(new Uint8Array(data), 3 + topicBytes.length);\n this.socket.send(frame.buffer);\n }\n\n /** Parse a server frame. Only objects carrying a string `topic` are\n * publications; malformed JSON and unknown shapes are ignored so a chatty\n * server cannot crash the message path. */\n private async handleMessage(raw: unknown): Promise<void> {\n // Browser WebSockets may deliver binary frames as Blob unless\n // `binaryType = 'arraybuffer'` is explicitly configured by the host.\n // Normalize Blob asynchronously and reuse the exact ArrayBuffer parser.\n if (typeof Blob !== 'undefined' && raw instanceof Blob) {\n try {\n await this.handleMessage(await raw.arrayBuffer());\n } catch (error) {\n this.handlers?.onError(error);\n }\n return;\n }\n let parsed: unknown;\n if (raw instanceof ArrayBuffer) {\n const bytes = new Uint8Array(raw);\n if (bytes[0] !== 0xc7 || bytes.length < 3) return;\n const topicLength = new DataView(raw).getUint16(1);\n if (bytes.length < 3 + topicLength) return;\n const topic = new TextDecoder().decode(bytes.subarray(3, 3 + topicLength));\n const data = bytes.slice(3 + topicLength).buffer;\n this.handlers?.onMessage({ topic, data: data as TData });\n return;\n }\n if (typeof raw !== 'string') return;\n try {\n parsed = JSON.parse(raw);\n } catch {\n this.handlers?.onError(new Error('WebSocket server sent a non-JSON frame.'));\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n const publication = parseDataBusPublication<TData>(parsed);\n if (publication) this.handlers?.onMessage(publication as DataBusMessage<TData>);\n }\n}\n\n/** Resolve the platform WebSocket, or null in runtimes without one (SSR/Node). */\nfunction defaultWebSocketFactory(url: string, protocols?: string | string[]): WebSocketLike {\n if (typeof WebSocket === 'undefined') {\n throw new Error('WebSocketTransport requires a WebSocket implementation.');\n }\n return new WebSocket(url, protocols) as unknown as WebSocketLike;\n}\n\n/** Create a CrossTabDataBus backed by a plain WebSocket transport.\n * Cross-tab clustering (owner dedup, sticky routes, failover) works identically\n * to the Centrifuge backend \u2014 only the transport I/O differs. */\nexport function createWebSocketDataBus<TData = unknown>(\n options: CreateWebSocketDataBusOptions<TData>\n): CrossTabDataBus<WebSocketDataBusConfig, TData> {\n const { clusterKey, connection, ...dataBusOptions } = options;\n return new CrossTabDataBus({\n ...dataBusOptions,\n autoStart: true,\n clusterKey: clusterKey ?? connection.url,\n initialConfig: connection,\n transport: new WebSocketTransport<TData>(connection)\n });\n}\n\n/** Re-export for convenience: the status type used by the transport. */\nexport type { WorkerStatus };\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAoBO,SAAS,iCACd,SACiC;AACjC,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,+CAA+C;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY;AAClB,QAAM,cAAc,QAAQ;AAC5B,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,GAAG;AAC1D,UAAM,IAAI,UAAU,oDAAoD,OAAO,WAAW,CAAC,GAAG;AAAA,EAChG;AACA,MAAI,YAAyC;AAC7C,QAAM,aAAa,CAAC,OAA0B;AAC5C,QAAI,WAAW;AACb,WAAK,UAAU,KAAK,aAAW;AAC7B,YAAI,YAAY,IAAI;AAClB,kBAAQ,MAAM;AACd,sBAAY;AAAA,QACd;AAAA,MACF,GAAG,MAAM,MAAS;AAAA,IACpB;AAAA,EAC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O,CAAC,CAAM,GACvD,GAAG,CAAC,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"vue.d.ts","sourceRoot":"","sources":["../src/vue.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAsD,KAAK,GAAG,EAAE,MAAM,KAAK,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjE,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,KAAK,EAC/C,MAAM,EAAE,MAAM,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,EAC7C,IAAI,GAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,OAAO,CAAC,CAAM,GACvD,GAAG,CAAC,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,CAmB7C;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,KAAK,EACpD,GAAG,EAAE,GAAG,CAAC,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,EAC7E,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,KAAK,IAAI,GAChD,IAAI,CAoBN;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,KAAK,EAC9C,GAAG,EAAE,GAAG,CAAC,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,GAC/C,GAAG,CAAC,YAAY,CAAC,CAUnB"}
|
package/dist/vue.js
CHANGED
|
@@ -3,6 +3,7 @@ import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from "vue";
|
|
|
3
3
|
function useCrossTabDataBus(create, deps = []) {
|
|
4
4
|
const bus = shallowRef(null);
|
|
5
5
|
let instance = null;
|
|
6
|
+
let lifecycleGeneration = 0;
|
|
6
7
|
const stop = async () => {
|
|
7
8
|
const current = instance;
|
|
8
9
|
instance = null;
|
|
@@ -10,7 +11,9 @@ function useCrossTabDataBus(create, deps = []) {
|
|
|
10
11
|
if (current) await current.stop();
|
|
11
12
|
};
|
|
12
13
|
const start = () => {
|
|
14
|
+
const generation = ++lifecycleGeneration;
|
|
13
15
|
void stop().then(() => {
|
|
16
|
+
if (generation !== lifecycleGeneration) return;
|
|
14
17
|
const next = create();
|
|
15
18
|
instance = next;
|
|
16
19
|
bus.value = next;
|
|
@@ -27,20 +30,23 @@ function useCrossTabDataBus(create, deps = []) {
|
|
|
27
30
|
}
|
|
28
31
|
function useCrossTabSubscription(bus, topic, handler) {
|
|
29
32
|
let currentBus = null;
|
|
33
|
+
let currentTopic = null;
|
|
30
34
|
let cleanup;
|
|
31
35
|
let latestHandler = handler;
|
|
32
36
|
const stop = () => {
|
|
33
37
|
cleanup?.();
|
|
34
38
|
cleanup = void 0;
|
|
35
39
|
currentBus = null;
|
|
40
|
+
currentTopic = null;
|
|
36
41
|
};
|
|
37
42
|
const sync = () => {
|
|
38
43
|
const nextBus = bus.value;
|
|
39
44
|
const nextTopic = typeof topic === "string" ? topic : topic.value;
|
|
40
|
-
if (nextBus === currentBus && cleanup) return;
|
|
45
|
+
if (nextBus === currentBus && currentTopic === nextTopic && cleanup) return;
|
|
41
46
|
stop();
|
|
42
47
|
if (!nextBus) return;
|
|
43
48
|
currentBus = nextBus;
|
|
49
|
+
currentTopic = nextTopic;
|
|
44
50
|
cleanup = nextBus.subscribe(nextTopic, (message) => latestHandler(message));
|
|
45
51
|
};
|
|
46
52
|
watch(bus, sync, { immediate: true });
|
package/dist/vue.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/vue.ts"],
|
|
4
|
-
"sourcesContent": ["/** Vue 3 composables adapter for cross-tab-worker-databus.\n * Vue is an optional peer dependency; this module is a separate entry point.\n */\nimport { onBeforeUnmount, onMounted, ref, shallowRef, watch, type Ref } from 'vue';\nimport type { CrossTabDataBus } from './core/data-bus';\nimport type { DataBusMessage, WorkerStatus } from './core/types';\n\nexport function useCrossTabDataBus<TConfig, TData>(\n create: () => CrossTabDataBus<TConfig, TData>,\n deps: ReadonlyArray<Ref<unknown> | (() => unknown)> = []\n): Ref<CrossTabDataBus<TConfig, TData> | null> {\n const bus = shallowRef<CrossTabDataBus<TConfig, TData> | null>(null);\n let instance: CrossTabDataBus<TConfig, TData> | null = null;\n const stop = async () => { const current = instance; instance = null; bus.value = null; if (current) await current.stop(); };\n const start = () => { void stop().then(() => { const next = create()
|
|
5
|
-
"mappings": ";AAGA,SAAS,iBAAiB,WAAW,KAAK,YAAY,aAAuB;AAItE,SAAS,mBACd,QACA,OAAsD,CAAC,GACV;AAC7C,QAAM,MAAM,WAAmD,IAAI;AACnE,MAAI,WAAmD;AACvD,QAAM,OAAO,YAAY;AAAE,UAAM,UAAU;AAAU,eAAW;AAAM,QAAI,QAAQ;AAAM,QAAI,QAAS,OAAM,QAAQ,KAAK;AAAA,EAAG;AAC3H,QAAM,QAAQ,MAAM;
|
|
4
|
+
"sourcesContent": ["/** Vue 3 composables adapter for cross-tab-worker-databus.\n * Vue is an optional peer dependency; this module is a separate entry point.\n */\nimport { onBeforeUnmount, onMounted, ref, shallowRef, watch, type Ref } from 'vue';\nimport type { CrossTabDataBus } from './core/data-bus';\nimport type { DataBusMessage, WorkerStatus } from './core/types';\n\nexport function useCrossTabDataBus<TConfig, TData>(\n create: () => CrossTabDataBus<TConfig, TData>,\n deps: ReadonlyArray<Ref<unknown> | (() => unknown)> = []\n): Ref<CrossTabDataBus<TConfig, TData> | null> {\n const bus = shallowRef<CrossTabDataBus<TConfig, TData> | null>(null);\n let instance: CrossTabDataBus<TConfig, TData> | null = null;\n let lifecycleGeneration = 0;\n const stop = async () => { const current = instance; instance = null; bus.value = null; if (current) await current.stop(); };\n const start = () => {\n const generation = ++lifecycleGeneration;\n void stop().then(() => {\n if (generation !== lifecycleGeneration) return;\n const next = create();\n instance = next;\n bus.value = next;\n void next.ready().catch(() => {});\n });\n };\n onMounted(start);\n onBeforeUnmount(() => { void stop(); });\n if (deps.length > 0) watch(deps, start);\n return bus as Ref<CrossTabDataBus<TConfig, TData> | null>;\n}\n\nexport function useCrossTabSubscription<TConfig, TData>(\n bus: Ref<CrossTabDataBus<TConfig, TData> | null>, topic: Ref<string> | string,\n handler: (message: DataBusMessage<TData>) => void\n): void {\n let currentBus: CrossTabDataBus<TConfig, TData> | null = null;\n let currentTopic: string | null = null;\n let cleanup: (() => void) | undefined;\n let latestHandler = handler;\n const stop = () => { cleanup?.(); cleanup = undefined; currentBus = null; currentTopic = null; };\n const sync = () => {\n const nextBus = bus.value;\n const nextTopic = typeof topic === 'string' ? topic : topic.value;\n if (nextBus === currentBus && currentTopic === nextTopic && cleanup) return;\n stop();\n if (!nextBus) return;\n currentBus = nextBus;\n currentTopic = nextTopic;\n cleanup = nextBus.subscribe(nextTopic, message => latestHandler(message));\n };\n watch(bus, sync, { immediate: true });\n if (typeof topic !== 'string') watch(topic, sync);\n watch(() => handler, value => { latestHandler = value; });\n onBeforeUnmount(stop);\n}\n\nexport function useCrossTabStatus<TConfig, TData>(\n bus: Ref<CrossTabDataBus<TConfig, TData> | null>\n): Ref<WorkerStatus> {\n const status = ref<WorkerStatus>('connecting');\n let cleanup: (() => void) | undefined;\n watch(bus, next => {\n cleanup?.(); cleanup = undefined;\n status.value = next?.getStatus() ?? 'connecting';\n if (next) cleanup = next.onStatus(value => { status.value = value; });\n }, { immediate: true });\n onBeforeUnmount(() => cleanup?.());\n return status;\n}\n"],
|
|
5
|
+
"mappings": ";AAGA,SAAS,iBAAiB,WAAW,KAAK,YAAY,aAAuB;AAItE,SAAS,mBACd,QACA,OAAsD,CAAC,GACV;AAC7C,QAAM,MAAM,WAAmD,IAAI;AACnE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1F,wEAAwE;IACxE,IAAI,IAAI,YAAY,CAAC,IAAI,CAAC;IAQ1B;;iEAE6D;IAC7D,OAAO,CAAC,SAAS;IAQjB,OAAO,CAAC,eAAe;IA8BvB;;+CAE2C;YAC7B,aAAa;CAkC5B;AAUD;;iEAEiE;AACjE,wBAAgB,sBAAsB,CAAC,KAAK,GAAG,OAAO,EACpD,OAAO,EAAE,6BAA6B,CAAC,KAAK,CAAC,GAC5C,eAAe,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAShD;AAED,wEAAwE;AACxE,YAAY,EAAE,YAAY,EAAE,CAAC"}
|
package/docs/README.md
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
| [Architecture](./architecture.md) | Worker cluster, routing, storage, migration, and degradation design |
|
|
12
12
|
| [Capabilities Matrix](./capabilities.md) | Implemented, not implemented, and planned capabilities matrix |
|
|
13
13
|
| [Roadmap](./roadmap.md) | Release-oriented priorities and verification checklist |
|
|
14
|
+
| [Release checklist](./release-checklist.md) | Local gates, tagging, publishing, and post-release verification |
|
|
14
15
|
| [../examples/demo](../examples/demo) | Runnable multi-tab browser demo |
|
|
15
16
|
| [../CHANGELOG.md](../CHANGELOG.md) | Version changelog |
|
|
16
17
|
|
package/docs/api.md
CHANGED
|
@@ -86,7 +86,10 @@ Registers a local subscription and returns a cleanup function.
|
|
|
86
86
|
- The current tab only leaves the topic after the last handler is released.
|
|
87
87
|
- Subscriptions are automatically queued when the transport is not yet ready.
|
|
88
88
|
- Wildcard subscriptions: a topic ending in `.*` (`chat.*`) matches any remainder, and `*` matches everything. The pattern is routed, owned, and transport-subscribed as a literal channel; publications tagged with a matching concrete topic (or with the pattern itself) are delivered to wildcard handlers. See `topicMatchesPattern` below.
|
|
89
|
-
- Replay (opt-in): construct the bus with `replay: { maxPerTopic }` and pass `{ replay: true | n }` as the third `subscribe()` argument. `maxPerTopic` must be a positive safe integer. The new handler immediately receives the buffered history (up to `n`, capped by `maxPerTopic`, default 100) with `message.replayed: true`, so late joiners do not miss earlier publications. Only dispatched publications are buffered (a topic with no local subscriber drops them as unowned); buffers are in-memory and cleared when the last handler for the topic unsubscribes. Wildcard subscriptions replay across every buffered topic matching the pattern. For reload/BFCache persistence, pass an optional `persistence` created by `createIndexedDbReplayPersistence({ maxPerTopic })`; persistence is asynchronous and failures are reported through `onError` without breaking live delivery.
|
|
89
|
+
- Replay (opt-in): construct the bus with `replay: { maxPerTopic }` and pass `{ replay: true | n }` as the third `subscribe()` argument. `maxPerTopic` must be a positive safe integer. The new handler immediately receives the buffered history (up to `n`, capped by `maxPerTopic`, default 100) with `message.replayed: true`, so late joiners do not miss earlier publications. Only dispatched publications are buffered (a topic with no local subscriber drops them as unowned); buffers are in-memory and cleared when the last handler for the topic unsubscribes. Wildcard subscriptions replay across every buffered topic matching the pattern. For reload/BFCache persistence, pass an optional `persistence` created by `createIndexedDbReplayPersistence({ maxPerTopic })`; persistence is asynchronous and failures are reported through `onError` without breaking live delivery. Set `retentionMs` to automatically prune durable history via `clearBefore` during hydration and after appends. Set `persistenceRetry: { maxAttempts, backoffMs }` to retry transient persistence failures; defaults preserve one-attempt behavior.
|
|
90
|
+
When tracing is enabled, retries emit `reliability` events with `operation: 'persistence_retry'`, a bounded `persistenceOperation`, and `attempt`.
|
|
91
|
+
|
|
92
|
+
The WebSocket transport accepts binary publications delivered as either `ArrayBuffer` or browser `Blob` frames.
|
|
90
93
|
- Persistent replay stores may also implement `clearTopic(topic)`; the bus calls it on final topic unsubscribe. A store may expose `clear()` for application-controlled retention cleanup; `stop()` deliberately preserves durable history for reload/BFCache recovery.
|
|
91
94
|
|
|
92
95
|
### `unsubscribe(topic, handler?)`
|
|
@@ -115,7 +118,7 @@ Published data must satisfy the serialization constraints of the underlying tran
|
|
|
115
118
|
|
|
116
119
|
When the owning Worker is a remote Tab and the publish control message cannot be posted (for example the BroadcastChannel fails to clone the payload), `publish()` reports the failure through `onError` instead of silently dropping it.
|
|
117
120
|
|
|
118
|
-
Incoming messages may include a caller/server supplied `messageId`. Enable bounded duplicate suppression with `dedup: { maxEntries, ttlMs }`; repeated IDs within the window are ignored. This is disabled by default and does not provide an exactly-once server guarantee.
|
|
121
|
+
Incoming messages may include a caller/server supplied `messageId`. Enable bounded duplicate suppression with `dedup: { maxEntries, ttlMs }`; repeated IDs within the window are ignored. This is disabled by default and does not provide an exactly-once server guarantee. Tests and hosts with a custom time source may provide `dedup.now`. A full `stop()` clears the remembered ID window; a later `start()` begins a fresh dedup session.
|
|
119
122
|
|
|
120
123
|
When supplied, `options.messageId` and `options.timestamp` are propagated through cross-tab routing, Worker boundaries, and supported transports. The server must echo or otherwise preserve them for inbound deduplication and replay retention.
|
|
121
124
|
|
|
@@ -139,7 +142,11 @@ Clears in-memory replay buffers and invokes the persistence adapter's optional `
|
|
|
139
142
|
|
|
140
143
|
`clearReplayTopic(topic)` applies the same cleanup to one exact topic. `getDedupStats()` returns bounded counters (`enabled`, `tracked`, `accepted`, `suppressed`), and `resetDedup()` clears remembered IDs and counters without changing configuration.
|
|
141
144
|
|
|
142
|
-
`clearReplayBefore(timestamp)` removes entries older than an epoch-millisecond cutoff from memory and from adapters that implement optional `clearBefore(timestamp)`. Incoming messages receive a bus timestamp when the transport does not provide one.
|
|
145
|
+
`clearReplayBefore(timestamp)` removes entries with an explicit producer timestamp older than an epoch-millisecond cutoff from memory and from adapters that implement optional `clearBefore(timestamp)`. Legacy messages without a producer timestamp are preserved for compatibility. Incoming messages receive a bus timestamp when the transport does not provide one; that bus timestamp is not treated as producer metadata for retention cleanup.
|
|
146
|
+
|
|
147
|
+
When automatic retention is enabled, repeated cleanup requests are coalesced while a persistence cleanup is in flight; the newest cutoff is applied next.
|
|
148
|
+
|
|
149
|
+
Set `replay.retentionSweepMs` to periodically apply the retention cutoff even when no new publications arrive. The sweep is active only while the bus is started and visible; it pauses during pagehide and stops permanently on `stop()`.
|
|
143
150
|
|
|
144
151
|
### `onStatus(handler)`
|
|
145
152
|
|
|
@@ -201,7 +208,7 @@ trace: {
|
|
|
201
208
|
}
|
|
202
209
|
```
|
|
203
210
|
|
|
204
|
-
Low-frequency event types include `lifecycle`, `status`, `subscription`, `coordination`, and `error`; high-frequency data is output as `message_metrics` per window, containing receive/dispatch counts, active topic count, and dispatch latency aggregates (`dispatchSamples`, `dispatchAvgMs`, `dispatchP50Ms`, `dispatchP95Ms`, `dispatchMaxMs`). All public events use a fixed structure and do not contain raw topics, message payloads, connection addresses, or error bodies. Errors thrown by the sink are isolated and do not interrupt message dispatch, but are output to `console.warn` to facilitate diagnosing configuration issues. The sink should ideally not throw — capture expected error conditions in the event data rather than raising exceptions.
|
|
211
|
+
Low-frequency event types include `lifecycle`, `status`, `subscription`, `coordination`, and `error`; high-frequency data is output as `message_metrics` per window, containing receive/dispatch counts, active topic count, and dispatch latency aggregates (`dispatchSamples`, `dispatchAvgMs`, `dispatchP50Ms`, `dispatchP95Ms`, `dispatchMaxMs`), and deduplication outcomes (`dedupAccepted`, `dedupSuppressed`). All public events use a fixed structure and do not contain raw topics, message payloads, connection addresses, or error bodies. Errors thrown by the sink are isolated and do not interrupt message dispatch, but are output to `console.warn` to facilitate diagnosing configuration issues. The sink should ideally not throw — capture expected error conditions in the event data rather than raising exceptions.
|
|
205
212
|
|
|
206
213
|
### `stop()`
|
|
207
214
|
|
package/docs/architecture.md
CHANGED
|
@@ -411,6 +411,10 @@ BroadcastChannel does not echo to its sender, so the owner receives no `EVENT` b
|
|
|
411
411
|
|
|
412
412
|
Publications are not written to localStorage. Message data and publication metadata only exist in the BroadcastChannel in-memory event and within the transport; batch writes only cover coordination metadata.
|
|
413
413
|
|
|
414
|
+
### Service Worker boundary
|
|
415
|
+
|
|
416
|
+
The SDK intentionally does not host a real-time transport in a Service Worker. Service Workers can be terminated between events, do not provide a durable foreground connection lifetime, and impose browser-specific restrictions around long-lived WebSockets. A future adapter would need an explicit connection owner, client wake-up protocol, reconnection policy, and durable handoff semantics; until those are standardized and covered by browser tests, Dedicated/Shared Worker transports remain the supported runtime models.
|
|
417
|
+
|
|
414
418
|
### Dispatch flow: three gates
|
|
415
419
|
|
|
416
420
|
Every publication from the transport goes through three checks before reaching the application handler:
|
package/docs/capabilities.md
CHANGED
|
@@ -22,7 +22,7 @@ Status Legend: `✅ Implemented` means the current version has code and test cov
|
|
|
22
22
|
| Degradation | Runs locally when localStorage or BroadcastChannel is unavailable | ✅ Implemented | Preserves the current Tab's connection and subscription capabilities |
|
|
23
23
|
| Centrifuge | Built-in Dedicated / Shared Worker transport | ✅ Implemented | Supports subscribe, unsubscribe, publish, connection status, and error reporting; `auto` degrades from SharedWorker → Dedicated Worker → main-thread WebSocket |
|
|
24
24
|
| Security Boundary | localStorage uses opaque keys derived from connection and Topic; BroadcastChannel coordination messages carry plaintext topic names | ✅ Implemented | Does not persist URLs, raw Topic names, credentials, or publication payloads. BroadcastChannel coordination messages are in-memory only and carry plaintext topic names — they are not persisted. |
|
|
25
|
-
| Diagnostics | Aggregates lifecycle events, throughput, delivery latency, recovery retries, route acknowledgments, and migrations | ✅ Implemented | Disabled by default; metrics are emitted every 5 seconds by default, with bounded reliability events for recovery and route coordination |
|
|
25
|
+
| Diagnostics | Aggregates lifecycle events, throughput, delivery latency, dedup outcomes, recovery retries, route acknowledgments, and migrations | ✅ Implemented | Disabled by default; metrics are emitted every 5 seconds by default, with bounded reliability events for recovery and route coordination |
|
|
26
26
|
| Performance | Batched writes of coordination metadata with backoff retry | ✅ Implemented | Heartbeat, route, and subscriber writes are merged and flushed in a microtask; failures use exponential backoff; `pagehide` / `stop()` flush synchronously |
|
|
27
27
|
| Performance | Optional ArrayBuffer Transferable transport | ✅ Implemented | With `transferable: true`, binary publish / receive bypasses structured clone copying; the object message API is unchanged |
|
|
28
28
|
| Message Semantics | exactly-once delivery | Not Implemented | Graceful handoff avoids overlap, but crash recovery and transport/server behavior still do not provide an exactly-once guarantee |
|
|
@@ -31,7 +31,7 @@ Status Legend: `✅ Implemented` means the current version has code and test cov
|
|
|
31
31
|
| Load Policy | Adaptive weighting by message rate, byte count, or CPU | Planned | Load is currently computed only from the number of owner Topics |
|
|
32
32
|
| Observability | Metrics/events for owner acknowledgments, migrations, and recovery attempts | ✅ Implemented | `DataBusReliabilityTraceEvent` reports bounded route ack/migration and transport recovery events; exact server-side ack remains transport-specific |
|
|
33
33
|
| Runtime Model | SharedWorker / Dedicated Worker transport | ✅ Implemented | `workerMode` supports `dedicated`, `shared`, and `auto`, defaulting to `dedicated` |
|
|
34
|
-
| Runtime Model | Service Worker transport | Not Implemented |
|
|
34
|
+
| Runtime Model | Service Worker transport | Not Implemented | Deliberately deferred; lifetime and long-lived connection constraints are documented in `docs/architecture.md` |
|
|
35
35
|
| Durable Messages | Persisting publications or publish commands across page close | Not Implemented | The SDK does not persist business payloads, nor does it replay publish commands after restoration |
|
|
36
36
|
|
|
37
37
|
## Acceptance Criteria
|
package/docs/configuration.md
CHANGED
|
@@ -46,7 +46,27 @@ const bus = new CrossTabDataBus({
|
|
|
46
46
|
| `metricsIntervalMs` | `number` | `5000` | Aggregation window; must be a finite value greater than 0 |
|
|
47
47
|
| `sink` | `(event) => void` | Required | Determined by the integrator: console, monitoring SDK, or other output |
|
|
48
48
|
|
|
49
|
-
`message_metrics` contains window duration, received count, dispatched count, active Topic count, and receive-to-dispatch latency sample count, average, P50, P95, and maximum. Latency is aggregated in 50ms buckets and never contains an individual message payload. Subscription events include their Topic so an integrator can correlate ownership changes. They are emitted only when the owner transport subscription set changes; idempotent `CONTROL` retries do not produce duplicate subscription events. Treat trace sinks as diagnostic surfaces: redact sensitive Topic conventions before writing to a console or external telemetry. Trace events do not include URLs, credentials, payloads, or error bodies. Errors thrown in the sink are isolated and will not interrupt message distribution, but will output to `console.warn` to help integrators discover diagnostic configuration issues.
|
|
49
|
+
`message_metrics` contains window duration, received count, dispatched count, active Topic count, and receive-to-dispatch latency sample count, average, P50, P95, and maximum, plus `dedupAccepted` and `dedupSuppressed` counters for the same window. Latency is aggregated in 50ms buckets and never contains an individual message payload. Persistence failures also emit a bounded `reliability` event with `operation: persistence_cleanup` before reaching the error handlers. `dedup.now` and `trace.now` can be injected for deterministic TTL, event-timestamp, and metrics-window tests. Subscription events include their Topic so an integrator can correlate ownership changes. They are emitted only when the owner transport subscription set changes; idempotent `CONTROL` retries do not produce duplicate subscription events. Treat trace sinks as diagnostic surfaces: redact sensitive Topic conventions before writing to a console or external telemetry. Trace events do not include URLs, credentials, payloads, or error bodies. Errors thrown in the sink are isolated and will not interrupt message distribution, but will output to `console.warn` to help integrators discover diagnostic configuration issues.
|
|
50
|
+
|
|
51
|
+
When `replay.retentionMs` is enabled, automatic durable cleanup is coalesced during bursts: an in-flight cleanup is reused and the newest cutoff is applied after it settles. This bounds IndexedDB cleanup work without changing the retention boundary.
|
|
52
|
+
|
|
53
|
+
`replay.retentionSweepMs` optionally schedules the same cleanup on a periodic interval. It is useful for quiet topics whose old durable records should still expire; it requires `retentionMs` and a persistence adapter with `clearBefore()`. The timer follows visibility and lifecycle transitions and is disabled by default.
|
|
54
|
+
|
|
55
|
+
`replay.persistenceRetry` optionally controls transient persistence recovery. `maxAttempts` is the total number of attempts (default `1`), and `backoffMs` is the initial delay before retry (default `50`). Delays grow exponentially and are capped; final failures retain the existing `onError` and reliability behavior.
|
|
56
|
+
|
|
57
|
+
When tracing is enabled, each retry before the final attempt emits a bounded `reliability` event with `operation: persistence_retry`, `persistenceOperation` (`load`, `append`, `clear`, `clearTopic`, or `clearBefore`), and the failed attempt number. No payload, URL, credential, or error body is included.
|
|
58
|
+
|
|
59
|
+
WebSocket binary frames may arrive as either `ArrayBuffer` or browser `Blob`; both use the same compact binary publication format. Blob conversion is asynchronous and conversion failures are reported through the transport error handler.
|
|
60
|
+
|
|
61
|
+
Retry waits are lifecycle-aware: `stop()` and pagehide suspension cancel pending retry attempts. A later `start()`/pageshow begins new work under a fresh lifecycle generation.
|
|
62
|
+
|
|
63
|
+
`dedup.sweepMs` optionally runs TTL cleanup while the bus is started and visible. It is disabled by default; on-message cleanup and `maxEntries` bounds remain in effect regardless.
|
|
64
|
+
|
|
65
|
+
The Vue adapter serializes bus replacement and ignores stale stop completions when reactive dependencies change rapidly, preserving the newest component lifecycle.
|
|
66
|
+
|
|
67
|
+
The React adapter applies the same generation guard across StrictMode and dependency-driven recreation, so stale effect cleanup cannot clear a newer bus.
|
|
68
|
+
|
|
69
|
+
IndexedDB replay persistence closes connections receiving `versionchange` and lazily reopens them for the next operation, which keeps multi-tab schema upgrades recoverable.
|
|
50
70
|
|
|
51
71
|
On `pagehide`, the aggregation timer stops and discards the incomplete window; on `pageshow`, it resumes with a new window. A permanent `stop()` clears the timer. Only diagnostics output is throttled; actual message reception and distribution are never rate-limited.
|
|
52
72
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Release checklist
|
|
2
|
+
|
|
3
|
+
Use this checklist for each pre-1.0 release. The repository does not publish from the assistant; run the final npm command manually after reviewing the packed artifact.
|
|
4
|
+
|
|
5
|
+
## Before tagging
|
|
6
|
+
|
|
7
|
+
1. Update `package.json`, `CHANGELOG.md`, and both roadmap files.
|
|
8
|
+
2. Run `pnpm check`, `pnpm lint`, `pnpm bench`, `pnpm test:e2e`, `pnpm bench:browser`, `pnpm verify:pack`, and `git diff --check`.
|
|
9
|
+
3. Confirm the package contains only intended files with `npm pack --dry-run --json`.
|
|
10
|
+
4. Commit, tag the exact version, and push `main --tags`.
|
|
11
|
+
|
|
12
|
+
## Publishing
|
|
13
|
+
|
|
14
|
+
Run `npm publish --access public` from the tagged checkout. A version already present on npm cannot be published again. Historical versions missing from npm must be rebuilt from their exact git tags and reviewed individually; never publish the current tree under an old version.
|
|
15
|
+
|
|
16
|
+
## After publishing
|
|
17
|
+
|
|
18
|
+
1. Verify the version appears in `npm view cross-tab-worker-databus versions --json`.
|
|
19
|
+
2. Install the published tarball or version in a clean consumer and import the root plus every public subpath.
|
|
20
|
+
3. Record the result in the release notes. Do not advance to `1.0.0` until the public API and protocol deprecation policy are explicitly frozen.
|
package/docs/roadmap.md
CHANGED
|
@@ -1,8 +1,150 @@
|
|
|
1
1
|
# Roadmap
|
|
2
2
|
|
|
3
|
-
0.6
|
|
3
|
+
0.20.6 is the current development line. The project is intentionally continuing through reliability-focused minor releases before a 1.0.0 stability freeze.
|
|
4
4
|
|
|
5
|
-
## 0.
|
|
5
|
+
## 0.20.6 delivered scope
|
|
6
|
+
|
|
7
|
+
- Added bilingual release checklists covering local validation, packed consumers, tagging, manual npm publication, and post-release verification.
|
|
8
|
+
- Documented immutable npm history and the requirement to rebuild missing historical versions from their exact git tags.
|
|
9
|
+
|
|
10
|
+
## 0.20.5 delivered scope
|
|
11
|
+
|
|
12
|
+
- Public-consumer freeze coverage now exercises root, hooks, Vue, and Centrifuge subpaths in both ESM and CommonJS builds.
|
|
13
|
+
- Shipped declaration files are checked for existence and key replay, deduplication, and publication metadata types.
|
|
14
|
+
|
|
15
|
+
## 0.20.4 delivered scope
|
|
16
|
+
|
|
17
|
+
- Added a real Chromium multi-tab soak scenario covering repeated fan-out, owner migration, BFCache round trips, reload recovery, and duplicate-free delivery.
|
|
18
|
+
- Browser lifecycle transitions are now exercised as one continuous session, catching timer and route cleanup regressions that isolated checks can miss.
|
|
19
|
+
|
|
20
|
+
## 0.20.3 delivered scope
|
|
21
|
+
|
|
22
|
+
- Added React lifecycle coverage for dynamic topic changes.
|
|
23
|
+
- Topic replacement verifies old subscriptions are removed before the new topic is delivered through WebSocket hook wiring.
|
|
24
|
+
|
|
25
|
+
## 0.20.2 delivered scope
|
|
26
|
+
|
|
27
|
+
- Added protocol recovery coverage proving valid WebSocket publications continue after malformed binary and text frames.
|
|
28
|
+
- Binary truncation, JSON parse failures, nested envelopes, and error isolation are exercised as one compatibility sequence.
|
|
29
|
+
|
|
30
|
+
## 0.20.1 delivered scope
|
|
31
|
+
|
|
32
|
+
- Added persistence mutation-sequence soak coverage spanning hydration, retry recovery, topic cleanup, subsequent append, and full cleanup.
|
|
33
|
+
- Serialized persistence operations remain usable after transient failures.
|
|
34
|
+
|
|
35
|
+
## 0.20.0 delivered scope
|
|
36
|
+
|
|
37
|
+
- Publication envelope compatibility is covered for legacy, nested, fallback-topic, primitive payload, metadata, and unknown-field frames.
|
|
38
|
+
- Empty or missing topics are rejected consistently while transport-supplied fallback channels remain supported.
|
|
39
|
+
|
|
40
|
+
## 0.19.9 delivered scope
|
|
41
|
+
|
|
42
|
+
- Added combined deduplication and replay/persistence regression coverage.
|
|
43
|
+
- Dedup-suppressed publications cannot pollute replay history, while TTL expiry permits the same message ID to be accepted again.
|
|
44
|
+
|
|
45
|
+
## 0.19.8 delivered scope
|
|
46
|
+
|
|
47
|
+
- IndexedDB replay adapters invalidate cached connections after transaction or request failures.
|
|
48
|
+
- Closed connections can recover through the existing persistence retry path without recreating the adapter.
|
|
49
|
+
|
|
50
|
+
## 0.19.7 delivered scope
|
|
51
|
+
|
|
52
|
+
- IndexedDB replay adapters discard rejected open promises so transient open failures can recover on the next operation.
|
|
53
|
+
- Recovery remains compatible with the existing cross-tab `versionchange` connection reset behavior.
|
|
54
|
+
|
|
55
|
+
## 0.19.6 delivered scope
|
|
56
|
+
|
|
57
|
+
- IndexedDB replay adapters recover from cross-tab `versionchange` events by reopening on the next operation.
|
|
58
|
+
- Stale database connections are closed instead of being reused after schema changes.
|
|
59
|
+
|
|
60
|
+
## 0.19.5 delivered scope
|
|
61
|
+
|
|
62
|
+
- React bus effects are generation-guarded across StrictMode and rapid dependency changes.
|
|
63
|
+
- Superseded asynchronous cleanup cannot overwrite the newest active bus.
|
|
64
|
+
|
|
65
|
+
## 0.19.4 delivered scope
|
|
66
|
+
|
|
67
|
+
- Vue bus recreation is generation-guarded across rapid reactive dependency changes.
|
|
68
|
+
- Stale asynchronous lifecycle completions cannot resurrect an obsolete bus instance.
|
|
69
|
+
|
|
70
|
+
## 0.19.3 delivered scope
|
|
71
|
+
|
|
72
|
+
- Added optional `dedup.sweepMs` to remove expired message IDs during quiet periods.
|
|
73
|
+
- Sweep timers follow DataBus lifecycle and remain disabled by default.
|
|
74
|
+
|
|
75
|
+
## 0.19.2 delivered scope
|
|
76
|
+
|
|
77
|
+
- Persistence retries are cancelled across `stop()` and pagehide suspension transitions.
|
|
78
|
+
- Cancelled retry waits do not trigger another adapter call or surface as persistence failures.
|
|
79
|
+
|
|
80
|
+
## 0.19.1 delivered scope
|
|
81
|
+
|
|
82
|
+
- WebSocket binary publication handling accepts browser `Blob` frames in addition to `ArrayBuffer` frames.
|
|
83
|
+
- Blob conversion failures remain isolated through the transport error callback.
|
|
84
|
+
|
|
85
|
+
## 0.19.0 delivered scope
|
|
86
|
+
|
|
87
|
+
- Persistence retries emit bounded, opt-in `persistence_retry` reliability events with the operation and attempt number.
|
|
88
|
+
- Diagnostics cover hydration, append, full/topic cleanup, and retention cleanup without exposing payloads or error bodies.
|
|
89
|
+
- Existing retry timing, default single-attempt behavior, adapter contracts, and final error handling remain compatible.
|
|
90
|
+
|
|
91
|
+
## 0.18.0 delivered scope
|
|
92
|
+
|
|
93
|
+
- Opt-in replay persistence retry policy with bounded attempts and exponential backoff.
|
|
94
|
+
- Append, hydration, manual cleanup, topic cleanup, and retention cleanup share one recovery path.
|
|
95
|
+
- Public retry option type is exported while persistence adapter contracts remain source-compatible.
|
|
96
|
+
|
|
97
|
+
## 0.17.0 delivered scope
|
|
98
|
+
|
|
99
|
+
- Optional periodic replay retention sweeps run without requiring a new publication.
|
|
100
|
+
- Sweep timers follow start/resume and pagehide/stop lifecycle boundaries.
|
|
101
|
+
- Fake-timer coverage protects cleanup scheduling, teardown, and invalid configuration behavior.
|
|
102
|
+
|
|
103
|
+
## 0.16.0 delivered scope
|
|
104
|
+
|
|
105
|
+
- Retention cleanup is coalesced during publication bursts and executes serialized mutations using the newest requested cutoff.
|
|
106
|
+
- WebSocket binary protocol boundaries now have regression coverage for truncated and invalid frames.
|
|
107
|
+
- Existing legacy replay, JSON metadata, and manual cleanup compatibility guarantees remain documented.
|
|
108
|
+
|
|
109
|
+
## 0.15.0 delivered scope
|
|
110
|
+
|
|
111
|
+
- Replay retention preserves legacy timestamp-less messages while pruning only explicitly timestamped records older than the cutoff.
|
|
112
|
+
- Trace timestamps accept an injectable `trace.now` clock, aligned with the existing dedup clock injection.
|
|
113
|
+
- Compatibility and lifecycle regression coverage protects replay cleanup, diagnostics, and adapter behavior.
|
|
114
|
+
|
|
115
|
+
## 0.14.0 delivered scope
|
|
116
|
+
|
|
117
|
+
- Vue subscription parity for reactive topic changes on a stable bus.
|
|
118
|
+
- Cross-page replay mutation ordering and lifecycle guarantees are documented and regression-tested.
|
|
119
|
+
|
|
120
|
+
## 0.13.0 delivered scope
|
|
121
|
+
|
|
122
|
+
- IndexedDB replay mutation serialization prevents concurrent append loss.
|
|
123
|
+
- Dedup state is reset on full stop/restart boundaries.
|
|
124
|
+
- Persistence failure and lifecycle regression coverage is included.
|
|
125
|
+
|
|
126
|
+
## 0.12.0 delivered scope
|
|
127
|
+
|
|
128
|
+
- Injectable deduplication TTL clock for deterministic lifecycle and expiry tests.
|
|
129
|
+
- Structured persistence cleanup diagnostics for append, hydration, unsubscribe, and retention failures.
|
|
130
|
+
- Strict-but-compatible publication metadata normalization (non-empty IDs and finite timestamps only).
|
|
131
|
+
- Protocol compatibility fixtures and expanded package-consumption coverage.
|
|
132
|
+
|
|
133
|
+
## 0.11.0 delivered scope
|
|
134
|
+
|
|
135
|
+
- Automatic durable replay retention through `replay.retentionMs` when the persistence adapter supports `clearBefore`.
|
|
136
|
+
- Deduplication accepted/suppressed counters in periodic trace metrics.
|
|
137
|
+
- Publication metadata compatibility coverage across WebSocket, Centrifuge, Worker boundaries, and browser E2E.
|
|
138
|
+
- Service Worker transport decision: remain deliberately unimplemented until a stable connection-lifetime contract exists across target browsers.
|
|
139
|
+
|
|
140
|
+
## 0.13.0 candidates
|
|
141
|
+
|
|
142
|
+
1. Freeze the public export surface and transport-neutral publication envelope.
|
|
143
|
+
2. Document at-least-once delivery and deduplication guarantees precisely.
|
|
144
|
+
3. Add long-running browser soak coverage for replay retention, reconnect, BFCache, and owner migration.
|
|
145
|
+
4. Publish a migration guide and deprecation policy for any pre-1.0 protocol aliases.
|
|
146
|
+
|
|
147
|
+
## Longer-term candidates
|
|
6
148
|
|
|
7
149
|
1. **Replay lifecycle and retention** — add explicit persistence cleanup (`clear`, `clearTopic`), make unsubscribe/replacement remove stale history, and surface persistence failures through trace and error handlers.
|
|
8
150
|
2. **Reliability diagnostics** — emit structured recovery/retry, owner-acknowledgment, and route-migration events with bounded metadata while keeping tracing opt-in.
|
package/docs/zh/README.md
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
| [架构说明](./architecture.md) | Worker 集群、路由、存储、迁移和降级设计 |
|
|
14
14
|
| [能力矩阵](./capabilities.md) | 已实现、未实现和计划待实现的能力矩阵 |
|
|
15
15
|
| [路线图](./roadmap.md) | 面向版本的优先级与验证清单 |
|
|
16
|
+
| [发布检查清单](./release-checklist.md) | 本地门禁、打 tag、发布和发布后验证 |
|
|
16
17
|
| [../..//examples/demo](../../examples/demo) | 可运行的多标签浏览器演示 |
|
|
17
18
|
| [../../CHANGELOG.md](../../CHANGELOG.md) | 版本变更记录 |
|
|
18
19
|
|
package/docs/zh/api.md
CHANGED
|
@@ -86,7 +86,10 @@ subscribe(
|
|
|
86
86
|
- 最后一个 handler 释放后,当前 Tab 才退出该 Topic。
|
|
87
87
|
- transport 尚未 ready 时订阅自动排队。
|
|
88
88
|
- 通配符订阅:以 `.*` 结尾的 Topic(如 `chat.*`)匹配任意后缀,`*` 匹配全部。pattern 以字面量参与路由、归属与传输订阅;携带匹配的具体 topic(或 pattern 本身)的发布都会投递给通配 handler。匹配规则见下方 `topicMatchesPattern`。
|
|
89
|
-
- 重放(可选):构造 bus 时传 `replay: { maxPerTopic }` 开启缓冲,`maxPerTopic` 必须是正安全整数;`subscribe()` 第三个参数传 `{ replay: true | n }` 后,新 handler 会立即收到缓冲历史(最多 `n` 条,受 `maxPerTopic` 上限约束,默认 100),消息带 `message.replayed: true` 标记——晚加入的 handler 不会错过更早的发布。只有被分发过的消息才入缓冲(无本地订阅者的 topic 会被 owner 丢弃);缓冲仅存内存,该 topic 最后一个 handler 退订时清空。通配订阅会对所有匹配 pattern 的已缓冲 topic 做回放。需要跨 reload/BFCache 持久化时,可传入 `createIndexedDbReplayPersistence({ maxPerTopic })` 创建的 `persistence`;持久化为异步操作,失败会通过 `onError`
|
|
89
|
+
- 重放(可选):构造 bus 时传 `replay: { maxPerTopic }` 开启缓冲,`maxPerTopic` 必须是正安全整数;`subscribe()` 第三个参数传 `{ replay: true | n }` 后,新 handler 会立即收到缓冲历史(最多 `n` 条,受 `maxPerTopic` 上限约束,默认 100),消息带 `message.replayed: true` 标记——晚加入的 handler 不会错过更早的发布。只有被分发过的消息才入缓冲(无本地订阅者的 topic 会被 owner 丢弃);缓冲仅存内存,该 topic 最后一个 handler 退订时清空。通配订阅会对所有匹配 pattern 的已缓冲 topic 做回放。需要跨 reload/BFCache 持久化时,可传入 `createIndexedDbReplayPersistence({ maxPerTopic })` 创建的 `persistence`;持久化为异步操作,失败会通过 `onError` 报告,不影响实时投递。设置 `retentionMs` 后,如果 adapter 支持 `clearBefore`,会在 hydrate 和追加后自动清理过期历史。设置 `persistenceRetry: { maxAttempts, backoffMs }` 可重试瞬时持久化失败;默认仍保持单次尝试。
|
|
90
|
+
启用 trace 后,重试会发出 `reliability` 事件,包含 `operation: 'persistence_retry'`、有界的 `persistenceOperation` 和 `attempt`。
|
|
91
|
+
|
|
92
|
+
WebSocket transport 支持以 `ArrayBuffer` 或浏览器 `Blob` 帧接收二进制 publication。
|
|
90
93
|
- 持久化 replay store 还可实现 `clearTopic(topic)`;bus 会在最后一个 handler 退订时调用。应用可自行保留 `clear()` 做全量留存清理;`stop()` 会保留 durable history,以支持 reload/BFCache 恢复。
|
|
91
94
|
|
|
92
95
|
### `unsubscribe(topic, handler?)`
|
|
@@ -135,9 +138,13 @@ clearReplay(): Promise<void>
|
|
|
135
138
|
|
|
136
139
|
清空内存 replay 缓冲,并调用持久化适配器可选的 `clear()`。适合留存策略、退出登录或租户切换;普通 `stop()` 仍会保留 durable history。
|
|
137
140
|
|
|
138
|
-
`clearReplayTopic(topic)` 只清理一个精确 topic。`getDedupStats()` 返回 `enabled`、`tracked`、`accepted`、`suppressed` 四项有界统计;`resetDedup()` 清除已记忆 ID 和计数,不改变 dedup
|
|
141
|
+
`clearReplayTopic(topic)` 只清理一个精确 topic。`getDedupStats()` 返回 `enabled`、`tracked`、`accepted`、`suppressed` 四项有界统计;`resetDedup()` 清除已记忆 ID 和计数,不改变 dedup 配置。为测试或非墙上时钟宿主,可额外提供 `dedup.now`。完整 `stop()` 会清空已记忆的 ID 窗口,之后 `start()` 会开启新的 dedup 会话。
|
|
142
|
+
|
|
143
|
+
`clearReplayBefore(timestamp)` 按毫秒时间戳清理带显式 producer timestamp 且早于 cutoff 的记录;实现可选 `clearBefore()` 的持久化适配器会同步执行该清理。没有 producer timestamp 的 legacy 消息会为兼容性保留。transport 未提供时间戳时,系统仍会补充 bus timestamp,但该时间戳不会被当作 producer metadata 用于 retention 清理。
|
|
144
|
+
|
|
145
|
+
启用自动 retention 时,如果持久化清理正在进行,后续清理请求会合并,完成后再应用最新 cutoff。
|
|
139
146
|
|
|
140
|
-
`
|
|
147
|
+
设置 `replay.retentionSweepMs` 后,即使没有新 publication 也会周期性应用 retention cutoff。sweep 只在 bus started 且页面可见时运行;pagehide 时暂停,`stop()` 后永久停止。
|
|
141
148
|
|
|
142
149
|
### `onStatus(handler)`
|
|
143
150
|
|
|
@@ -199,7 +206,7 @@ trace: {
|
|
|
199
206
|
}
|
|
200
207
|
```
|
|
201
208
|
|
|
202
|
-
低频事件类型包括 `lifecycle`、`status`、`subscription`、`coordination` 和 `error`;高频数据按窗口输出 `message_metrics`,包含接收/分发计数、活跃 Topic 数量和分发延迟聚合(`dispatchSamples`、`dispatchAvgMs`、`dispatchP50Ms`、`dispatchP95Ms`、`dispatchMaxMs`)。所有公开事件都使用固定结构,不包含原始 Topic、消息 payload、连接地址或错误正文。sink 抛错会被隔离,不会中断消息分发,但会向 `console.warn` 输出错误,便于定位诊断配置问题。sink 应尽量避免抛出异常——预期中的错误条件应通过事件数据表达,而不是通过异常上报。
|
|
209
|
+
低频事件类型包括 `lifecycle`、`status`、`subscription`、`coordination` 和 `error`;高频数据按窗口输出 `message_metrics`,包含接收/分发计数、活跃 Topic 数量和分发延迟聚合(`dispatchSamples`、`dispatchAvgMs`、`dispatchP50Ms`、`dispatchP95Ms`、`dispatchMaxMs`),以及去重结果(`dedupAccepted`、`dedupSuppressed`)。所有公开事件都使用固定结构,不包含原始 Topic、消息 payload、连接地址或错误正文。sink 抛错会被隔离,不会中断消息分发,但会向 `console.warn` 输出错误,便于定位诊断配置问题。sink 应尽量避免抛出异常——预期中的错误条件应通过事件数据表达,而不是通过异常上报。
|
|
203
210
|
|
|
204
211
|
### `stop()`
|
|
205
212
|
|
package/docs/zh/architecture.md
CHANGED
|
@@ -414,6 +414,10 @@ BroadcastChannel 不会把消息回传给发送者,因此 owner 收不到自
|
|
|
414
414
|
|
|
415
415
|
publication 不写入 localStorage。消息数据与 publication 元数据只存在于 BroadcastChannel 内存事件和 transport 内;批量写入只覆盖协调元数据。
|
|
416
416
|
|
|
417
|
+
### Service Worker 边界
|
|
418
|
+
|
|
419
|
+
SDK 当前刻意不在 Service Worker 中承载实时 transport。Service Worker 可能在事件之间被浏览器终止,不能提供持久的前台连接生命周期,而且各浏览器对长连接 WebSocket 的限制并不一致。未来若实现 adapter,必须先定义明确的连接 owner、客户端唤醒协议、重连策略和持久化交接语义;在这些条件标准化并有真实浏览器测试前,Dedicated/Shared Worker 仍是受支持的运行模型。
|
|
420
|
+
|
|
417
421
|
### 分发流程:三道关卡
|
|
418
422
|
|
|
419
423
|
每条来自 transport 的 publication 在到达应用 handler 之前经过三道关卡:
|
package/docs/zh/capabilities.md
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
| 降级 | localStorage 或 BroadcastChannel 不可用时本地运行 | ✅ 已实现 | 保留当前 Tab 的连接和订阅能力 |
|
|
23
23
|
| Centrifuge | 内置 Dedicated / Shared Worker transport | ✅ 已实现 | 支持 subscribe、unsubscribe、publish、连接状态和错误上报;`auto` 从 SharedWorker → Dedicated Worker → 主线程 WebSocket 降级 |
|
|
24
24
|
| 安全边界 | localStorage 使用连接和 Topic 派生不透明 key;BroadcastChannel 协调消息以明文传输 Topic 名称 | ✅ 已实现 | 不持久化 URL、原始 Topic 名称、凭证或 publication payload。BroadcastChannel 协调消息仅存在于内存中,以明文传输 Topic 名称——不会被持久化。 |
|
|
25
|
-
| 诊断 |
|
|
25
|
+
| 诊断 | 聚合生命周期、吞吐量、分发延迟、去重结果、恢复重试、路由确认和迁移 | ✅ 已实现 | 默认关闭;默认每 5 秒输出指标,并以有界 reliability 事件记录恢复和路由协调 |
|
|
26
26
|
| 性能 | 协调元数据批量写入 + 退避重试 | ✅ 已实现 | 心跳、路由和 subscriber 写入合并后在微任务中 flush;失败时指数退避;`pagehide` / `stop()` 同步 flush |
|
|
27
27
|
| 性能 | 可选 ArrayBuffer Transferable 传输 | ✅ 已实现 | 开启 `transferable: true` 后,二进制 publish/receive 跳过 structured clone 复制;对象消息 API 不变 |
|
|
28
28
|
| 消息语义 | exactly-once 投递 | 未实现 | 正常交接会避免重叠,但异常恢复和 transport/服务端行为仍不提供 exactly-once 保证 |
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
| 负载策略 | 按消息速率、字节数或 CPU 自适应加权 | 规划中 | 当前负载仅按 owner Topic 数量计算 |
|
|
32
32
|
| 可观测性 | owner 确认、迁移和恢复尝试的指标/事件 | ✅ 已实现 | `DataBusReliabilityTraceEvent` 记录有界的 route ack/migration 与 transport recovery;服务端最终确认仍由 transport 决定 |
|
|
33
33
|
| 运行时模型 | SharedWorker / Dedicated Worker transport | ✅ 已实现 | `workerMode` 支持 `dedicated`、`shared` 和 `auto`,默认 `dedicated` |
|
|
34
|
-
| 运行时模型 | Service Worker transport | 未实现 |
|
|
34
|
+
| 运行时模型 | Service Worker transport | 未实现 | 刻意延后;生命周期与长连接约束见 `docs/zh/architecture.md` |
|
|
35
35
|
| 持久消息 | 跨页面关闭持久化 publication 或发布命令 | 未实现 | SDK 不持久化业务 payload,也不在恢复后重放发布命令 |
|
|
36
36
|
|
|
37
37
|
## 验收标准
|