react-websocket 4.22.1 → 4.22.2
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 +7 -7
- package/dist/ag-ui.cjs.map +1 -1
- package/dist/ag-ui.d.cts +3 -2
- package/dist/ag-ui.js +7 -7
- package/dist/ag-ui.js.map +1 -1
- package/dist/chaos.cjs +59 -11
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts +1 -0
- package/dist/chaos.d.ts +1 -0
- package/dist/chaos.js +59 -11
- package/dist/chaos.js.map +1 -1
- package/dist/core.cjs +82 -43
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +4 -3
- package/dist/core.d.ts +4 -3
- package/dist/core.js +82 -43
- package/dist/core.js.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +3 -2
- package/dist/outbox.cjs +14 -8
- package/dist/outbox.cjs.map +1 -1
- package/dist/outbox.d.cts +1 -1
- package/dist/outbox.js +14 -8
- package/dist/outbox.js.map +1 -1
- package/dist/replay.cjs +12 -7
- package/dist/replay.cjs.map +1 -1
- package/dist/replay.d.cts +8 -2
- package/dist/replay.d.ts +8 -2
- package/dist/replay.js +12 -7
- package/dist/replay.js.map +1 -1
- package/dist/tabs.cjs +11 -14
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs.js +11 -14
- package/dist/tabs.js.map +1 -1
- package/dist/timeline.cjs +3 -1
- package/dist/timeline.cjs.map +1 -1
- package/dist/timeline.d.cts +3 -3
- package/dist/timeline.d.ts +2 -2
- package/dist/timeline.js +3 -1
- package/dist/timeline.js.map +1 -1
- package/dist/{types-paLT8yQF.d.cts → types-Bb3sBG8L.d.cts} +4 -3
- package/dist/webtransport.cjs +12 -10
- package/dist/webtransport.cjs.map +1 -1
- package/dist/webtransport.js +12 -10
- package/dist/webtransport.js.map +1 -1
- package/package.json +6 -6
package/dist/timeline.js
CHANGED
|
@@ -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);
|
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,MAAM;EACrD,OAAO,KAAK;GAAE;GAAU,SAAS,YAAY,IAAI;EAAE,CAAC;EACpD,IAAI,OAAO,SAAS,MAAM,OAAO,MAAM;EACv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"],"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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;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"}
|
|
@@ -235,8 +235,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
235
235
|
close(code?: number, reason?: string): void;
|
|
236
236
|
/**
|
|
237
237
|
* Drop the current socket (if any) and connect again immediately, resetting the
|
|
238
|
-
* backoff. Also restarts a `closed` client
|
|
239
|
-
*
|
|
238
|
+
* backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
|
|
239
|
+
* again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
|
|
240
|
+
* are kept: when another user signs in, call `close()` and then `connect()` instead.
|
|
240
241
|
*/
|
|
241
242
|
reconnect(): void;
|
|
242
243
|
/**
|
|
@@ -270,4 +271,4 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
270
271
|
}
|
|
271
272
|
//#endregion
|
|
272
273
|
export { WebSocketClient as t };
|
|
273
|
-
//# sourceMappingURL=types-
|
|
274
|
+
//# sourceMappingURL=types-Bb3sBG8L.d.cts.map
|
package/dist/webtransport.cjs
CHANGED
|
@@ -90,7 +90,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
90
90
|
this.#fallBack(protocols);
|
|
91
91
|
return;
|
|
92
92
|
}
|
|
93
|
-
this.#connect(protocols);
|
|
93
|
+
this.#connect(protocols).catch(() => this.#fail());
|
|
94
94
|
}
|
|
95
95
|
get readyState() {
|
|
96
96
|
return this.#state;
|
|
@@ -106,7 +106,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
106
106
|
const chain = (this.#chain ?? Promise.resolve()).then(async () => {
|
|
107
107
|
this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));
|
|
108
108
|
if (this.#chain === chain) this.#chain = void 0;
|
|
109
|
-
});
|
|
109
|
+
}).catch(() => this.#fail());
|
|
110
110
|
this.#chain = chain;
|
|
111
111
|
return;
|
|
112
112
|
}
|
|
@@ -141,6 +141,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
141
141
|
let timer;
|
|
142
142
|
try {
|
|
143
143
|
transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);
|
|
144
|
+
transport.closed.catch(() => {});
|
|
144
145
|
await Promise.race([transport.ready, new Promise((_, reject) => timer = setTimeout(reject, timeout, /* @__PURE__ */ new Error("timeout")))]);
|
|
145
146
|
const stream = await transport.createBidirectionalStream();
|
|
146
147
|
if (this.#state !== CONNECTING) return transport.close();
|
|
@@ -152,19 +153,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
152
153
|
this.#transport?.close();
|
|
153
154
|
this.#transport = void 0;
|
|
154
155
|
if (this.#state !== CONNECTING) return;
|
|
155
|
-
if (options.fallback === false)
|
|
156
|
-
this.dispatchEvent(new Event("error"));
|
|
157
|
-
return this.#end(1006, "", false);
|
|
158
|
-
}
|
|
156
|
+
if (options.fallback === false) return this.#fail();
|
|
159
157
|
fallingBack = true;
|
|
160
158
|
return this.#fallBack(protocols);
|
|
161
159
|
} finally {
|
|
162
160
|
clearTimeout(timer);
|
|
163
161
|
}
|
|
164
|
-
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () =>
|
|
165
|
-
this.dispatchEvent(new Event("error"));
|
|
166
|
-
this.#end(1006, "", false);
|
|
167
|
-
});
|
|
162
|
+
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () => this.#fail());
|
|
168
163
|
this.#state = OPEN;
|
|
169
164
|
this.dispatchEvent(new Event("open"));
|
|
170
165
|
}
|
|
@@ -229,6 +224,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
229
224
|
if (data instanceof ArrayBuffer && this.binaryType === "blob") data = new Blob([data]);
|
|
230
225
|
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
231
226
|
}
|
|
227
|
+
/** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */
|
|
228
|
+
#fail() {
|
|
229
|
+
if (this.#state === CLOSED) return;
|
|
230
|
+
this.#transport?.close();
|
|
231
|
+
this.dispatchEvent(new Event("error"));
|
|
232
|
+
this.#end(1006, "", false);
|
|
233
|
+
}
|
|
232
234
|
#end(code, reason, wasClean) {
|
|
233
235
|
if (this.#state === CLOSED) return;
|
|
234
236
|
this.#state = CLOSED;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webtransport.cjs","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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\nfunction bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n void this.#connect(protocols);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve()).then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n });\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) {\n this.dispatchEvent(new Event('error'));\n return this.#end(1006, '', false);\n }\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => {\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";;AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,SAAS,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,QAAQ,KAAK,YAAY,KAAK,UAAU,CAAC;AAC/E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAAqC,CAAC,GACf;CACvB,MAAM,SAAS,QAAQ,SAAS,QAAgB,IAAI,QAA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MAAc,SAAqB;GACxC,KAAK,SAAS,SAAS,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM;EAClF;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,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"webtransport.cjs","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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\nfunction bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n // A fallback that throws, e.g. for protocols the WebSocket rejects, fails the connection.\n this.#connect(protocols).catch(() => this.#fail());\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve())\n .then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n })\n // A Blob that can't be read fails the connection, as in browsers, rather than\n // holding up every send after it.\n .catch(() => this.#fail());\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n // A session that fails rejects `closed` too, before anything listens to it.\n transport.closed.catch(() => {});\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) return this.#fail();\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => this.#fail()\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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 /** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */\n #fail() {\n if (this.#state === CLOSED) return;\n this.#transport?.close();\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";;AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,SAAS,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,QAA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,IAAI,MAAM;KACV,IAAI,MAAM,YAAY,KAAK,OAAO,MAAM,IAAK,MAAM,MAAM,CAAC,CAAC;IAC7D;GACF,QAAQ,CAER;EACF;EAEA,OAAO,MAAc,SAAqB;GACxC,KAAK,SAAS,SAAS,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM;EAClF;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;;EAGA,QAAQ;GACN,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,YAAY,MAAM;GACvB,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;GACrC,KAAK,KAAK,MAAM,IAAI,KAAK;EAC3B;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/dist/webtransport.js
CHANGED
|
@@ -89,7 +89,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
89
89
|
this.#fallBack(protocols);
|
|
90
90
|
return;
|
|
91
91
|
}
|
|
92
|
-
this.#connect(protocols);
|
|
92
|
+
this.#connect(protocols).catch(() => this.#fail());
|
|
93
93
|
}
|
|
94
94
|
get readyState() {
|
|
95
95
|
return this.#state;
|
|
@@ -105,7 +105,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
105
105
|
const chain = (this.#chain ?? Promise.resolve()).then(async () => {
|
|
106
106
|
this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));
|
|
107
107
|
if (this.#chain === chain) this.#chain = void 0;
|
|
108
|
-
});
|
|
108
|
+
}).catch(() => this.#fail());
|
|
109
109
|
this.#chain = chain;
|
|
110
110
|
return;
|
|
111
111
|
}
|
|
@@ -140,6 +140,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
140
140
|
let timer;
|
|
141
141
|
try {
|
|
142
142
|
transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);
|
|
143
|
+
transport.closed.catch(() => {});
|
|
143
144
|
await Promise.race([transport.ready, new Promise((_, reject) => timer = setTimeout(reject, timeout, /* @__PURE__ */ new Error("timeout")))]);
|
|
144
145
|
const stream = await transport.createBidirectionalStream();
|
|
145
146
|
if (this.#state !== CONNECTING) return transport.close();
|
|
@@ -151,19 +152,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
151
152
|
this.#transport?.close();
|
|
152
153
|
this.#transport = void 0;
|
|
153
154
|
if (this.#state !== CONNECTING) return;
|
|
154
|
-
if (options.fallback === false)
|
|
155
|
-
this.dispatchEvent(new Event("error"));
|
|
156
|
-
return this.#end(1006, "", false);
|
|
157
|
-
}
|
|
155
|
+
if (options.fallback === false) return this.#fail();
|
|
158
156
|
fallingBack = true;
|
|
159
157
|
return this.#fallBack(protocols);
|
|
160
158
|
} finally {
|
|
161
159
|
clearTimeout(timer);
|
|
162
160
|
}
|
|
163
|
-
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () =>
|
|
164
|
-
this.dispatchEvent(new Event("error"));
|
|
165
|
-
this.#end(1006, "", false);
|
|
166
|
-
});
|
|
161
|
+
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () => this.#fail());
|
|
167
162
|
this.#state = OPEN;
|
|
168
163
|
this.dispatchEvent(new Event("open"));
|
|
169
164
|
}
|
|
@@ -228,6 +223,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
228
223
|
if (data instanceof ArrayBuffer && this.binaryType === "blob") data = new Blob([data]);
|
|
229
224
|
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
230
225
|
}
|
|
226
|
+
/** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */
|
|
227
|
+
#fail() {
|
|
228
|
+
if (this.#state === CLOSED) return;
|
|
229
|
+
this.#transport?.close();
|
|
230
|
+
this.dispatchEvent(new Event("error"));
|
|
231
|
+
this.#end(1006, "", false);
|
|
232
|
+
}
|
|
231
233
|
#end(code, reason, wasClean) {
|
|
232
234
|
if (this.#state === CLOSED) return;
|
|
233
235
|
this.#state = CLOSED;
|
package/dist/webtransport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webtransport.js","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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\nfunction bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n void this.#connect(protocols);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve()).then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n });\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) {\n this.dispatchEvent(new Event('error'));\n return this.#end(1006, '', false);\n }\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => {\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,SAAS,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,QAAQ,KAAK,YAAY,KAAK,UAAU,CAAC;AAC/E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAAqC,CAAC,GACf;CACvB,MAAM,SAAS,QAAQ,SAAS,QAAgB,IAAI,QAAQ,YAAY,QAAQ;CAChF,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI,cAAc;CAElB,MAAM,2BAA2B,YAAiC;EAChE,OAAgB,aAAa;EAC7B,OAAgB,OAAO;EACvB,OAAgB,UAAU;EAC1B,OAAgB,SAAS;EACzB,aAAsB;EACtB,OAAgB;EAChB,UAAmB;EACnB,SAAkB;EAElB;EACA,aAAsB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AAK,cAAc,IAAI,aAAa,WAAW,EAAE,KAAK,CAAC,CAAC;EAC1D;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"webtransport.js","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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\nfunction bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n // A fallback that throws, e.g. for protocols the WebSocket rejects, fails the connection.\n this.#connect(protocols).catch(() => this.#fail());\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve())\n .then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n })\n // A Blob that can't be read fails the connection, as in browsers, rather than\n // holding up every send after it.\n .catch(() => this.#fail());\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n // A session that fails rejects `closed` too, before anything listens to it.\n transport.closed.catch(() => {});\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) return this.#fail();\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => this.#fail()\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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 /** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */\n #fail() {\n if (this.#state === CLOSED) return;\n this.#transport?.close();\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,SAAS,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,QAAQ,KAAK,YAAY,KAAK,UAAU,CAAC;AAC/E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAAqC,CAAC,GACf;CACvB,MAAM,SAAS,QAAQ,SAAS,QAAgB,IAAI,QAAQ,YAAY,QAAQ;CAChF,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI,cAAc;CAElB,MAAM,2BAA2B,YAA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;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;;EAGA,QAAQ;GACN,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,YAAY,MAAM;GACvB,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;GACrC,KAAK,KAAK,MAAM,IAAI,KAAK;EAC3B;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-websocket",
|
|
3
|
-
"version": "4.22.
|
|
3
|
+
"version": "4.22.2",
|
|
4
4
|
"description": "The real-time toolkit for React: a WebSocket hook with shared connections, auto-reconnect and typed messages, plus topics, state, requests, presence and AI agents",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -239,7 +239,7 @@
|
|
|
239
239
|
"ignore": [
|
|
240
240
|
"react"
|
|
241
241
|
],
|
|
242
|
-
"limit": "1.
|
|
242
|
+
"limit": "1.9 kB",
|
|
243
243
|
"gzip": true
|
|
244
244
|
},
|
|
245
245
|
{
|
|
@@ -249,7 +249,7 @@
|
|
|
249
249
|
"ignore": [
|
|
250
250
|
"react"
|
|
251
251
|
],
|
|
252
|
-
"limit": "1.
|
|
252
|
+
"limit": "1.8 kB",
|
|
253
253
|
"gzip": true
|
|
254
254
|
},
|
|
255
255
|
{
|
|
@@ -259,7 +259,7 @@
|
|
|
259
259
|
"ignore": [
|
|
260
260
|
"react"
|
|
261
261
|
],
|
|
262
|
-
"limit": "1.
|
|
262
|
+
"limit": "1.25 kB",
|
|
263
263
|
"gzip": true
|
|
264
264
|
},
|
|
265
265
|
{
|
|
@@ -279,7 +279,7 @@
|
|
|
279
279
|
"ignore": [
|
|
280
280
|
"react"
|
|
281
281
|
],
|
|
282
|
-
"limit": "
|
|
282
|
+
"limit": "780 B",
|
|
283
283
|
"gzip": true
|
|
284
284
|
},
|
|
285
285
|
{
|
|
@@ -296,7 +296,7 @@
|
|
|
296
296
|
"name": "react-websocket/chaos (createChaosWebSocket)",
|
|
297
297
|
"path": "dist/chaos.js",
|
|
298
298
|
"import": "{ createChaosWebSocket }",
|
|
299
|
-
"limit": "2.
|
|
299
|
+
"limit": "2.3 kB",
|
|
300
300
|
"gzip": true
|
|
301
301
|
},
|
|
302
302
|
{
|