react-websocket 4.22.1 → 4.22.3
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/dist/ag-ui.cjs +8 -9
- package/dist/ag-ui.cjs.map +1 -1
- package/dist/ag-ui.d.cts +3 -8
- package/dist/ag-ui.d.ts +0 -2
- package/dist/ag-ui.js +8 -9
- package/dist/ag-ui.js.map +1 -1
- package/dist/chaos.cjs +60 -13
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts +1 -2
- package/dist/chaos.d.ts +1 -2
- package/dist/chaos.js +60 -13
- package/dist/chaos.js.map +1 -1
- package/dist/core.cjs +93 -65
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +4 -25
- package/dist/core.d.ts +4 -25
- package/dist/core.js +93 -65
- package/dist/core.js.map +1 -1
- package/dist/devtools.cjs +1 -2
- package/dist/devtools.d.cts +0 -2
- package/dist/devtools.d.ts +0 -2
- package/dist/devtools.js +1 -2
- package/dist/index.cjs +1 -2
- package/dist/index.d.cts +4 -31
- package/dist/index.d.ts +3 -24
- package/dist/index.development.cjs +1 -2
- package/dist/index.development.js +1 -2
- package/dist/index.js +1 -2
- package/dist/outbox.cjs +15 -10
- package/dist/outbox.cjs.map +1 -1
- package/dist/outbox.d.cts +1 -3
- package/dist/outbox.d.ts +0 -2
- package/dist/outbox.js +15 -10
- package/dist/outbox.js.map +1 -1
- package/dist/replay.cjs +13 -9
- package/dist/replay.cjs.map +1 -1
- package/dist/replay.d.cts +8 -4
- package/dist/replay.d.ts +8 -4
- package/dist/replay.js +13 -9
- package/dist/replay.js.map +1 -1
- package/dist/tabs.cjs +12 -16
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs.d.cts +0 -2
- package/dist/tabs.d.ts +0 -2
- package/dist/tabs.js +12 -16
- package/dist/tabs.js.map +1 -1
- package/dist/timeline.cjs +4 -3
- package/dist/timeline.cjs.map +1 -1
- package/dist/timeline.d.cts +3 -7
- package/dist/timeline.d.ts +2 -4
- package/dist/timeline.js +4 -3
- package/dist/timeline.js.map +1 -1
- package/dist/{types-paLT8yQF.d.cts → types-DyZm2F7B.d.cts} +4 -5
- package/dist/webtransport.cjs +13 -12
- package/dist/webtransport.cjs.map +1 -1
- package/dist/webtransport.d.cts +0 -2
- package/dist/webtransport.d.ts +0 -2
- package/dist/webtransport.js +13 -12
- package/dist/webtransport.js.map +1 -1
- package/package.json +9 -9
package/dist/tabs.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabs.cjs","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n let hiding = false;\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n agents.set(key, {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n });\n void navigator.locks.request(key, () => {\n if (!agents.has(key)) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again.\n #leave = () => {\n if (this.#state >= CLOSING) return; // `close()` told the leader already\n this.#post({ t: 'disconnect', id: this.#id });\n this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n if (!hiding) {\n hiding = true;\n addEventListener('pagehide', onPageHide);\n }\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";;AAyDA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAYf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,IAAI,MAAM;AAGV,MAAM,SAAS,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCtB,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,SAAS,QAAQ,UAAU;CAEjC,MAAM,yBAAS,IAAI,IAA6D;CAEhF,MAAM,QAAQ,SAAkB;EAC9B,IAAI,CAAC,QAAQ,QAAQ,OAAO,SAAS,UAAU,OAAO;EACtD,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,QAAQ;GACN,OAAO;EACT;CACF;;CAGA,MAAM,WACJ,WACA,YACG;EACH,IAAI,CAAC,aAAa,YAAY,QAAQ,OAAO,KAAA;EAC7C,IAAI;GACF,OAAO,UAAU,OAAO,KAAK,KAAA;EAC/B,QAAQ;GACN;EACF;CACF;CAIA,MAAM,uBAAO,IAAI,IAAgB;C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AI,MAAM,MAAM,CAAC;EACtC;EAEA,SAAS,MAAe;GACtB,IAAI,KAAK,WAAW,MAAM;GAC1B,IAAI,gBAAgB,eAAe,KAAK,eAAe,QAAQ,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC;GACrF,KAAK,cAAc,IAAI,aAAa,WAAW,EAAE,KAAK,CAAC,CAAC;EAC1D;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,UAAU,MAAM;GACrB,KAAK,OAAO,KAAK,MAAM;GACvB,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"tabs.cjs","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n const self = {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n };\n agents.set(key, self);\n void navigator.locks.request(key, () => {\n // Stopped by `dispose()`, even if the URL has a new agent in this tab since.\n if (agents.get(key) !== self) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again. After `close()`, it ends by itself.\n #leave = () => {\n if (this.#state < CLOSING) this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n // While any socket is live; adding it again does nothing.\n addEventListener('pagehide', onPageHide);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n // Not through `close()`: tell the leader, which may count this socket still, such as one\n // it heard from only after the shared socket closed.\n if (this.#state < CLOSING) this.#post({ t: 'disconnect', id: this.#id });\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n if (!live.size) removeEventListener('pagehide', onPageHide);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";;AAyDA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAYf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,IAAI,MAAM;AAGV,MAAM,SAAS,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCtB,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,SAAS,QAAQ,UAAU;CAEjC,MAAM,yBAAS,IAAI,IAA6D;CAEhF,MAAM,QAAQ,SAAkB;EAC9B,IAAI,CAAC,QAAQ,QAAQ,OAAO,SAAS,UAAU,OAAO;EACtD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;KAAW,IAAI,KAAK;IAAI,CAAC;SACpE,KAAK,KAAK,MAAM,IAAI,KAAK;GAChC;EACF;EAEA,MAAM,UAAkB;GACtB,KAAK,SAAS;GACd,KAAK,WAAW;GAChB,KAAK,cAAc,IAAI,MAAM,MAAM,CAAC;EACtC;EAEA,SAAS,MAAe;GACtB,IAAI,KAAK,WAAW,MAAM;GAC1B,IAAI,gBAAgB,eAAe,KAAK,eAAe,QAAQ,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC;GACrF,KAAK,cAAc,IAAI,aAAa,WAAW,EAAE,KAAK,CAAC,CAAC;EAC1D;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAG5B,IAAI,KAAK,SAAS,SAAS,KAAK,MAAM;IAAE,GAAG;IAAc,IAAI,KAAK;GAAI,CAAC;GACvE,KAAK,SAAS;GACd,KAAK,UAAU,MAAM;GACrB,KAAK,OAAO,KAAK,MAAM;GACvB,IAAI,CAAC,KAAK,MAAM,oBAAoB,YAAY,UAAU;GAC1D,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/dist/tabs.d.cts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/tabs.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With
|
|
4
3
|
* `json`, only messages that parse are passed to these, and one that throws counts as
|
|
@@ -84,5 +83,4 @@ export interface TabsWebSocket {
|
|
|
84
83
|
* ```
|
|
85
84
|
*/
|
|
86
85
|
export declare function createTabsWebSocket(options?: TabsWebSocketOptions): TabsWebSocket;
|
|
87
|
-
//#endregion
|
|
88
86
|
//# sourceMappingURL=tabs.d.cts.map
|
package/dist/tabs.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/tabs.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With
|
|
4
3
|
* `json`, only messages that parse are passed to these, and one that throws counts as
|
|
@@ -84,5 +83,4 @@ export interface TabsWebSocket {
|
|
|
84
83
|
* ```
|
|
85
84
|
*/
|
|
86
85
|
export declare function createTabsWebSocket(options?: TabsWebSocketOptions): TabsWebSocket;
|
|
87
|
-
//#endregion
|
|
88
86
|
//# sourceMappingURL=tabs.d.ts.map
|
package/dist/tabs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/tabs.ts
|
|
2
2
|
const CONNECTING = 0;
|
|
3
3
|
const OPEN = 1;
|
|
4
4
|
const CLOSING = 2;
|
|
@@ -66,7 +66,6 @@ function createTabsWebSocket(options = {}) {
|
|
|
66
66
|
}
|
|
67
67
|
};
|
|
68
68
|
const live = /* @__PURE__ */ new Set();
|
|
69
|
-
let hiding = false;
|
|
70
69
|
const onPageHide = () => {
|
|
71
70
|
for (const leave of [...live]) leave();
|
|
72
71
|
};
|
|
@@ -174,7 +173,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
174
173
|
}
|
|
175
174
|
}
|
|
176
175
|
}
|
|
177
|
-
|
|
176
|
+
const self = {
|
|
178
177
|
channel,
|
|
179
178
|
stop() {
|
|
180
179
|
clearTimeout(lingerTimer);
|
|
@@ -185,9 +184,10 @@ function createTabsWebSocket(options = {}) {
|
|
|
185
184
|
}
|
|
186
185
|
release?.();
|
|
187
186
|
}
|
|
188
|
-
}
|
|
187
|
+
};
|
|
188
|
+
agents.set(key, self);
|
|
189
189
|
navigator.locks.request(key, () => {
|
|
190
|
-
if (
|
|
190
|
+
if (agents.get(key) !== self) return;
|
|
191
191
|
channel.onmessage = (event) => handle(event.data);
|
|
192
192
|
post({ t: "leader" });
|
|
193
193
|
return new Promise((resolve) => release = resolve);
|
|
@@ -215,12 +215,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
215
215
|
#state = CONNECTING;
|
|
216
216
|
#channel;
|
|
217
217
|
#leave = () => {
|
|
218
|
-
if (this.#state
|
|
219
|
-
this.#post({
|
|
220
|
-
t: "disconnect",
|
|
221
|
-
id: this.#id
|
|
222
|
-
});
|
|
223
|
-
this.#end(1001, "", false);
|
|
218
|
+
if (this.#state < CLOSING) this.#end(1001, "", false);
|
|
224
219
|
};
|
|
225
220
|
#inner;
|
|
226
221
|
static dispose() {
|
|
@@ -255,10 +250,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
255
250
|
id: this.#id
|
|
256
251
|
});
|
|
257
252
|
live.add(this.#leave);
|
|
258
|
-
|
|
259
|
-
hiding = true;
|
|
260
|
-
addEventListener("pagehide", onPageHide);
|
|
261
|
-
}
|
|
253
|
+
addEventListener("pagehide", onPageHide);
|
|
262
254
|
}
|
|
263
255
|
get readyState() {
|
|
264
256
|
return this.#state;
|
|
@@ -321,15 +313,19 @@ function createTabsWebSocket(options = {}) {
|
|
|
321
313
|
}
|
|
322
314
|
#end(code, reason, wasClean) {
|
|
323
315
|
if (this.#state === CLOSED) return;
|
|
316
|
+
if (this.#state < CLOSING) this.#post({
|
|
317
|
+
t: "disconnect",
|
|
318
|
+
id: this.#id
|
|
319
|
+
});
|
|
324
320
|
this.#state = CLOSED;
|
|
325
321
|
this.#channel?.close();
|
|
326
322
|
live.delete(this.#leave);
|
|
323
|
+
if (!live.size) removeEventListener("pagehide", onPageHide);
|
|
327
324
|
this.dispatchEvent(closeEvent(code, reason, wasClean));
|
|
328
325
|
}
|
|
329
326
|
}
|
|
330
327
|
return TabSocket;
|
|
331
328
|
}
|
|
332
|
-
//#endregion
|
|
333
329
|
export { createTabsWebSocket };
|
|
334
330
|
|
|
335
331
|
//# sourceMappingURL=tabs.js.map
|
package/dist/tabs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabs.js","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n let hiding = false;\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n agents.set(key, {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n });\n void navigator.locks.request(key, () => {\n if (!agents.has(key)) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again.\n #leave = () => {\n if (this.#state >= CLOSING) return; // `close()` told the leader already\n this.#post({ t: 'disconnect', id: this.#id });\n this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n if (!hiding) {\n hiding = true;\n addEventListener('pagehide', onPageHide);\n }\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";AAyDA,MAAM,aAAa;AACnB,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+
{"version":3,"file":"tabs.js","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n const self = {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n };\n agents.set(key, self);\n void navigator.locks.request(key, () => {\n // Stopped by `dispose()`, even if the URL has a new agent in this tab since.\n if (agents.get(key) !== self) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again. After `close()`, it ends by itself.\n #leave = () => {\n if (this.#state < CLOSING) this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n // While any socket is live; adding it again does nothing.\n addEventListener('pagehide', onPageHide);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n // Not through `close()`: tell the leader, which may count this socket still, such as one\n // it heard from only after the shared socket closed.\n if (this.#state < CLOSING) this.#post({ t: 'disconnect', id: this.#id });\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n if (!live.size) removeEventListener('pagehide', onPageHide);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";AAyDA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAYf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,IAAI,MAAM;AAGV,MAAM,SAAS,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCtB,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,SAAS,QAAQ,UAAU;CAEjC,MAAM,yBAAS,IAAI,IAA6D;CAEhF,MAAM,QAAQ,SAAkB;EAC9B,IAAI,CAAC,QAAQ,QAAQ,OAAO,SAAS,UAAU,OAAO;EACtD,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,QAAQ;GACN,OAAO;EACT;CACF;;CAGA,MAAM,WACJ,WACA,YACG;EACH,IAAI,CAAC,aAAa,YAAY,QAAQ,OAAO,KAAA;EAC7C,IAAI;GACF,OAAO,UAAU,OAAO,KAAK,KAAA;EAC/B,QAAQ;GACN;EACF;CACF;CAIA,MAAM,uBAAO,IAAI,IAAgB;CACjC,MAAM,mBAAmB;EACvB,KAAK,MAAM,SAAS,CAAC,GAAG,IAAI,GAAG,MAAM;CACvC;CAEA,SAAS,MAAM,KAAa,KAAa,WAA0C;EACjF,IAAI,OAAO,IAAI,GAAG,GAAG;EACrB,MAAM,UAAU,IAAI,iBAAiB,GAAG;EACxC,M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KAAK,SAAS,SAAS,KAAK,MAAM;IAAE,GAAG;IAAc,IAAI,KAAK;GAAI,CAAC;GACvE,KAAK,SAAS;GACd,KAAK,UAAU,MAAM;GACrB,KAAK,OAAO,KAAK,MAAM;GACvB,IAAI,CAAC,KAAK,MAAM,oBAAoB,YAAY,UAAU;GAC1D,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/dist/timeline.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// src/timeline.ts
|
|
3
3
|
const MAX_PENDING = 1e3;
|
|
4
4
|
/**
|
|
5
5
|
* Keep server snapshots on a timeline for multiplayer games: render what the server moves
|
|
@@ -40,6 +40,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
40
40
|
let arrival = -Infinity;
|
|
41
41
|
let rendered = -Infinity;
|
|
42
42
|
let stale = false;
|
|
43
|
+
let measuredBefore;
|
|
43
44
|
let seq = 0;
|
|
44
45
|
let pending = [];
|
|
45
46
|
let prediction;
|
|
@@ -71,7 +72,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
71
72
|
function renderTime() {
|
|
72
73
|
if (!buffer.length) return;
|
|
73
74
|
const measured = latency?.getSnapshot();
|
|
74
|
-
const edge = measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
75
|
+
const edge = measured !== measuredBefore && measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
75
76
|
rendered = Math.max(rendered, edge - (typeof delay === "function" ? delay() : delay));
|
|
76
77
|
return rendered;
|
|
77
78
|
}
|
|
@@ -110,6 +111,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
110
111
|
pending = [];
|
|
111
112
|
folded = -1;
|
|
112
113
|
stale = true;
|
|
114
|
+
measuredBefore = latency?.getSnapshot();
|
|
113
115
|
}), client.on("message", (message) => {
|
|
114
116
|
const snapshot = options.snapshot(message);
|
|
115
117
|
if (snapshot != null) receive(snapshot);
|
|
@@ -156,7 +158,6 @@ function createWebSocketTimeline(client, options) {
|
|
|
156
158
|
}
|
|
157
159
|
};
|
|
158
160
|
}
|
|
159
|
-
//#endregion
|
|
160
161
|
exports.createWebSocketTimeline = createWebSocketTimeline;
|
|
161
162
|
|
|
162
163
|
//# sourceMappingURL=timeline.cjs.map
|
package/dist/timeline.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeline.cjs","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time, the\n * server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";;AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,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OAAO;EACzC,IAAI,YAAY,MAAM,QAAQ,QAAQ;CACxC,CAAC,CACH;CAEA,OAAO;EACL;EACA;EACA;EACA,MAAM,OAAO;GACX,MAAM,OAAO,MAAM;GAEnB,MAAM,UAAU,OAAQ,KAAK,OAAO,IAAI;GACxC,IAAI,CAAC,OAAO,KAAK,SAAS;IAAE,UAAU;IAAM,aAAa,OAAQ;GAAY,CAAC,GAAG;GACjF,MAAM;GACN,QAAQ,KAAK;IAAE;IAAK,OAAO;GAAM,CAAC;GAClC,IAAI,QAAQ,SAAS,aAAa;IAChC,QAAQ,MAAM;IACd,SAAS;GACX;GACA,OAAO;EACT;EACA,cAAc,OAAO,GAAG,EAAE,CAAC,EAAE;EAC7B;EACA,eAAe,QAAQ;EACvB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,QAAQ;GACN,MAAM;GACN,UAAU,CAAC;GACX,SAAS;GACT,OAAO;EACT;EACA,UAAU;GACR,KAAK,SAAQ,QAAO,IAAI,CAAC;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"timeline.cjs","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time on the\n * current connection, the server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n // What `latency` measured before the current connection opened: the clock of a server that\n // may have restarted since.\n let measuredBefore: unknown;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured !== measuredBefore && measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n measuredBefore = latency?.getSnapshot();\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";;AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,MAAM,EAAE,aAAa,SAAS,OAAO,WAAW;CAChD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,OAAO,KAAK,IAAI,GAAG,QAAQ,UAAU,EAAE;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAGtC,IAAI,SAA+D,CAAC;CAEpE,IAAI,UAAU;CAEd,IAAI,WAAW;CAEf,IAAI,QAAQ;CAGZ,IAAI;CACJ,IAAI,MAAM;CACV,IAAI,UAAuC,CAAC;CAC5C,IAAI;CAEJ,IAAI,SAAS;CAEb,SAAS,SAAS;EAChB,KAAK,MAAM,YAAY,CAAC,GAAG,SAAS,GAAG,SAAS;CAClD;CAEA,SAAS,QAAQ;EACf,SAAS,CAAC;EACV,UAAU,WAAW;EACrB,QAAQ;CACV;CAEA,SAAS,QAAQ,UAA+B;EAC9C,IAAI,OAAO,MAAM;EACjB,MAAM,SAAS,OAAO,GAAG,EAAE;EAE3B,IAAI,UAAU,SAAS,QAAQ,OAAO,SAAS,MAAM;EACrD,OAAO,KAAK;GAAE;GAAU,SAAS,YAAY,IAAI;EAAE,CAAC;EACpD,IAAI,OAAO,SAAS,MAAM,OAAO,MAAM;EACvC,UAAU;EACV,KAAK,MAAM,SAAS,QAAQ,UAAU,KAAK,IA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t as WebSocketClient } from "./types-
|
|
2
|
-
//#region src/latency.d.ts
|
|
1
|
+
import { t as WebSocketClient } from "./types-DyZm2F7B.cjs";
|
|
3
2
|
/** Latest latency measurements. A new object is created on every change. */
|
|
4
3
|
interface Latency {
|
|
5
4
|
/** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */
|
|
@@ -25,8 +24,6 @@ interface WebSocketLatency {
|
|
|
25
24
|
/** Stop pinging and listening. Only needed for instances created dynamically. */
|
|
26
25
|
dispose(): void;
|
|
27
26
|
}
|
|
28
|
-
//#endregion
|
|
29
|
-
//#region src/timeline.d.ts
|
|
30
27
|
/** A server snapshot, as returned by the `snapshot` option. */
|
|
31
28
|
export interface TimelineSnapshot<S> {
|
|
32
29
|
/** Server time the state is for, in ms. Must increase from one snapshot to the next. */
|
|
@@ -88,8 +85,8 @@ export interface WebSocketTimelineOptions<S, I, In, Out> {
|
|
|
88
85
|
buffer?: number;
|
|
89
86
|
/**
|
|
90
87
|
* Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use
|
|
91
|
-
* the same clock as snapshot `time`. Without it, or before the first pong with a time
|
|
92
|
-
* server clock is estimated from when snapshots arrive.
|
|
88
|
+
* the same clock as snapshot `time`. Without it, or before the first pong with a time on the
|
|
89
|
+
* current connection, the server clock is estimated from when snapshots arrive.
|
|
93
90
|
*/
|
|
94
91
|
latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;
|
|
95
92
|
/** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */
|
|
@@ -163,6 +160,5 @@ export interface WebSocketTimeline<S, I> {
|
|
|
163
160
|
* ```
|
|
164
161
|
*/
|
|
165
162
|
export declare function createWebSocketTimeline<In, const Out, S, I = never>(client: WebSocketClient<In, Out>, options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>): WebSocketTimeline<S, I>;
|
|
166
|
-
//#endregion
|
|
167
163
|
export {};
|
|
168
164
|
//# sourceMappingURL=timeline.d.cts.map
|
package/dist/timeline.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { WebSocketClient, WebSocketLatency } from "./core.js";
|
|
2
|
-
//#region src/timeline.d.ts
|
|
3
2
|
/** A server snapshot, as returned by the `snapshot` option. */
|
|
4
3
|
export interface TimelineSnapshot<S> {
|
|
5
4
|
/** Server time the state is for, in ms. Must increase from one snapshot to the next. */
|
|
@@ -61,8 +60,8 @@ export interface WebSocketTimelineOptions<S, I, In, Out> {
|
|
|
61
60
|
buffer?: number;
|
|
62
61
|
/**
|
|
63
62
|
* Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use
|
|
64
|
-
* the same clock as snapshot `time`. Without it, or before the first pong with a time
|
|
65
|
-
* server clock is estimated from when snapshots arrive.
|
|
63
|
+
* the same clock as snapshot `time`. Without it, or before the first pong with a time on the
|
|
64
|
+
* current connection, the server clock is estimated from when snapshots arrive.
|
|
66
65
|
*/
|
|
67
66
|
latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;
|
|
68
67
|
/** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */
|
|
@@ -136,5 +135,4 @@ export interface WebSocketTimeline<S, I> {
|
|
|
136
135
|
* ```
|
|
137
136
|
*/
|
|
138
137
|
export declare function createWebSocketTimeline<In, const Out, S, I = never>(client: WebSocketClient<In, Out>, options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>): WebSocketTimeline<S, I>;
|
|
139
|
-
//#endregion
|
|
140
138
|
//# sourceMappingURL=timeline.d.ts.map
|
package/dist/timeline.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/timeline.ts
|
|
2
2
|
const MAX_PENDING = 1e3;
|
|
3
3
|
/**
|
|
4
4
|
* Keep server snapshots on a timeline for multiplayer games: render what the server moves
|
|
@@ -39,6 +39,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
39
39
|
let arrival = -Infinity;
|
|
40
40
|
let rendered = -Infinity;
|
|
41
41
|
let stale = false;
|
|
42
|
+
let measuredBefore;
|
|
42
43
|
let seq = 0;
|
|
43
44
|
let pending = [];
|
|
44
45
|
let prediction;
|
|
@@ -70,7 +71,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
70
71
|
function renderTime() {
|
|
71
72
|
if (!buffer.length) return;
|
|
72
73
|
const measured = latency?.getSnapshot();
|
|
73
|
-
const edge = measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
74
|
+
const edge = measured !== measuredBefore && measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
74
75
|
rendered = Math.max(rendered, edge - (typeof delay === "function" ? delay() : delay));
|
|
75
76
|
return rendered;
|
|
76
77
|
}
|
|
@@ -109,6 +110,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
109
110
|
pending = [];
|
|
110
111
|
folded = -1;
|
|
111
112
|
stale = true;
|
|
113
|
+
measuredBefore = latency?.getSnapshot();
|
|
112
114
|
}), client.on("message", (message) => {
|
|
113
115
|
const snapshot = options.snapshot(message);
|
|
114
116
|
if (snapshot != null) receive(snapshot);
|
|
@@ -155,7 +157,6 @@ function createWebSocketTimeline(client, options) {
|
|
|
155
157
|
}
|
|
156
158
|
};
|
|
157
159
|
}
|
|
158
|
-
//#endregion
|
|
159
160
|
export { createWebSocketTimeline };
|
|
160
161
|
|
|
161
162
|
//# sourceMappingURL=timeline.js.map
|
package/dist/timeline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeline.js","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time, the\n * server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,MAAM,EAAE,aAAa,SAAS,OAAO,WAAW;CAChD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,OAAO,KAAK,IAAI,GAAG,QAAQ,UAAU,EAAE;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAGtC,IAAI,SAA+D,CAAC;CAEpE,IAAI,UAAU;CAEd,IAAI,WAAW;CAEf,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI,UAAuC,CAAC;CAC5C,IAAI;CAEJ,IAAI,SAAS;CAEb,SAAS,SAAS;EAChB,KAAK,MAAM,YAAY,CAAC,GAAG,SAAS,GAAG,SAAS;CAClD;CAEA,SAAS,QAAQ;EACf,SAAS,CAAC;EACV,UAAU,WAAW;EACrB,QAAQ;CACV;CAEA,SAAS,QAAQ,UAA+B;EAC9C,IAAI,OAAO,MAAM;EACjB,MAAM,SAAS,OAAO,GAAG,EAAE;EAE3B,IAAI,UAAU,SAAS,QAAQ,OAAO,SAAS,MA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;GACR,KAAK,SAAQ,QAAO,IAAI,CAAC;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"timeline.js","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time on the\n * current connection, the server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n // What `latency` measured before the current connection opened: the clock of a server that\n // may have restarted since.\n let measuredBefore: unknown;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured !== measuredBefore && measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n measuredBefore = latency?.getSnapshot();\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,MAAM,EAAE,aAAa,SAAS,OAAO,WAAW;CAChD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,OAAO,KAAK,IAAI,GAAG,QAAQ,UAAU,EAAE;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAGtC,IAAI,SAA+D,C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