@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,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/Rewind.ts"],
4
+ "sourcesContent": ["import { $values, type MapSchema, type ArraySchema, type SetSchema } from \"@colyseus/schema\";\nimport { $METADATA } from \"./utils/Utils.ts\";\n\nconst DEFAULT_MAX_REWIND_MS = 500;\n/** Ring-sizing fallback when the record cadence isn't supplied (manual `record(now)`\n * without a hint). `allowRewindState` feeds the real sim interval, so this only\n * matters for ad-hoc manual use. */\nconst DEFAULT_SAMPLE_INTERVAL_MS = 1000 / 60;\n\n// Hot record() path: dense `$values[index]` is ~15\u00D7 faster than `inst[fieldName]`; entity symbol prop ~8\u00D7 faster than a WeakMap.\n/** Per-entity history, under this private symbol ON the entity. Symbol-keyed so it's\n * invisible to Object.keys / `assign` / `clone`, and GC'd with the entity. */\nconst $HISTORY = Symbol(\"rewind.history\");\n\n/** Keys of T whose value type is `number` \u2014 the only rewindable fields. */\ntype NumericKeys<T> = { [K in keyof T]-?: T[K] extends number ? K : never }[keyof T] & string;\n/** A Colyseus collection whose element type is `E`. Inferring `E` from the live\n * collection the caller passes is what lets `fields` narrow with zero state-type\n * plumbing. */\ntype Collection<E> = MapSchema<E> | ArraySchema<E> | SetSchema<E>;\n\n/** Options for {@link Rewind.get} / {@link Room.allowRewindState}. */\nexport interface RewindOptions {\n /** Default rewind window (ms) for attaches that don't pass their own \u2014 sizes the\n * per-entity history ring. Per-attach `maxRewindMs` overrides it. Default 500. */\n maxRewindMs?: number;\n}\n\n/** Field's `$values` index from the schema metadata (`metadata[name]` = index), or\n * -1 if unknown. Resolved ONCE per constructor (cold path), never per tick. */\nfunction fieldIndexOf(instance: object, field: string): number {\n const md = (instance.constructor as any)[$METADATA] as Record<string, unknown> | undefined;\n const idx = md?.[field];\n return typeof idx === \"number\" ? idx : -1;\n}\n\n/** The lag-comp technique an attach-group rewinds to \u2014 the TIMELINE the client\n * displays those targets on. `\"snapshot\"` (default): the renderTime stamp (what\n * a lerping/damped client shows, behind real time). `\"reckon\"`: the reckonTime\n * stamp (what a forward-extrapolated client shows, \u2248 serverNow). Declared at\n * {@link Rewind.attachAll}, not on the schema. */\nexport type RewindMode = \"snapshot\" | \"reckon\";\n\n/**\n * Per-entity ring of recent field snapshots. `valueAt(time, col)` reconstructs\n * one field's recorded PATH at an arbitrary past time \u2014 `linear` interp for\n * continuous motion (patrol, a sine bob), or `step` (hold the last value) for\n * discrete motion (teleport snaps), where a lerp would smear across the jump.\n */\nclass EntityHistory {\n readonly fields: readonly string[];\n /** The attach-group's `mode: \"reckon\"` technique, mirrored here so a view can\n * pick its aim time PER FIELD (each field's covering history carries it). */\n readonly reckoned: boolean;\n /** The attach-group this history belongs to. One entity can have several\n * histories (attached to multiple groups over disjoint fields); `record()`\n * finds the right one by this id. */\n readonly groupId: number;\n /** Each tracked field's index into the entity's dense `$values` array \u2014\n * resolved per CONSTRUCTOR (mixed-type collections differ per type). */\n private readonly fieldIdx: readonly number[];\n private readonly cap: number;\n private readonly t: Float64Array;\n private readonly cols: Float64Array[]; // one column per field\n private readonly step: boolean; // hold (vs lerp) between samples\n private head = 0; // next write slot\n private count = 0;\n\n constructor(fields: readonly string[], fieldIdx: readonly number[], maxRewindMs: number, sampleIntervalMs: number, step: boolean, reckoned: boolean, groupId: number) {\n this.fields = fields;\n this.fieldIdx = fieldIdx;\n this.step = step;\n this.reckoned = reckoned;\n this.groupId = groupId;\n this.cap = Math.max(2, Math.ceil(maxRewindMs / sampleIntervalMs) + 4);\n this.t = new Float64Array(this.cap);\n this.cols = fields.map(() => new Float64Array(this.cap));\n }\n\n /** `values` = the entity's dense `$values` array. Direct array reads \u2014 no\n * per-field megamorphic accessor. */\n record(time: number, values: ArrayLike<number>): void {\n const fieldIdx = this.fieldIdx;\n this.t[this.head] = time;\n for (let f = 0; f < fieldIdx.length; f++) this.cols[f][this.head] = values[fieldIdx[f]];\n this.head = (this.head + 1) % this.cap;\n if (this.count < this.cap) this.count++;\n }\n\n /** Interpolated value of column `col` at `time`, clamped to the retained range. */\n valueAt(time: number, col: number): number {\n const c = this.cols[col];\n const oldest = (this.head - this.count + this.cap) % this.cap;\n if (time <= this.t[oldest]) return c[oldest];\n const newest = (this.head - 1 + this.cap) % this.cap;\n if (time >= this.t[newest]) return c[newest];\n let prev = oldest;\n for (let i = 1; i < this.count; i++) {\n const idx = (oldest + i) % this.cap;\n if (this.t[idx] >= time) {\n if (this.step) return c[prev]; // discrete: hold the value before `time`\n const t0 = this.t[prev], t1 = this.t[idx];\n const a = t1 > t0 ? (time - t0) / (t1 - t0) : 0;\n return c[prev] + (c[idx] - c[prev]) * a;\n }\n prev = idx;\n }\n return c[newest]; // unreachable: `newest` guard above covers it\n }\n}\n\n/** The histories an entity accumulates \u2014 one per attach-group it belongs to\n * (length 1 in the common single-group case). Stored under {@link $HISTORY} on\n * the entity; GC'd with it. */\ntype EntityHistories = EntityHistory[];\n\n/** Find the history covering `field` (the group that recorded it), or undefined\n * \u2192 read live. Disjoint field sets across groups make the first match the only\n * match; the scan is length-1 in every common case. */\nfunction historyForField(instance: object, field: string): EntityHistory | undefined {\n const arr = (instance as any)[$HISTORY] as EntityHistories | undefined;\n if (arr === undefined) return undefined;\n for (let i = 0; i < arr.length; i++) {\n if (arr[i].fields.indexOf(field) >= 0) return arr[i];\n }\n return undefined;\n}\n\n/** How `valueAt` reconstructs a value between recorded samples: `linear` interp\n * (continuous motion) or `step` = hold the last sample (discrete motion). */\ntype Interp = \"linear\" | \"step\";\n\n/**\n * A read-only view of the tracked world at ONE past time \u2014 the rewound state a\n * hit test reads instead of live positions. Created by {@link Rewind.at} /\n * {@link Rewind.lastSeenBy}, which bake in the `maxRewindMs` clamp and the\n * live-fallback so callers never re-implement either.\n *\n * The view assumes NOTHING about your schema's field names \u2014 you name the\n * fields (and therefore the shape) at the call site:\n *\n * ```ts\n * const seen = rewind.lastSeenBy(shooterSessionId);\n * // read fields directly\u2026\n * overlaps(bullet, seen.value(target, \"x\"), seen.value(target, \"y\"));\n * // \u2026or batch them into an object shaped by YOUR field list:\n * const pos = seen.read(target, [\"x\", \"y\"]); // { x, y }\n * seen.read(enemy, [\"x\", \"y\"], this.seenScratch); // fill + return a reused scratch\n * ```\n *\n * By default `at`/`lastSeenBy` re-aim and return the Rewind's own internal\n * view \u2014 the usual \"one view at a time, read it right away\" flow is zero-alloc\n * AND zero-setup (the server is single-threaded; nothing interleaves a\n * synchronous read). Need more than one view alive at once (compare two\n * shooters' perspectives, A/B a rewind window)? Pass your own instance as\n * their `out` \u2014 it is re-aimed and returned instead of the shared one:\n *\n * ```ts\n * const a = rewind.lastSeenBy(shooterA); // shared default view\n * const b = rewind.lastSeenBy(shooterB, new RewindView()); // independent second view\n * ```\n *\n * Don't store a view across calls or ticks: the default is re-aimed by the\n * next `at`/`lastSeenBy`, and ANY view's clamp was computed against\n * `lastRecordedAt`, so it goes stale at the next `record()` regardless.\n */\nexport class RewindView {\n /** Bound (and re-bound) by {@link _retarget} \u2014 a bare `new RewindView()` is\n * un-aimed scratch until it first passes through at()/lastSeenBy(). */\n private rewind?: Rewind;\n private _time = 0;\n private _reckonTime = 0;\n\n /** The clamped server-time (ms) this view reads at \u2014 after the maxRewindMs\n * clamp and the live (newest-sample) fallback. Mostly for logging/debug. */\n get time(): number { return this._time; }\n\n /** The clamped server-time (ms) `mode: \"reckon\"` groups read at \u2014 the\n * client's reconstructed simulation instant, not the raw stamp (see\n * {@link Rewind.at}). Always a resolved instant: a clamped direct stamp,\n * or the midpoint/live reconstruction when unstamped. `0` only before the\n * first `record()`. */\n get reckonTime(): number { return this._reckonTime; }\n\n /** @internal Aim at a rewind + clamped times ({@link Rewind.at} owns the clamps). */\n _retarget(rewind: Rewind, at: number, reckonAt: number): this {\n this.rewind = rewind;\n this._time = at;\n this._reckonTime = reckonAt;\n return this;\n }\n\n /** Rewound value of a numeric `field` on `entity` (live if it isn't tracked). */\n value<T extends object>(entity: T, field: NumericKeys<T>): number {\n if (this.rewind === undefined) {\n throw new Error(\"RewindView is not aimed \u2014 obtain it from rewind.at()/lastSeenBy(), or pass it to them as `out`.\");\n }\n // The field's covering attach-group picks the timeline: mode:\"reckon\" reads\n // at the reckon-display instant, mode:\"snapshot\" at the renderTime stamp.\n const h = historyForField(entity, field);\n if (h === undefined) return (entity as Record<string, number>)[field]; // untracked \u2192 live\n return h.valueAt(h.reckoned ? this._reckonTime : this._time, h.fields.indexOf(field));\n }\n\n /**\n * Batch {@link value} reads: the `fields` YOU list define the result's shape\n * (`Record<field, number>`). Pass `out` to fill (and return) a reused scratch\n * instead of allocating \u2014 its properties beyond `fields` are left untouched,\n * so a scratch can carry extra context (an `alive` flag, say).\n */\n read<T extends object, F extends NumericKeys<T>, O extends Record<F, number> = Record<F, number>>(\n entity: T,\n fields: readonly F[],\n out?: O,\n ): O {\n const o = (out ?? {}) as Record<F, number>;\n for (let i = 0; i < fields.length; i++) o[fields[i]] = this.value(entity, fields[i]);\n return o as O;\n }\n}\n\n/** Array-form `fields` resolved against one constructor: names with a known\n * `$values` index, in lock-step. Fields a type doesn't declare are dropped\n * (they read live) instead of recording `values[-1]` garbage. */\ninterface ResolvedFields { fields: readonly string[]; idx: readonly number[]; }\n\ninterface TrackedGroup {\n entities: () => Iterable<object>;\n fields: readonly string[] | ((entity: any) => readonly string[]);\n /** Per-constructor resolution of array-form `fields` \u2014 one entry per entity\n * type seen in the group (mixed-type collections differ per type). */\n resolvedByCtor: Map<Function, ResolvedFields>;\n maxRewindMs: number;\n interpolate: Interp | ((entity: any) => Interp);\n /** `true` when this group's `mode` is `\"reckon\"` (vs the `\"snapshot\"` default). */\n reckoned: boolean;\n /** Stable id (push index) \u2014 links an entity's per-group {@link EntityHistory}\n * back to its group so the same collection can be attached more than once. */\n groupId: number;\n}\n\n/**\n * Per-attach options for {@link Rewind.attachAll} / {@link Rewind.attach}.\n */\ninterface AttachOptions<E> {\n /** Numeric fields to record per tick. An array applies to every type in the\n * collection (fields a type lacks are skipped \u2014 they read live); a per-entity\n * fn picks the list per entity, mirroring `interpolate`'s fn form. */\n fields: readonly NumericKeys<E>[] | ((entity: E) => readonly NumericKeys<E>[]);\n maxRewindMs?: number;\n /** How `valueAt` reconstructs between samples (a mode or a per-entity fn,\n * default `linear`) \u2014 use `step` for discrete motion (e.g. teleporters). */\n interpolate?: Interp | ((entity: E) => Interp);\n /**\n * The lag-comp TIMELINE these fields rewind to \u2014 must match how the CLIENT\n * displays this target (\"what you see is what you hit\"):\n * - `\"snapshot\"` (default): rewind to the client's `renderTime` \u2014 for\n * targets it shows INTERPOLATED (Predict `lerp`/`damped`), behind real\n * time by its interp buffer + rtt/2.\n * - `\"reckon\"`: rewind to the client's `reckonTime` (\u2248 its serverNow) \u2014 for\n * targets it forward-extrapolates (Predict `reckon`).\n * Attach the same collection twice with disjoint `fields` to mix techniques.\n * The room ships exactly the stamp(s) its attached groups need (see the\n * handshake derivation in `Room`).\n */\n mode?: RewindMode;\n}\n\n/**\n * Server-side lag compensation \u2014 the dual of the client's `Predict`. Where\n * `Predict` forward-reckons entities it RECEIVES, `Rewind` records the recent\n * positions of entities it OWNS and rewinds field reads to a past (client\n * render) time, so a hit test judges against where the client actually SAW an\n * entity \u2014 not where it has slid to ~RTT later.\n *\n * Prefer {@link Room.allowRewindState}, which creates a `Rewind` and records it\n * automatically each simulation tick:\n *\n * @example\n * ```ts\n * onCreate() {\n * const rewind = this.allowRewindState({ maxRewindMs: 500 });\n * rewind.attachAll(this.state.enemies, { fields: [\"x\", \"y\"] }); // fields \u2190 Enemy's numeric keys\n * this.setTimestep((dt) => { ...move enemies... }, 1000 / 30);\n * // framework calls rewind.record() after each tick.\n * }\n * // in your hit test, with the client's renderTime:\n * const seenX = rewind.valueAt(enemy, renderTime, \"x\");\n * ```\n *\n * `attachAll` takes the live collection (not a string key), so the element type\n * \u2014 and the legal `fields` / `valueAt` field names \u2014 are inferred with no\n * state-type generic. Entities are keyed by object identity \u2014 removed entities\n * and their history are reclaimed automatically.\n *\n * The rewind TIMELINE is declared per attach-group via `attachAll(coll, { mode })`:\n * `\"snapshot\"` (default) reads at the client's `renderTime` stamp, `\"reckon\"` at\n * its `reckonTime` (see {@link at}). Not-attached = not rewound (reads are live)\n * \u2014 there is no \"none\". The same collection may be attached more than once with\n * disjoint `fields` to put different fields on different timelines. The room\n * ships exactly the stamp(s) these groups need (handshake derivation reads\n * {@link timelineMode}); the client declares its display mode independently.\n */\nexport class Rewind {\n private static readonly byRoom = new WeakMap<object, Rewind>();\n\n /** One `Rewind` per room (idempotent). `room` is only the cache key. */\n static get(room: object, opts?: RewindOptions): Rewind {\n let r = Rewind.byRoom.get(room);\n if (r === undefined) { r = new Rewind(opts?.maxRewindMs ?? DEFAULT_MAX_REWIND_MS); Rewind.byRoom.set(room, r); }\n return r;\n }\n\n private readonly groups: TrackedGroup[] = [];\n private readonly defaultMaxRewindMs: number;\n private _sampleIntervalMs = DEFAULT_SAMPLE_INTERVAL_MS;\n private _lastRecordedAt = -1;\n /** Resolves a client's auto-stamped render time (set by `Room.allowRewindState`\n * when a `mode:\"snapshot\"` group is attached); powers {@link lastSeenBy}. */\n private _renderTimeOf?: (sessionId: string) => number;\n /** Resolves a client's auto-stamped reckon-display instant (its serverNow\n * estimate at input-sample time). When present (> 0), {@link lastSeenBy}\n * reads `mode:\"reckon\"` groups AT this stamp directly \u2014 exact regardless\n * of the client's clock/RTT-estimation error (it displayed f(est), we read\n * f(est)) \u2014 instead of reconstructing it via the midpoint. */\n private _reckonTimeOf?: (sessionId: string) => number;\n /** Resolves the CURRENT server time (set by `Room.allowRewindState`) \u2014 the\n * reckon midpoint's \"now\" anchor in {@link at}. Without it, the anchor falls\n * back to `lastRecordedAt`, which is one tick stale at hit-test time. */\n private _nowOf?: () => number;\n /** Default view returned by at/lastSeenBy when no `out` is given \u2014 one per\n * Rewind, re-aimed per call (zero alloc, zero userland setup). */\n private readonly _view = new RewindView();\n\n private constructor(defaultMaxRewindMs: number) { this.defaultMaxRewindMs = defaultMaxRewindMs; }\n\n /** The default rewind window (ms). Use it to bound a hit test:\n * `Math.max(renderTime, now - rewind.maxRewindMs)`. */\n get maxRewindMs(): number { return this.defaultMaxRewindMs; }\n /** Server time of the last {@link record} (or -1). The auto-record skips a tick\n * whose time was already recorded manually \u2014 your `record()` wins. */\n get lastRecordedAt(): number { return this._lastRecordedAt; }\n\n /** Track every entity in a collection (Map/Array/Set schema). `fields` narrows\n * to its element's numeric fields. `interpolate` (a mode or a per-entity fn,\n * default `linear`) picks how `valueAt` reconstructs between samples \u2014 use\n * `step` for discrete-motion entities (e.g. teleporters). `mode` picks the\n * lag-comp timeline (default `\"snapshot\"`; see {@link AttachOptions}). */\n attachAll<E extends object>(\n collection: Collection<E>,\n opts: AttachOptions<E>,\n ): this {\n const c = collection as unknown as { values(): Iterable<object> };\n this.groups.push({ entities: () => c.values(), fields: opts.fields, resolvedByCtor: new Map(), maxRewindMs: opts.maxRewindMs ?? this.defaultMaxRewindMs, interpolate: opts.interpolate ?? \"linear\", reckoned: opts.mode === \"reckon\", groupId: this.groups.length });\n return this;\n }\n\n /** Track a single entity (e.g. a boss). `fields` narrows to its numeric fields. */\n attach<E extends object>(instance: E, opts: AttachOptions<E>): this {\n const one: object[] = [instance]; // reused; no per-tick alloc\n this.groups.push({ entities: () => one, fields: opts.fields, resolvedByCtor: new Map(), maxRewindMs: opts.maxRewindMs ?? this.defaultMaxRewindMs, interpolate: opts.interpolate ?? \"linear\", reckoned: opts.mode === \"reckon\", groupId: this.groups.length });\n return this;\n }\n\n /**\n * Snapshot every tracked entity at `now`. Call once per tick, AFTER they move \u2014\n * {@link Room.allowRewindState} does this for you. `sampleIntervalMs` (the gap\n * between records) sizes the history rings; the framework passes the sim\n * interval. Calling this yourself during a tick suppresses that tick's\n * auto-record (see {@link lastRecordedAt}).\n */\n record(now: number, sampleIntervalMs?: number): void {\n if (sampleIntervalMs !== undefined && sampleIntervalMs > 0) this._sampleIntervalMs = sampleIntervalMs;\n this._lastRecordedAt = now;\n for (const g of this.groups) {\n for (const e of g.entities()) {\n const t = e as any; // private-symbol access on a foreign schema instance\n let arr = t[$HISTORY] as EntityHistories | undefined;\n if (arr === undefined) { arr = []; t[$HISTORY] = arr; }\n let h: EntityHistory | undefined;\n for (let i = 0; i < arr.length; i++) { if (arr[i].groupId === g.groupId) { h = arr[i]; break; } }\n if (h === undefined) { h = this.createHistory(g, e); arr.push(h); } // cold: once per (entity, group)\n h.record(now, t[$values] as ArrayLike<number>);\n }\n }\n }\n\n /** Cold path \u2014 first time an entity is seen by `record()` for a given group.\n * Resolves the field\u2192`$values` indices (cached per constructor for array-form\n * `fields`; fn-form resolves per entity) and bakes in the group's `mode`. */\n private createHistory(g: TrackedGroup, e: object): EntityHistory {\n let rf: ResolvedFields;\n if (typeof g.fields === \"function\") {\n rf = this.resolveFields(e, g.fields(e));\n } else {\n let cached = g.resolvedByCtor.get(e.constructor);\n if (cached === undefined) {\n cached = this.resolveFields(e, g.fields);\n g.resolvedByCtor.set(e.constructor, cached);\n }\n rf = cached;\n }\n const interp = typeof g.interpolate === \"function\" ? g.interpolate(e) : g.interpolate;\n return new EntityHistory(rf.fields, rf.idx, g.maxRewindMs, this._sampleIntervalMs, interp === \"step\", g.reckoned, g.groupId);\n }\n\n /** Keep only the fields this entity's type declares (unknown \u2192 read live). */\n private resolveFields(e: object, names: readonly string[]): ResolvedFields {\n const fields: string[] = [];\n const idx: number[] = [];\n for (const name of names) {\n const i = fieldIndexOf(e, name);\n if (i >= 0) { fields.push(name); idx.push(i); }\n }\n return { fields, idx };\n }\n\n /**\n * `instance`'s `field` value at past `time` (interpolated from history). Falls\n * back to the live value when the entity has no history yet, or the field\n * isn't tracked.\n */\n valueAt<T extends object>(instance: T, time: number, field: NumericKeys<T>): number {\n const h = historyForField(instance, field);\n if (h === undefined) return (instance as Record<string, number>)[field];\n return h.valueAt(time, h.fields.indexOf(field));\n }\n\n /**\n * Which timeline(s) the attached groups rewind to \u2014 `reckon` true iff any\n * group is `mode:\"reckon\"`, `snapshot` true iff any is `mode:\"snapshot\"`. The\n * room reads this once (groups are declared in `onCreate`, before any join) to\n * pick which stamp(s) the client must ship: reckon-only / render-only / both /\n * none. @internal\n */\n timelineMode(): { reckon: boolean; snapshot: boolean } {\n let reckon = false, snapshot = false;\n for (const g of this.groups) {\n if (g.reckoned) reckon = true; else snapshot = true;\n }\n return { reckon, snapshot };\n }\n\n /**\n * @internal Wire a resolver from sessionId \u2192 that client's auto-stamped\n * `renderTime`. Called by {@link Room.allowRewindState} so {@link lastSeenBy}\n * works for `mode:\"snapshot\"` groups; auto-enabled by attaching one.\n */\n bindRenderTime(resolver: (sessionId: string) => number): void {\n this._renderTimeOf = resolver;\n }\n\n /**\n * @internal Wire a resolver for the CURRENT server time (ms, same epoch as\n * `record` times). Called by {@link Room.allowRewindState}; standalone users\n * (tests/harnesses) should bind their own. Anchors the reckon midpoint in\n * {@link at} at the true processing instant \u2014 the `lastRecordedAt` fallback\n * is one tick stale by hit-test time, biasing the aim ~half a tick early:\n * imperceptible on slow horizontal motion, but enough to flip knife-edge\n * stomp/hit verdicts on fast vertical movers (a bobbing jumper).\n */\n bindNow(resolver: () => number): void {\n this._nowOf = resolver;\n }\n\n /**\n * @internal Wire a resolver from sessionId \u2192 that client's auto-stamped\n * reckon-display instant (`input(sid).reckonTime`). Called by\n * {@link Room.allowRewindState}. With it, {@link lastSeenBy} aims\n * `mode:\"reckon\"` groups at the EXACT instant the client displayed them\n * (immune to its RTT-estimation error); without it (or while the stamp is\n * still 0), the midpoint reconstruction in {@link at} is the fallback.\n */\n bindReckonTime(resolver: (sessionId: string) => number): void {\n this._reckonTimeOf = resolver;\n }\n\n /**\n * A {@link RewindView} of the tracked world at `time` (an acting client's render\n * time), with the two things every hit test re-implements baked in:\n * - **clamp** to `[lastRecordedAt \u2212 maxRewindMs, lastRecordedAt]` \u2014 an\n * anti-spoof / clock-skew bound (a client can't rewind arbitrarily far), and\n * - **live fallback**: `time <= 0` (the client's clock hasn't synced) \u2192 the\n * newest recorded sample (\u2248 current position).\n *\n * Sugar over {@link valueAt}; pass the render time yourself (e.g. from\n * `input(sid).renderTime`, or a value stored on the entity). For the common\n * \"rewind to a specific client's view\" case use {@link lastSeenBy}.\n *\n * Re-aims and returns this Rewind's internal view by default \u2014 zero alloc,\n * nothing to declare. Pass `out` to aim a view of your own instead; needed\n * only to hold several views at once \u2014 see the {@link RewindView} doc.\n */\n at(time: number, out?: RewindView): RewindView {\n return this._aim(time, 0, out);\n }\n\n /**\n * Shared aiming: clamp the snapshot-timeline `time`, and resolve the reckon\n * timeline either from the DIRECT `reckonStamp` (the instant the client's\n * forward-reckoned entities were displayed at \u2014 exact, immune to the\n * client's RTT-estimation error) or, when absent (0), by reconstruction.\n */\n private _aim(time: number, reckonStamp: number, out?: RewindView): RewindView {\n const newest = this._lastRecordedAt;\n const oldest = newest - this.defaultMaxRewindMs;\n // time<=0 \u2192 not synced yet \u2192 read live (newest). Else clamp into the window.\n const at = time <= 0 ? newest : (time < oldest ? oldest : time > newest ? newest : time);\n // mode:\"reckon\" groups display forward-extrapolated to \u2248 the client's\n // serverNow \u2014 rewinding them to the raw snapshot stamp would double-\n // compensate (client extrapolates forward + server rewinds back = a\n // full-RTT ghost in the entity's past).\n let reckonAt: number;\n if (reckonStamp > 0) {\n // Direct stamp: read at exactly what the client displayed. The clamp is\n // the anti-spoof bound, same as the snapshot timeline's.\n reckonAt = reckonStamp < oldest ? oldest : reckonStamp > newest ? newest : reckonStamp;\n } else if (time <= 0) {\n reckonAt = newest;\n } else {\n // Reconstruction fallback (custom `at(time)` users / old clients): with\n // symmetric latency the client's instant is the midpoint of the stamp\n // and ARRIVAL \u2014 anchored at the bound \"now\" (the true processing\n // instant; the lastRecordedAt fallback is one tick stale by hit-test\n // time and biases the aim ~half a tick early \u2014 see bindNow). NOTE: the\n // stamp itself embeds the client's rtt/2 estimate, so this path inherits\n // its error \u2014 the direct stamp above is the accurate one.\n const anchor = this._nowOf !== undefined ? this._nowOf() : newest;\n const mid = (time + anchor) / 2;\n reckonAt = mid < oldest ? oldest : mid > newest ? newest : mid;\n }\n return (out ?? this._view)._retarget(this, at, reckonAt);\n }\n\n /**\n * A {@link RewindView} of the world as session `sessionId` LAST saw it \u2014\n * resolves the render time stamped on that client's most recently CONSUMED\n * input (hence \"last\": under a multi-frame `drain()` it is the newest frame's\n * stamp) and hands off to {@link at}. This is the \"what you see is what you\n * hit\" path:\n *\n * ```ts\n * const seen = this.rewind.lastSeenBy(shooterSessionId);\n * const hit = overlaps(bullet, seen.value(target, \"x\"), seen.value(target, \"y\"));\n * ```\n *\n * Requires the room's framework input (`this.defineInput(Input)`) \u2014 the\n * per-client stamp auto-enables from the `attachAll` `mode` of the groups you\n * rewind (declaration order vs `allowRewindState` doesn't matter). A client\n * that merely hasn't stamped yet (clock still syncing, unknown sessionId) is\n * NOT an error \u2014 it reads 0 and the view falls back to live. Use\n * {@link at} with an explicit time if you stamp render times yourself.\n *\n * Re-aims and returns this Rewind's internal view by default \u2014 zero alloc,\n * nothing to declare. Pass `out` to aim a view of your own instead; needed\n * only to hold several views at once \u2014 see the {@link RewindView} doc.\n */\n lastSeenBy(sessionId: string, out?: RewindView): RewindView {\n if (this._renderTimeOf === undefined) {\n throw new Error(\n \"Rewind.lastSeenBy(sessionId) needs the framework input API. Declare \" +\n \"`this.defineInput(Input)` (stamps auto-enable from your attachAll `mode`), \" +\n \"or call `at(time)` and pass the render time yourself.\",\n );\n }\n return this._aim(\n this._renderTimeOf(sessionId),\n this._reckonTimeOf !== undefined ? this._reckonTimeOf(sessionId) : 0,\n out,\n );\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA0E;AAC1E,mBAA0B;AAE1B,IAAM,wBAAwB;AAI9B,IAAM,6BAA6B,MAAO;AAK1C,IAAM,WAAW,uBAAO,gBAAgB;AAkBxC,SAAS,aAAa,UAAkB,OAAuB;AAC7D,QAAM,KAAM,SAAS,YAAoB,sBAAS;AAClD,QAAM,MAAM,KAAK,KAAK;AACtB,SAAO,OAAO,QAAQ,WAAW,MAAM;AACzC;AAeA,IAAM,gBAAN,MAAoB;AAAA,EAmBlB,YAAY,QAA2B,UAA6B,aAAqB,kBAA0B,MAAe,UAAmB,SAAiB;AAHtK;AAAA,SAAQ,OAAO;A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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,GAAG,MAAc,KAA8B;AAC7C,WAAO,KAAK,KAAK,MAAM,GAAG,GAAG;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,KAAK,MAAc,aAAqB,KAA8B;AAC5E,UAAM,SAAS,KAAK;AACpB,UAAM,SAAS,SAAS,KAAK;AAE7B,UAAM,KAAK,QAAQ,IAAI,SAAU,OAAO,SAAS,SAAS,OAAO,SAAS,SAAS;AAKnF,QAAI;AACJ,QAAI,cAAc,GAAG;AAGnB,iBAAW,cAAc,SAAS,SAAS,cAAc,SAAS,SAAS;AAAA,IAC7E,WAAW,QAAQ,GAAG;AACpB,iBAAW;AAAA,IACb,OAAO;AAQL,YAAM,SAAS,KAAK,WAAW,SAAY,KAAK,OAAO,IAAI;AAC3D,YAAM,OAAO,OAAO,UAAU;AAC9B,iBAAW,MAAM,SAAS,SAAS,MAAM,SAAS,SAAS;AAAA,IAC7D;AACA,YAAQ,OAAO,KAAK,OAAO,UAAU,MAAM,IAAI,QAAQ;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyBA,WAAW,WAAmB,KAA8B;AAC1D,QAAI,KAAK,kBAAkB,QAAW;AACpC,YAAM,IAAI;AAAA,QACR;AAAA,MAGF;AAAA,IACF;AACA,WAAO,KAAK;AAAA,MACV,KAAK,cAAc,SAAS;AAAA,MAC5B,KAAK,kBAAkB,SAAY,KAAK,cAAc,SAAS,IAAI;AAAA,MACnE;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,291 @@
1
+ import { type MapSchema, type ArraySchema, type SetSchema } from "@colyseus/schema";
2
+ /** Keys of T whose value type is `number` — the only rewindable fields. */
3
+ type NumericKeys<T> = {
4
+ [K in keyof T]-?: T[K] extends number ? K : never;
5
+ }[keyof T] & string;
6
+ /** A Colyseus collection whose element type is `E`. Inferring `E` from the live
7
+ * collection the caller passes is what lets `fields` narrow with zero state-type
8
+ * plumbing. */
9
+ type Collection<E> = MapSchema<E> | ArraySchema<E> | SetSchema<E>;
10
+ /** Options for {@link Rewind.get} / {@link Room.allowRewindState}. */
11
+ export interface RewindOptions {
12
+ /** Default rewind window (ms) for attaches that don't pass their own — sizes the
13
+ * per-entity history ring. Per-attach `maxRewindMs` overrides it. Default 500. */
14
+ maxRewindMs?: number;
15
+ }
16
+ /** The lag-comp technique an attach-group rewinds to — the TIMELINE the client
17
+ * displays those targets on. `"snapshot"` (default): the renderTime stamp (what
18
+ * a lerping/damped client shows, behind real time). `"reckon"`: the reckonTime
19
+ * stamp (what a forward-extrapolated client shows, ≈ serverNow). Declared at
20
+ * {@link Rewind.attachAll}, not on the schema. */
21
+ export type RewindMode = "snapshot" | "reckon";
22
+ /** How `valueAt` reconstructs a value between recorded samples: `linear` interp
23
+ * (continuous motion) or `step` = hold the last sample (discrete motion). */
24
+ type Interp = "linear" | "step";
25
+ /**
26
+ * A read-only view of the tracked world at ONE past time — the rewound state a
27
+ * hit test reads instead of live positions. Created by {@link Rewind.at} /
28
+ * {@link Rewind.lastSeenBy}, which bake in the `maxRewindMs` clamp and the
29
+ * live-fallback so callers never re-implement either.
30
+ *
31
+ * The view assumes NOTHING about your schema's field names — you name the
32
+ * fields (and therefore the shape) at the call site:
33
+ *
34
+ * ```ts
35
+ * const seen = rewind.lastSeenBy(shooterSessionId);
36
+ * // read fields directly…
37
+ * overlaps(bullet, seen.value(target, "x"), seen.value(target, "y"));
38
+ * // …or batch them into an object shaped by YOUR field list:
39
+ * const pos = seen.read(target, ["x", "y"]); // { x, y }
40
+ * seen.read(enemy, ["x", "y"], this.seenScratch); // fill + return a reused scratch
41
+ * ```
42
+ *
43
+ * By default `at`/`lastSeenBy` re-aim and return the Rewind's own internal
44
+ * view — the usual "one view at a time, read it right away" flow is zero-alloc
45
+ * AND zero-setup (the server is single-threaded; nothing interleaves a
46
+ * synchronous read). Need more than one view alive at once (compare two
47
+ * shooters' perspectives, A/B a rewind window)? Pass your own instance as
48
+ * their `out` — it is re-aimed and returned instead of the shared one:
49
+ *
50
+ * ```ts
51
+ * const a = rewind.lastSeenBy(shooterA); // shared default view
52
+ * const b = rewind.lastSeenBy(shooterB, new RewindView()); // independent second view
53
+ * ```
54
+ *
55
+ * Don't store a view across calls or ticks: the default is re-aimed by the
56
+ * next `at`/`lastSeenBy`, and ANY view's clamp was computed against
57
+ * `lastRecordedAt`, so it goes stale at the next `record()` regardless.
58
+ */
59
+ export declare class RewindView {
60
+ /** Bound (and re-bound) by {@link _retarget} — a bare `new RewindView()` is
61
+ * un-aimed scratch until it first passes through at()/lastSeenBy(). */
62
+ private rewind?;
63
+ private _time;
64
+ private _reckonTime;
65
+ /** The clamped server-time (ms) this view reads at — after the maxRewindMs
66
+ * clamp and the live (newest-sample) fallback. Mostly for logging/debug. */
67
+ get time(): number;
68
+ /** The clamped server-time (ms) `mode: "reckon"` groups read at — the
69
+ * client's reconstructed simulation instant, not the raw stamp (see
70
+ * {@link Rewind.at}). Always a resolved instant: a clamped direct stamp,
71
+ * or the midpoint/live reconstruction when unstamped. `0` only before the
72
+ * first `record()`. */
73
+ get reckonTime(): number;
74
+ /** @internal Aim at a rewind + clamped times ({@link Rewind.at} owns the clamps). */
75
+ _retarget(rewind: Rewind, at: number, reckonAt: number): this;
76
+ /** Rewound value of a numeric `field` on `entity` (live if it isn't tracked). */
77
+ value<T extends object>(entity: T, field: NumericKeys<T>): number;
78
+ /**
79
+ * Batch {@link value} reads: the `fields` YOU list define the result's shape
80
+ * (`Record<field, number>`). Pass `out` to fill (and return) a reused scratch
81
+ * instead of allocating — its properties beyond `fields` are left untouched,
82
+ * so a scratch can carry extra context (an `alive` flag, say).
83
+ */
84
+ read<T extends object, F extends NumericKeys<T>, O extends Record<F, number> = Record<F, number>>(entity: T, fields: readonly F[], out?: O): O;
85
+ }
86
+ /**
87
+ * Per-attach options for {@link Rewind.attachAll} / {@link Rewind.attach}.
88
+ */
89
+ interface AttachOptions<E> {
90
+ /** Numeric fields to record per tick. An array applies to every type in the
91
+ * collection (fields a type lacks are skipped — they read live); a per-entity
92
+ * fn picks the list per entity, mirroring `interpolate`'s fn form. */
93
+ fields: readonly NumericKeys<E>[] | ((entity: E) => readonly NumericKeys<E>[]);
94
+ maxRewindMs?: number;
95
+ /** How `valueAt` reconstructs between samples (a mode or a per-entity fn,
96
+ * default `linear`) — use `step` for discrete motion (e.g. teleporters). */
97
+ interpolate?: Interp | ((entity: E) => Interp);
98
+ /**
99
+ * The lag-comp TIMELINE these fields rewind to — must match how the CLIENT
100
+ * displays this target ("what you see is what you hit"):
101
+ * - `"snapshot"` (default): rewind to the client's `renderTime` — for
102
+ * targets it shows INTERPOLATED (Predict `lerp`/`damped`), behind real
103
+ * time by its interp buffer + rtt/2.
104
+ * - `"reckon"`: rewind to the client's `reckonTime` (≈ its serverNow) — for
105
+ * targets it forward-extrapolates (Predict `reckon`).
106
+ * Attach the same collection twice with disjoint `fields` to mix techniques.
107
+ * The room ships exactly the stamp(s) its attached groups need (see the
108
+ * handshake derivation in `Room`).
109
+ */
110
+ mode?: RewindMode;
111
+ }
112
+ /**
113
+ * Server-side lag compensation — the dual of the client's `Predict`. Where
114
+ * `Predict` forward-reckons entities it RECEIVES, `Rewind` records the recent
115
+ * positions of entities it OWNS and rewinds field reads to a past (client
116
+ * render) time, so a hit test judges against where the client actually SAW an
117
+ * entity — not where it has slid to ~RTT later.
118
+ *
119
+ * Prefer {@link Room.allowRewindState}, which creates a `Rewind` and records it
120
+ * automatically each simulation tick:
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * onCreate() {
125
+ * const rewind = this.allowRewindState({ maxRewindMs: 500 });
126
+ * rewind.attachAll(this.state.enemies, { fields: ["x", "y"] }); // fields ← Enemy's numeric keys
127
+ * this.setTimestep((dt) => { ...move enemies... }, 1000 / 30);
128
+ * // framework calls rewind.record() after each tick.
129
+ * }
130
+ * // in your hit test, with the client's renderTime:
131
+ * const seenX = rewind.valueAt(enemy, renderTime, "x");
132
+ * ```
133
+ *
134
+ * `attachAll` takes the live collection (not a string key), so the element type
135
+ * — and the legal `fields` / `valueAt` field names — are inferred with no
136
+ * state-type generic. Entities are keyed by object identity — removed entities
137
+ * and their history are reclaimed automatically.
138
+ *
139
+ * The rewind TIMELINE is declared per attach-group via `attachAll(coll, { mode })`:
140
+ * `"snapshot"` (default) reads at the client's `renderTime` stamp, `"reckon"` at
141
+ * its `reckonTime` (see {@link at}). Not-attached = not rewound (reads are live)
142
+ * — there is no "none". The same collection may be attached more than once with
143
+ * disjoint `fields` to put different fields on different timelines. The room
144
+ * ships exactly the stamp(s) these groups need (handshake derivation reads
145
+ * {@link timelineMode}); the client declares its display mode independently.
146
+ */
147
+ export declare class Rewind {
148
+ private static readonly byRoom;
149
+ /** One `Rewind` per room (idempotent). `room` is only the cache key. */
150
+ static get(room: object, opts?: RewindOptions): Rewind;
151
+ private readonly groups;
152
+ private readonly defaultMaxRewindMs;
153
+ private _sampleIntervalMs;
154
+ private _lastRecordedAt;
155
+ /** Resolves a client's auto-stamped render time (set by `Room.allowRewindState`
156
+ * when a `mode:"snapshot"` group is attached); powers {@link lastSeenBy}. */
157
+ private _renderTimeOf?;
158
+ /** Resolves a client's auto-stamped reckon-display instant (its serverNow
159
+ * estimate at input-sample time). When present (> 0), {@link lastSeenBy}
160
+ * reads `mode:"reckon"` groups AT this stamp directly — exact regardless
161
+ * of the client's clock/RTT-estimation error (it displayed f(est), we read
162
+ * f(est)) — instead of reconstructing it via the midpoint. */
163
+ private _reckonTimeOf?;
164
+ /** Resolves the CURRENT server time (set by `Room.allowRewindState`) — the
165
+ * reckon midpoint's "now" anchor in {@link at}. Without it, the anchor falls
166
+ * back to `lastRecordedAt`, which is one tick stale at hit-test time. */
167
+ private _nowOf?;
168
+ /** Default view returned by at/lastSeenBy when no `out` is given — one per
169
+ * Rewind, re-aimed per call (zero alloc, zero userland setup). */
170
+ private readonly _view;
171
+ private constructor();
172
+ /** The default rewind window (ms). Use it to bound a hit test:
173
+ * `Math.max(renderTime, now - rewind.maxRewindMs)`. */
174
+ get maxRewindMs(): number;
175
+ /** Server time of the last {@link record} (or -1). The auto-record skips a tick
176
+ * whose time was already recorded manually — your `record()` wins. */
177
+ get lastRecordedAt(): number;
178
+ /** Track every entity in a collection (Map/Array/Set schema). `fields` narrows
179
+ * to its element's numeric fields. `interpolate` (a mode or a per-entity fn,
180
+ * default `linear`) picks how `valueAt` reconstructs between samples — use
181
+ * `step` for discrete-motion entities (e.g. teleporters). `mode` picks the
182
+ * lag-comp timeline (default `"snapshot"`; see {@link AttachOptions}). */
183
+ attachAll<E extends object>(collection: Collection<E>, opts: AttachOptions<E>): this;
184
+ /** Track a single entity (e.g. a boss). `fields` narrows to its numeric fields. */
185
+ attach<E extends object>(instance: E, opts: AttachOptions<E>): this;
186
+ /**
187
+ * Snapshot every tracked entity at `now`. Call once per tick, AFTER they move —
188
+ * {@link Room.allowRewindState} does this for you. `sampleIntervalMs` (the gap
189
+ * between records) sizes the history rings; the framework passes the sim
190
+ * interval. Calling this yourself during a tick suppresses that tick's
191
+ * auto-record (see {@link lastRecordedAt}).
192
+ */
193
+ record(now: number, sampleIntervalMs?: number): void;
194
+ /** Cold path — first time an entity is seen by `record()` for a given group.
195
+ * Resolves the field→`$values` indices (cached per constructor for array-form
196
+ * `fields`; fn-form resolves per entity) and bakes in the group's `mode`. */
197
+ private createHistory;
198
+ /** Keep only the fields this entity's type declares (unknown → read live). */
199
+ private resolveFields;
200
+ /**
201
+ * `instance`'s `field` value at past `time` (interpolated from history). Falls
202
+ * back to the live value when the entity has no history yet, or the field
203
+ * isn't tracked.
204
+ */
205
+ valueAt<T extends object>(instance: T, time: number, field: NumericKeys<T>): number;
206
+ /**
207
+ * Which timeline(s) the attached groups rewind to — `reckon` true iff any
208
+ * group is `mode:"reckon"`, `snapshot` true iff any is `mode:"snapshot"`. The
209
+ * room reads this once (groups are declared in `onCreate`, before any join) to
210
+ * pick which stamp(s) the client must ship: reckon-only / render-only / both /
211
+ * none. @internal
212
+ */
213
+ timelineMode(): {
214
+ reckon: boolean;
215
+ snapshot: boolean;
216
+ };
217
+ /**
218
+ * @internal Wire a resolver from sessionId → that client's auto-stamped
219
+ * `renderTime`. Called by {@link Room.allowRewindState} so {@link lastSeenBy}
220
+ * works for `mode:"snapshot"` groups; auto-enabled by attaching one.
221
+ */
222
+ bindRenderTime(resolver: (sessionId: string) => number): void;
223
+ /**
224
+ * @internal Wire a resolver for the CURRENT server time (ms, same epoch as
225
+ * `record` times). Called by {@link Room.allowRewindState}; standalone users
226
+ * (tests/harnesses) should bind their own. Anchors the reckon midpoint in
227
+ * {@link at} at the true processing instant — the `lastRecordedAt` fallback
228
+ * is one tick stale by hit-test time, biasing the aim ~half a tick early:
229
+ * imperceptible on slow horizontal motion, but enough to flip knife-edge
230
+ * stomp/hit verdicts on fast vertical movers (a bobbing jumper).
231
+ */
232
+ bindNow(resolver: () => number): void;
233
+ /**
234
+ * @internal Wire a resolver from sessionId → that client's auto-stamped
235
+ * reckon-display instant (`input(sid).reckonTime`). Called by
236
+ * {@link Room.allowRewindState}. With it, {@link lastSeenBy} aims
237
+ * `mode:"reckon"` groups at the EXACT instant the client displayed them
238
+ * (immune to its RTT-estimation error); without it (or while the stamp is
239
+ * still 0), the midpoint reconstruction in {@link at} is the fallback.
240
+ */
241
+ bindReckonTime(resolver: (sessionId: string) => number): void;
242
+ /**
243
+ * A {@link RewindView} of the tracked world at `time` (an acting client's render
244
+ * time), with the two things every hit test re-implements baked in:
245
+ * - **clamp** to `[lastRecordedAt − maxRewindMs, lastRecordedAt]` — an
246
+ * anti-spoof / clock-skew bound (a client can't rewind arbitrarily far), and
247
+ * - **live fallback**: `time <= 0` (the client's clock hasn't synced) → the
248
+ * newest recorded sample (≈ current position).
249
+ *
250
+ * Sugar over {@link valueAt}; pass the render time yourself (e.g. from
251
+ * `input(sid).renderTime`, or a value stored on the entity). For the common
252
+ * "rewind to a specific client's view" case use {@link lastSeenBy}.
253
+ *
254
+ * Re-aims and returns this Rewind's internal view by default — zero alloc,
255
+ * nothing to declare. Pass `out` to aim a view of your own instead; needed
256
+ * only to hold several views at once — see the {@link RewindView} doc.
257
+ */
258
+ at(time: number, out?: RewindView): RewindView;
259
+ /**
260
+ * Shared aiming: clamp the snapshot-timeline `time`, and resolve the reckon
261
+ * timeline either from the DIRECT `reckonStamp` (the instant the client's
262
+ * forward-reckoned entities were displayed at — exact, immune to the
263
+ * client's RTT-estimation error) or, when absent (0), by reconstruction.
264
+ */
265
+ private _aim;
266
+ /**
267
+ * A {@link RewindView} of the world as session `sessionId` LAST saw it —
268
+ * resolves the render time stamped on that client's most recently CONSUMED
269
+ * input (hence "last": under a multi-frame `drain()` it is the newest frame's
270
+ * stamp) and hands off to {@link at}. This is the "what you see is what you
271
+ * hit" path:
272
+ *
273
+ * ```ts
274
+ * const seen = this.rewind.lastSeenBy(shooterSessionId);
275
+ * const hit = overlaps(bullet, seen.value(target, "x"), seen.value(target, "y"));
276
+ * ```
277
+ *
278
+ * Requires the room's framework input (`this.defineInput(Input)`) — the
279
+ * per-client stamp auto-enables from the `attachAll` `mode` of the groups you
280
+ * rewind (declaration order vs `allowRewindState` doesn't matter). A client
281
+ * that merely hasn't stamped yet (clock still syncing, unknown sessionId) is
282
+ * NOT an error — it reads 0 and the view falls back to live. Use
283
+ * {@link at} with an explicit time if you stamp render times yourself.
284
+ *
285
+ * Re-aims and returns this Rewind's internal view by default — zero alloc,
286
+ * nothing to declare. Pass `out` to aim a view of your own instead; needed
287
+ * only to hold several views at once — see the {@link RewindView} doc.
288
+ */
289
+ lastSeenBy(sessionId: string, out?: RewindView): RewindView;
290
+ }
291
+ export {};