@colyseus/core 0.17.44 → 0.18.1

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.
Files changed (157) hide show
  1. package/build/MatchMaker.cjs +22 -13
  2. package/build/MatchMaker.cjs.map +2 -2
  3. package/build/MatchMaker.d.ts +10 -0
  4. package/build/MatchMaker.mjs +22 -14
  5. package/build/MatchMaker.mjs.map +2 -2
  6. package/build/Protocol.cjs +102 -37
  7. package/build/Protocol.cjs.map +2 -2
  8. package/build/Protocol.d.ts +33 -2
  9. package/build/Protocol.mjs +102 -37
  10. package/build/Protocol.mjs.map +2 -2
  11. package/build/Rewind.cjs +385 -0
  12. package/build/Rewind.cjs.map +7 -0
  13. package/build/Rewind.d.ts +291 -0
  14. package/build/Rewind.mjs +359 -0
  15. package/build/Rewind.mjs.map +7 -0
  16. package/build/Room.cjs +425 -149
  17. package/build/Room.cjs.map +3 -3
  18. package/build/Room.d.ts +314 -27
  19. package/build/Room.mjs +434 -152
  20. package/build/Room.mjs.map +3 -3
  21. package/build/RoomMessages.cjs +265 -0
  22. package/build/RoomMessages.cjs.map +7 -0
  23. package/build/RoomMessages.d.ts +49 -0
  24. package/build/RoomMessages.mjs +240 -0
  25. package/build/RoomMessages.mjs.map +7 -0
  26. package/build/RoomPlugin.cjs +252 -0
  27. package/build/RoomPlugin.cjs.map +7 -0
  28. package/build/RoomPlugin.d.ts +271 -0
  29. package/build/RoomPlugin.mjs +220 -0
  30. package/build/RoomPlugin.mjs.map +7 -0
  31. package/build/Server.cjs +49 -11
  32. package/build/Server.cjs.map +2 -2
  33. package/build/Server.d.ts +26 -0
  34. package/build/Server.mjs +50 -12
  35. package/build/Server.mjs.map +2 -2
  36. package/build/Transport.cjs +64 -2
  37. package/build/Transport.cjs.map +2 -2
  38. package/build/Transport.d.ts +108 -5
  39. package/build/Transport.mjs +63 -2
  40. package/build/Transport.mjs.map +2 -2
  41. package/build/errors/RoomExceptions.cjs +7 -4
  42. package/build/errors/RoomExceptions.cjs.map +2 -2
  43. package/build/errors/RoomExceptions.d.ts +15 -3
  44. package/build/errors/RoomExceptions.mjs +5 -3
  45. package/build/errors/RoomExceptions.mjs.map +2 -2
  46. package/build/index.cjs +30 -4
  47. package/build/index.cjs.map +2 -2
  48. package/build/index.d.ts +9 -5
  49. package/build/index.mjs +29 -6
  50. package/build/index.mjs.map +2 -2
  51. package/build/input/InputBuffer.cjs +536 -0
  52. package/build/input/InputBuffer.cjs.map +7 -0
  53. package/build/input/InputBuffer.d.ts +226 -0
  54. package/build/input/InputBuffer.mjs +507 -0
  55. package/build/input/InputBuffer.mjs.map +7 -0
  56. package/build/input/RoomInput.cjs +306 -0
  57. package/build/input/RoomInput.cjs.map +7 -0
  58. package/build/input/RoomInput.d.ts +91 -0
  59. package/build/input/RoomInput.mjs +287 -0
  60. package/build/input/RoomInput.mjs.map +7 -0
  61. package/build/input/types.cjs +18 -0
  62. package/build/input/types.cjs.map +7 -0
  63. package/build/input/types.d.ts +476 -0
  64. package/build/input/types.mjs +0 -0
  65. package/build/input/types.mjs.map +7 -0
  66. package/build/internal.cjs +61 -0
  67. package/build/internal.cjs.map +7 -0
  68. package/build/internal.d.ts +9 -0
  69. package/build/internal.mjs +29 -0
  70. package/build/internal.mjs.map +7 -0
  71. package/build/matchmaker/LocalDriver/LocalDriver.cjs +13 -0
  72. package/build/matchmaker/LocalDriver/LocalDriver.cjs.map +2 -2
  73. package/build/matchmaker/LocalDriver/LocalDriver.d.ts +1 -0
  74. package/build/matchmaker/LocalDriver/LocalDriver.mjs +13 -0
  75. package/build/matchmaker/LocalDriver/LocalDriver.mjs.map +2 -2
  76. package/build/matchmaker/driver.cjs.map +1 -1
  77. package/build/matchmaker/driver.d.ts +12 -0
  78. package/build/matchmaker/driver.mjs.map +1 -1
  79. package/build/presence/LocalPresence.d.ts +1 -1
  80. package/build/rooms/LobbyRoom.cjs +8 -10
  81. package/build/rooms/LobbyRoom.cjs.map +2 -2
  82. package/build/rooms/LobbyRoom.d.ts +4 -3
  83. package/build/rooms/LobbyRoom.mjs +8 -10
  84. package/build/rooms/LobbyRoom.mjs.map +2 -2
  85. package/build/rooms/QueueRoom.cjs +1 -1
  86. package/build/rooms/QueueRoom.cjs.map +2 -2
  87. package/build/rooms/QueueRoom.mjs +1 -1
  88. package/build/rooms/QueueRoom.mjs.map +2 -2
  89. package/build/rooms/RelayRoom.cjs +12 -16
  90. package/build/rooms/RelayRoom.cjs.map +2 -2
  91. package/build/rooms/RelayRoom.d.ts +32 -11
  92. package/build/rooms/RelayRoom.mjs +10 -16
  93. package/build/rooms/RelayRoom.mjs.map +2 -2
  94. package/build/router/default_routes.cjs +4 -1
  95. package/build/router/default_routes.cjs.map +2 -2
  96. package/build/router/default_routes.mjs +4 -1
  97. package/build/router/default_routes.mjs.map +2 -2
  98. package/build/router/index.cjs +71 -5
  99. package/build/router/index.cjs.map +2 -2
  100. package/build/router/index.d.ts +30 -6
  101. package/build/router/index.mjs +72 -7
  102. package/build/router/index.mjs.map +3 -3
  103. package/build/serializer/NoneSerializer.cjs +2 -2
  104. package/build/serializer/NoneSerializer.cjs.map +2 -2
  105. package/build/serializer/NoneSerializer.d.ts +3 -3
  106. package/build/serializer/NoneSerializer.mjs +2 -2
  107. package/build/serializer/NoneSerializer.mjs.map +2 -2
  108. package/build/serializer/SchemaSerializer.cjs +44 -14
  109. package/build/serializer/SchemaSerializer.cjs.map +2 -2
  110. package/build/serializer/SchemaSerializer.d.ts +3 -3
  111. package/build/serializer/SchemaSerializer.mjs +46 -16
  112. package/build/serializer/SchemaSerializer.mjs.map +2 -2
  113. package/build/serializer/Serializer.cjs.map +1 -1
  114. package/build/serializer/Serializer.d.ts +12 -2
  115. package/build/utils/DevMode.cjs +14 -14
  116. package/build/utils/DevMode.cjs.map +2 -2
  117. package/build/utils/DevMode.d.ts +0 -2
  118. package/build/utils/DevMode.mjs +14 -12
  119. package/build/utils/DevMode.mjs.map +2 -2
  120. package/build/utils/UserSessionIndex.cjs +162 -0
  121. package/build/utils/UserSessionIndex.cjs.map +7 -0
  122. package/build/utils/UserSessionIndex.d.ts +166 -0
  123. package/build/utils/UserSessionIndex.mjs +130 -0
  124. package/build/utils/UserSessionIndex.mjs.map +7 -0
  125. package/build/utils/Utils.cjs +3 -0
  126. package/build/utils/Utils.cjs.map +2 -2
  127. package/build/utils/Utils.d.ts +8 -0
  128. package/build/utils/Utils.mjs +2 -0
  129. package/build/utils/Utils.mjs.map +2 -2
  130. package/package.json +19 -14
  131. package/src/MatchMaker.ts +47 -15
  132. package/src/Protocol.ts +130 -59
  133. package/src/Rewind.ts +572 -0
  134. package/src/Room.ts +649 -235
  135. package/src/RoomMessages.ts +342 -0
  136. package/src/RoomPlugin.ts +563 -0
  137. package/src/Server.ts +82 -15
  138. package/src/Transport.ts +172 -9
  139. package/src/errors/RoomExceptions.ts +18 -4
  140. package/src/index.ts +23 -3
  141. package/src/input/InputBuffer.ts +549 -0
  142. package/src/input/RoomInput.ts +337 -0
  143. package/src/input/types.ts +503 -0
  144. package/src/internal.ts +46 -0
  145. package/src/matchmaker/LocalDriver/LocalDriver.ts +10 -0
  146. package/src/matchmaker/driver.ts +13 -0
  147. package/src/rooms/LobbyRoom.ts +12 -8
  148. package/src/rooms/QueueRoom.ts +1 -1
  149. package/src/rooms/RelayRoom.ts +9 -15
  150. package/src/router/default_routes.ts +6 -1
  151. package/src/router/index.ts +117 -11
  152. package/src/serializer/NoneSerializer.ts +3 -3
  153. package/src/serializer/SchemaSerializer.ts +110 -19
  154. package/src/serializer/Serializer.ts +13 -2
  155. package/src/utils/DevMode.ts +18 -13
  156. package/src/utils/UserSessionIndex.ts +311 -0
  157. package/src/utils/Utils.ts +9 -0
@@ -0,0 +1,549 @@
1
+ import type { ClientPrivate } from '../Transport.ts';
2
+ import { $METADATA } from '../utils/Utils.ts';
3
+
4
+ import type {
5
+ ConsumeOptions, IdleContext, IdleInput, InputAccessor, SanitizeInput,
6
+ } from './types.ts';
7
+
8
+ /**
9
+ * @internal Validate a `subSteps` count. Throws on a fractional/non-positive
10
+ * value: both sides loop `subSteps` times at `dt/subSteps`, so anything but a
11
+ * whole number is a determinism bug, not a tunable. Shared by `defineInput`
12
+ * and `setFixedTimestep`.
13
+ */
14
+ export function validateSubSteps(subSteps: number | undefined, source: string): number | undefined {
15
+ if (subSteps === undefined) { return undefined; }
16
+ if (!Number.isInteger(subSteps) || subSteps < 1) {
17
+ throw new Error(`[${source}] subSteps must be an integer >= 1 (got ${subSteps}).`);
18
+ }
19
+ return subSteps;
20
+ }
21
+
22
+ /**
23
+ * @internal Compile a {@link SanitizeInput} spec into the per-frame function the
24
+ * decode path applies. The map form precompiles to dense min/max arrays walked
25
+ * with the NaN-safe branch clamp; the callback form passes through.
26
+ */
27
+ export function compileSanitizer<I>(spec: SanitizeInput<I>): (input: I) => void {
28
+ if (typeof spec === 'function') { return spec; }
29
+ const names = Object.keys(spec);
30
+ const mins = new Float64Array(names.length);
31
+ const maxs = new Float64Array(names.length);
32
+ for (let i = 0; i < names.length; i++) {
33
+ const range = (spec as Record<string, readonly [number, number]>)[names[i]]!;
34
+ mins[i] = range[0];
35
+ maxs[i] = range[1];
36
+ }
37
+ return (input: I) => {
38
+ const inst = input as Record<string, number>;
39
+ for (let i = 0; i < names.length; i++) {
40
+ const v = inst[names[i]];
41
+ // NaN-safe: NaN fails both comparisons → clamp floor.
42
+ inst[names[i]] = v >= mins[i] ? (v <= maxs[i] ? v : maxs[i]) : mins[i];
43
+ }
44
+ };
45
+ }
46
+
47
+ /** Field names of an input schema ctor, in declaration order (indices are dense
48
+ * from 0 in the metadata). Resolved ONCE per buffer (cold path). */
49
+ function fieldNamesOf(ctor: new () => any): string[] {
50
+ const md = (ctor as any)[$METADATA] as Record<number, { name?: string }> | undefined;
51
+ const names: string[] = [];
52
+ if (md) {
53
+ for (let i = 0; ; i++) {
54
+ const f = md[i];
55
+ if (!f || typeof f.name !== "string") break;
56
+ names.push(f.name);
57
+ }
58
+ }
59
+ return names;
60
+ }
61
+
62
+ /** Reclaim the consumed prefix once the read cursor passes this many items —
63
+ * bounds the parallel arrays' slack to O(THRESHOLD) between compactions while
64
+ * keeping per-consume work O(1) (no `shift()` re-index on every input). */
65
+ const COMPACT_THRESHOLD = 32;
66
+
67
+ /** Shared zero-state "already done" iterator — returned by `consume()` on an
68
+ * empty buffer with no idle policy, and by the no-op accessor. Frozen + a frozen
69
+ * result, so it's allocation-free and safe to share across all callers. */
70
+ const DONE_RESULT: IteratorResult<any> = Object.freeze({ value: undefined, done: true });
71
+ const DONE_ITERATOR: IterableIterator<any> = Object.freeze({
72
+ [Symbol.iterator]() { return this; },
73
+ next() { return DONE_RESULT; },
74
+ });
75
+
76
+ /** @internal */
77
+ export class InputBufferImpl<I = any> {
78
+ /** Pending snapshots, indexed `[_head, _items.length)`. Consumed inputs are
79
+ * NOT spliced off per-read — `_head` advances and the prefix is reclaimed in
80
+ * bulk by {@link compact} (a `shift()` per read is O(n), so a burst would be
81
+ * O(n²)). `_renderTimes`/`_reckonTimes` stay parallel to `_items`. */
82
+ private _items: I[] = [];
83
+ /** Read cursor: index of the oldest UNCONSUMED input (== `_items.length` when empty). */
84
+ private _head = 0;
85
+ private _lastSeq: number = -Infinity;
86
+ private readonly _maxSize: number;
87
+ private readonly _seqField: string | undefined;
88
+
89
+ /**
90
+ * Cumulative count of inputs CONSUMED from this buffer (via any consume
91
+ * primitive — {@link next}/{@link take}/{@link drain}/{@link consume} — plus
92
+ * {@link clear} and overflow). Consumed = "removed from the pending set",
93
+ * whether applied to state or discarded. The server echoes this in the TIMED
94
+ * prefix as the reconciliation ack: how many of the client's inputs are
95
+ * reflected in (or finished influencing) the authoritative state, which lags
96
+ * the receive counter by inputs still buffered. Distinct from
97
+ * `_receivedInputCount` (receive-time, for RTT), which leads the state.
98
+ */
99
+ consumedCount = 0;
100
+
101
+ /** Render times parallel to `_items` (server-clock ms; `0` when unset). */
102
+ private _renderTimes: number[] = [];
103
+ /** Render time of the most recently drained input (see {@link renderTime}). */
104
+ private _lastRenderTime = 0;
105
+ /** Reckon-display stamps parallel to `_items` — the client's serverNow
106
+ * estimate at input-sample time, i.e. the instant its forward-reckoned
107
+ * entities were displayed at (server-clock ms; `0` when unset). */
108
+ private _reckonTimes: number[] = [];
109
+ /** Reckon stamp of the most recently consumed input (see {@link reckonTime}). */
110
+ private _lastReckonTime = 0;
111
+ /** Framework wire seq per buffered input (parallel to `_items`) — UNRELIABLE
112
+ * ONLY, lazily created on the first seq-carrying push. Reliable inputs are
113
+ * contiguous, so their consumed-seq-value is always exactly {@link consumedCount}
114
+ * and needs no parallel array; `undefined` here marks that (the common, default
115
+ * path pays nothing). A buffer is single-mode, so this is either never created
116
+ * (reliable) or created once and kept parallel (unreliable). */
117
+ private _seqs?: number[];
118
+ /** Seq VALUE of the last consumed input — the reconciliation ack echoed to the
119
+ * client (see {@link ackSeq}). Only meaningful when {@link _seqs} is tracked
120
+ * (unreliable); reliable's ack falls back to {@link consumedCount}. */
121
+ private _lastConsumedSeq = 0;
122
+ /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */
123
+ private _lastWasIdle = false;
124
+
125
+ /** Reused {@link consume} iterator (lazily minted) + its per-call state, so a
126
+ * per-tick loop allocates no generator frame. `_iterRemaining` snapshots the
127
+ * COUNT to walk — a count, not an index: mid-pass mutations (`next()`/`take()`/
128
+ * `clear()`/compaction) shift indices but can only shorten a count-based pass,
129
+ * never point it past the tail. `_iterIdle` is an optional trailing synthesized
130
+ * frame; `_iterActive` guards against a nested consume() clobbering the shared
131
+ * `_iterRes`. */
132
+ private _iter?: IterableIterator<I>;
133
+ private _iterRemaining = 0;
134
+ private _iterActive = false;
135
+ private _iterIdle?: I;
136
+ private readonly _iterRes: { value: I | undefined; done: boolean } = { value: undefined, done: false };
137
+
138
+ /** Input schema ctor — mints the reused idle frame; idle is off without it. */
139
+ private readonly _ctor?: new () => I;
140
+ /** Client slice this buffer belongs to (the live object is `Client & ClientPrivate`)
141
+ * — feeds the idle callback's ctx (latest + sessionId). */
142
+ private readonly _client?: Pick<ClientPrivate, '_input'> & { sessionId: string };
143
+ /** Room-level idle policy (`defineInput({ idle })`) — the bare-call default. */
144
+ private readonly _roomIdle?: IdleInput<I>;
145
+ /** Reused synthesized idle frame + the schema's field names/defaults (lazy). */
146
+ private _idle?: I;
147
+ private _fieldNames?: string[];
148
+ private _defaults?: unknown[];
149
+ /** Reused ctx for the idle callback form (see {@link IdleContext}). */
150
+ private readonly _idleCtx: IdleContext<I> = { latest: undefined, sessionId: "" };
151
+
152
+ constructor(maxSize: number, seqField: string | undefined, ctor?: new () => I, client?: Pick<ClientPrivate, '_input'> & { sessionId: string }, idle?: IdleInput<I>) {
153
+ this._maxSize = maxSize;
154
+ this._seqField = seqField;
155
+ this._ctor = ctor;
156
+ this._client = client;
157
+ this._roomIdle = idle;
158
+ }
159
+
160
+ /** The effective idle policy for one consume call: per-call `false` suppresses,
161
+ * per-call value overrides, else the room-level default (or none). */
162
+ private effectiveIdle(opts?: ConsumeOptions<I>): IdleInput<I> | undefined {
163
+ return opts?.idle === false ? undefined : (opts?.idle ?? this._roomIdle);
164
+ }
165
+
166
+ /** Resolve an {@link IdleInput} to overrides — invokes the callback form
167
+ * LAZILY, here at synthesis time (the buffer is known to be empty). */
168
+ private resolveIdle(idle: IdleInput<I>): true | Partial<I> {
169
+ if (typeof idle !== "function") return idle;
170
+ this._idleCtx.latest = this._client?._input as I | undefined;
171
+ this._idleCtx.sessionId = this._client?.sessionId ?? "";
172
+ return idle(this._idleCtx) ?? true;
173
+ }
174
+
175
+ /**
176
+ * The synthesized "no input this tick" frame: schema defaults overlaid with
177
+ * `overrides` (`true` = none). Copies BY FIELD NAME from the schema metadata —
178
+ * schema fields are prototype accessors (no own props), so `Object.assign`
179
+ * can't source from a schema instance; the name walk reads getters, letting
180
+ * `overrides` be a plain partial OR a schema instance (e.g. `latest`).
181
+ * ONE reused instance — refilled per call, never advances the ack.
182
+ */
183
+ private idleFrame(overrides: true | Partial<I>): I {
184
+ if (this._idle === undefined) {
185
+ // Lazy mint (cold): the fresh instance doubles as the defaults source.
186
+ this._idle = new this._ctor!();
187
+ this._fieldNames = fieldNamesOf(this._ctor!);
188
+ const fresh = this._idle as Record<string, unknown>;
189
+ this._defaults = this._fieldNames.map((n) => fresh[n]);
190
+ }
191
+ const idle = this._idle as Record<string, unknown>;
192
+ const names = this._fieldNames!;
193
+ const defaults = this._defaults!;
194
+ const ov = overrides === true ? undefined : (overrides as Record<string, unknown>);
195
+ for (let i = 0; i < names.length; i++) {
196
+ const v = ov?.[names[i]];
197
+ idle[names[i]] = v !== undefined ? v : defaults[i];
198
+ }
199
+ return this._idle;
200
+ }
201
+
202
+ /** The idle frame to synthesize on an empty tick (room policy or per-call
203
+ * `opts.idle`), or `undefined` when no policy is in effect. Reuses the single
204
+ * idle instance; never advances the ack. Callers set {@link wasIdle}. */
205
+ private idleFrameOnEmpty(opts?: ConsumeOptions<I>): I | undefined {
206
+ const idle = this._ctor !== undefined ? this.effectiveIdle(opts) : undefined;
207
+ return idle === undefined ? undefined : this.idleFrame(this.resolveIdle(idle));
208
+ }
209
+
210
+ /** Consume the input at the cursor: advance cursor + ack, stamp THIS input's
211
+ * render/reckon times, clear {@link wasIdle}. The shared per-input step behind
212
+ * {@link next}, {@link consume}'s iterator, and the re-entrant fallback. */
213
+ private stepHead(): I {
214
+ const i = this._head;
215
+ this._lastWasIdle = false;
216
+ this._lastRenderTime = this._renderTimes[i];
217
+ this._lastReckonTime = this._reckonTimes[i];
218
+ if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[i]; }
219
+ this._head = i + 1;
220
+ this.consumedCount++;
221
+ return this._items[i];
222
+ }
223
+
224
+ /** Drop ALL slots, reusing the backing arrays' capacity — the zero-GC reset for
225
+ * the consume/next path ({@link compact}/{@link clear}). `drain()` deliberately
226
+ * does NOT use this (it returns an array, so fresh `[]` is faster there). */
227
+ private truncate(): void {
228
+ this._items.length = 0;
229
+ this._renderTimes.length = 0;
230
+ this._reckonTimes.length = 0;
231
+ if (this._seqs !== undefined) { this._seqs.length = 0; }
232
+ this._head = 0;
233
+ }
234
+
235
+ /**
236
+ * Append a decoded input snapshot. `seq` is the framework wire seq (unreliable);
237
+ * omit it for reliable inputs, which get an implicit monotonic receive count so
238
+ * {@link ackSeq} stays well-defined in both modes.
239
+ */
240
+ push(snapshot: I, renderTime: number = 0, reckonTime: number = 0, seq?: number): void {
241
+ this._items.push(snapshot);
242
+ this._renderTimes.push(renderTime);
243
+ this._reckonTimes.push(reckonTime);
244
+ // Track the wire seq only for unreliable (seq provided); reliable derives its
245
+ // ack from consumedCount, so it never allocates/maintains this array.
246
+ if (seq !== undefined) { (this._seqs ??= []).push(seq); }
247
+ // Overflow drops the oldest unconsumed input; count it consumed so the ack
248
+ // still advances past it. Advance the cursor (don't shift) — keeps it O(1).
249
+ if (this.size > this._maxSize) {
250
+ if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[this._head]; } // dropped oldest counts as acked
251
+ this._head++;
252
+ this.consumedCount++;
253
+ this.compact();
254
+ }
255
+ }
256
+
257
+ /** Reclaim the consumed prefix `[0, _head)`. Free when fully drained (reuse the
258
+ * arrays); otherwise splice only once the cursor passes {@link COMPACT_THRESHOLD},
259
+ * so the amortized per-input cost stays O(1). */
260
+ private compact(): void {
261
+ if (this._head === 0) { return; }
262
+ if (this._head >= this._items.length) {
263
+ this.truncate();
264
+ } else if (this._head >= COMPACT_THRESHOLD) {
265
+ this._items.splice(0, this._head);
266
+ this._renderTimes.splice(0, this._head);
267
+ this._reckonTimes.splice(0, this._head);
268
+ if (this._seqs !== undefined) { this._seqs.splice(0, this._head); }
269
+ this._head = 0;
270
+ }
271
+ }
272
+
273
+ /** Returns true if `value` hasn't been seen, and updates the last-seen marker. */
274
+ accept(value: number): boolean {
275
+ if (value <= this._lastSeq) { return false; }
276
+ this._lastSeq = value;
277
+ return true;
278
+ }
279
+
280
+ drain(opts?: ConsumeOptions<I>): I[] {
281
+ // Empty: synthesize one idle frame (NOT consumed — no ack bump, stamps
282
+ // untouched) when a policy is in effect, else [].
283
+ if (this.size === 0) {
284
+ const idle = this.idleFrameOnEmpty(opts);
285
+ this._lastWasIdle = idle !== undefined;
286
+ return idle !== undefined ? [idle] : [];
287
+ }
288
+ this._lastWasIdle = false;
289
+ const last = this._items.length - 1;
290
+ this._lastRenderTime = this._renderTimes[last]; // drain reports the NEWEST stamps
291
+ this._lastReckonTime = this._reckonTimes[last];
292
+ if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[last]; }
293
+ // Hand off the backing array untouched when nothing was partially consumed
294
+ // (O(1) — the caller may retain it); else copy out the unconsumed tail. Fresh
295
+ // arrays here, NOT truncate(): drain already allocates the returned array, and
296
+ // V8 makes `= []` + refill cheaper than `length = 0` reuse (~1.8× at small N),
297
+ // so the speed wins and the 3 tiny empties are negligible next to the return.
298
+ const out = this._head === 0 ? this._items : this._items.slice(this._head);
299
+ this.consumedCount += out.length;
300
+ this._items = [];
301
+ this._renderTimes = [];
302
+ this._reckonTimes = [];
303
+ if (this._seqs !== undefined) { this._seqs = []; }
304
+ this._head = 0;
305
+ return out;
306
+ }
307
+
308
+ /** Consume the single oldest input (ack advances by one); `undefined` if
309
+ * empty — or the synthesized idle frame when an idle policy is in effect. */
310
+ next(opts?: ConsumeOptions<I>): I | undefined {
311
+ if (this.size === 0) {
312
+ const idle = this.idleFrameOnEmpty(opts);
313
+ this._lastWasIdle = idle !== undefined;
314
+ return idle;
315
+ }
316
+ const item = this.stepHead();
317
+ this.compact();
318
+ return item;
319
+ }
320
+
321
+ /** Consume up to `n` oldest inputs (ack advances by the count actually taken). */
322
+ take(n: number): I[] {
323
+ this._lastWasIdle = false; // take never synthesizes idle
324
+ const avail = this.size;
325
+ if (n <= 0 || avail === 0) { return []; }
326
+ const count = Math.min(n, avail);
327
+ const start = this._head;
328
+ const out = this._items.slice(start, start + count);
329
+ this._lastRenderTime = this._renderTimes[start + count - 1]; // newest taken input's stamps
330
+ this._lastReckonTime = this._reckonTimes[start + count - 1];
331
+ if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[start + count - 1]; }
332
+ this._head += count;
333
+ this.consumedCount += count;
334
+ this.compact();
335
+ return out;
336
+ }
337
+
338
+ /**
339
+ * Iterate pending inputs one at a time (per-yield ack + stamp updates), or
340
+ * exactly one synthesized idle frame on an empty buffer with a policy in
341
+ * effect. See {@link InputAccessor.consume}.
342
+ *
343
+ * Returns a POOLED iterator (reused across calls — no generator frame, no
344
+ * per-call allocation) that consumes at most the pending count snapshotted at
345
+ * the call — never past the live tail — plus one optional trailing idle frame.
346
+ * The cursor advances per `next()`, so `break` (which calls `return()`)
347
+ * leaves the rest buffered and compacts. A nested
348
+ * `consume()` of the SAME buffer while one is live falls back to a fresh
349
+ * generator so the pooled `_iterRes` isn't clobbered (nesting is meaningless —
350
+ * both share the cursor — but it must not corrupt).
351
+ */
352
+ consume(opts?: ConsumeOptions<I>): IterableIterator<I> {
353
+ const empty = this.size === 0;
354
+ const idle = empty ? this.idleFrameOnEmpty(opts) : undefined;
355
+ if (empty && idle === undefined) { this._lastWasIdle = false; return DONE_ITERATOR as IterableIterator<I>; }
356
+ // A nested consume() of this same buffer would clobber the pooled iterator's
357
+ // shared state → hand the rare case a fresh generator instead.
358
+ if (this._iterActive) { return this.consumeGen(idle); }
359
+ this._iterActive = true;
360
+ this._iterIdle = idle; // one trailing idle frame, or undefined
361
+ this._iterRemaining = this.size; // count snapshot — a (hypothetical) mid-loop push isn't consumed this pass
362
+ return this.ensureIter();
363
+ }
364
+
365
+ [Symbol.iterator](): IterableIterator<I> {
366
+ return this.consume();
367
+ }
368
+
369
+ /** Lazily mint the reused iterator. Closures over `this` so it reads the
370
+ * private cursor directly; one `_iterRes` is reused — read each result before
371
+ * the next `next()`, as `for..of` / spread / `Array.from` all do. */
372
+ private ensureIter(): IterableIterator<I> {
373
+ if (this._iter !== undefined) { return this._iter; }
374
+ const self = this;
375
+ const res = this._iterRes;
376
+ const finish = (): IteratorResult<I> => {
377
+ self.compact();
378
+ self._iterActive = false;
379
+ self._iterRemaining = 0;
380
+ self._iterIdle = undefined;
381
+ res.value = undefined;
382
+ res.done = true;
383
+ return res as IteratorResult<I>;
384
+ };
385
+ this._iter = {
386
+ [Symbol.iterator]() { return this; },
387
+ next(): IteratorResult<I> {
388
+ // `size > 0` re-checks the live tail: a mid-loop next()/take()/clear()
389
+ // can only shorten the pass, never make it read past the end.
390
+ if (self._iterRemaining > 0 && self.size > 0) { // a buffered input
391
+ self._iterRemaining--;
392
+ res.value = self.stepHead();
393
+ res.done = false;
394
+ return res as IteratorResult<I>;
395
+ }
396
+ if (self._iterIdle !== undefined) { // one trailing idle frame
397
+ self._lastWasIdle = true;
398
+ res.value = self._iterIdle;
399
+ self._iterIdle = undefined;
400
+ res.done = false;
401
+ return res as IteratorResult<I>;
402
+ }
403
+ return finish();
404
+ },
405
+ return(): IteratorResult<I> { return finish(); }, // `break` → compact + release
406
+ };
407
+ return this._iter;
408
+ }
409
+
410
+ /** Re-entrant fallback: a fresh generator for a nested `consume()` of this same
411
+ * buffer (the pooled iterator is single-active). Same accounting + compaction. */
412
+ private *consumeGen(idleFrame: I | undefined): IterableIterator<I> {
413
+ let remaining = this.size; // count-based walk, same reason as the pooled pass
414
+ try {
415
+ while (remaining-- > 0 && this.size > 0) { yield this.stepHead(); }
416
+ if (idleFrame !== undefined) { this._lastWasIdle = true; yield idleFrame; }
417
+ } finally {
418
+ this.compact();
419
+ }
420
+ }
421
+
422
+ peek(): I[] {
423
+ return this._items.slice(this._head);
424
+ }
425
+
426
+ at(value: number): I | undefined {
427
+ if (this._seqField === undefined) { return undefined; }
428
+ for (let i = this._head; i < this._items.length; i++) {
429
+ if ((this._items[i] as any)[this._seqField] === value) { return this._items[i]; }
430
+ }
431
+ return undefined;
432
+ }
433
+
434
+ get size(): number {
435
+ return this._items.length - this._head;
436
+ }
437
+
438
+ /** Render time (server-clock ms) of the most recently drained input; `0`
439
+ * until the first render-time-stamped input is drained. */
440
+ get renderTime(): number {
441
+ return this._lastRenderTime;
442
+ }
443
+
444
+ /** Reckon-display stamp of the most recently consumed input — the client's
445
+ * serverNow estimate when it sampled that input, i.e. the EXACT instant its
446
+ * forward-reckoned entities were displayed at. Same consume semantics as
447
+ * {@link renderTime}. RAW: stays `0` until stamped — the resolved,
448
+ * always-usable value is the accessor's `reckonTime`
449
+ * (`room.inputs.get(sid)`); `rewind.lastSeenBy()`'s midpoint-reconstruction
450
+ * fallback depends on this raw `0`. */
451
+ get reckonTime(): number {
452
+ return this._lastReckonTime;
453
+ }
454
+
455
+ /** Seq VALUE of the last consumed input — the reconciliation ack sent to the
456
+ * client. Reliable (no wire seq tracked): falls back to {@link consumedCount}
457
+ * for free. Unreliable: the framework wire seq, so a fully-dropped input doesn't
458
+ * make the ack lag the client's sent seq by the lost count. `0` before the first
459
+ * consume. */
460
+ get ackSeq(): number {
461
+ return this._seqs !== undefined ? this._lastConsumedSeq : this.consumedCount;
462
+ }
463
+
464
+ /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */
465
+ get wasIdle(): boolean {
466
+ return this._lastWasIdle;
467
+ }
468
+
469
+ clear(): void {
470
+ // Cleared inputs count as consumed: advance both the count and the seq-value ack
471
+ // past them so the client's pending set drains (capture the newest seq before truncate).
472
+ if (this._seqs !== undefined && this._items.length > 0) { this._lastConsumedSeq = this._seqs[this._items.length - 1]; }
473
+ this.consumedCount += this.size;
474
+ this.truncate();
475
+ this._lastSeq = -Infinity;
476
+ this._iterActive = false; // recovery hatch if a consume() iterator was abandoned unclosed
477
+ this._iterRemaining = 0; // an abandoned iterator must not consume post-clear pushes
478
+ this._iterIdle = undefined;
479
+ }
480
+ }
481
+
482
+ /**
483
+ * Default per-client accessor. Reads `_input` and `_inputBuffer` off the
484
+ * client at access time — both are nullable until the room declares input
485
+ * via `defineInput()`. Cached as `client._inputAccessor` at join, so
486
+ * `room.inputs.get(sessionId)` is a Map lookup + property read.
487
+ *
488
+ * @internal
489
+ */
490
+ export class InputAccessorImpl<I = any> implements InputAccessor<I> {
491
+ private _client: ClientPrivate;
492
+ /** Current room time (`clock.elapsedTime`) — resolves the {@link reckonTime}
493
+ * fallback. Threaded by `RoomInput.allocate()`; optional so bare
494
+ * constructions (tests) keep the raw 0. */
495
+ private _nowOf?: () => number;
496
+ constructor(client: ClientPrivate, nowOf?: () => number) {
497
+ this._client = client;
498
+ this._nowOf = nowOf;
499
+ }
500
+ get latest(): I | undefined { return this._client._input as I | undefined; }
501
+ at(value: number): I | undefined { return this._client._inputBuffer?.at(value) as I | undefined; }
502
+ consume(opts?: ConsumeOptions<I>): IterableIterator<I> {
503
+ return (this._client._inputBuffer?.consume(opts) ?? DONE_ITERATOR) as IterableIterator<I>;
504
+ }
505
+ [Symbol.iterator](): IterableIterator<I> { return this.consume(); }
506
+ drain(opts?: ConsumeOptions<I>): I[] { return (this._client._inputBuffer?.drain(opts) ?? []) as I[]; }
507
+ next(): I | undefined;
508
+ next(opts: { idle: IdleInput<I> }): I;
509
+ next(opts?: ConsumeOptions<I>): I | undefined { return this._client._inputBuffer?.next(opts) as I | undefined; }
510
+ take(n: number): I[] { return (this._client._inputBuffer?.take(n) ?? []) as I[]; }
511
+ peek(): I[] { return (this._client._inputBuffer?.peek() ?? []) as I[]; }
512
+ get size(): number { return this._client._inputBuffer?.size ?? 0; }
513
+ get consumedCount(): number { return this._client._inputBuffer?.consumedCount ?? 0; }
514
+ get wasIdle(): boolean { return this._client._inputBuffer?.wasIdle ?? false; }
515
+ clear(): void { this._client._inputBuffer?.clear(); }
516
+ get renderTime(): number { return this._client._inputBuffer?.renderTime ?? 0; }
517
+ /** @internal RAW reckon stamp (0 until stamped). The rewind binding reads
518
+ * THIS, not the resolved getter below: `Rewind._aim`'s midpoint fallback
519
+ * must still see 0 for unstamped clients (a resolved value would silently
520
+ * take the direct-stamp clamp path). */
521
+ get rawReckonTime(): number { return this._client._inputBuffer?.reckonTime ?? 0; }
522
+ get reckonTime(): number {
523
+ const raw = this._client._inputBuffer?.reckonTime ?? 0;
524
+ return raw > 0 ? raw : this._nowOf !== undefined ? this._nowOf() : 0;
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Returned by `room.inputs.get(sessionId)` for unknown sessions and for rooms
530
+ * that didn't call `defineInput()`.
531
+ *
532
+ * @internal
533
+ */
534
+ export const NO_OP_INPUT_ACCESSOR: InputAccessor<any> = Object.freeze({
535
+ latest: undefined,
536
+ at: () => undefined,
537
+ consume: () => DONE_ITERATOR,
538
+ [Symbol.iterator]: () => DONE_ITERATOR,
539
+ drain: () => [],
540
+ next: () => undefined,
541
+ take: () => [],
542
+ peek: () => [],
543
+ size: 0,
544
+ consumedCount: 0,
545
+ wasIdle: false,
546
+ clear: () => {},
547
+ renderTime: 0,
548
+ reckonTime: 0, // stays 0 — an unknown session / input-less room has no clock to resolve against
549
+ });