@colyseus/core 0.18.24 → 0.18.25

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/build/index.cjs CHANGED
@@ -70,6 +70,7 @@ __export(index_exports, {
70
70
  attachToTestRoom: () => import_RoomPlugin.attachToTestRoom,
71
71
  basicAuth: () => import_router.basicAuth,
72
72
  compileSanitizer: () => import_InputBuffer.compileSanitizer,
73
+ compileSnapshot: () => import_InputBuffer.compileSnapshot,
73
74
  connectClientToRoom: () => import_Transport.connectClientToRoom,
74
75
  createAuthContext: () => import_Transport.createAuthContext,
75
76
  createEndpoint: () => import_router.createEndpoint,
@@ -183,6 +184,7 @@ var import_Logger = require("./Logger.cjs");
183
184
  attachToTestRoom,
184
185
  basicAuth,
185
186
  compileSanitizer,
187
+ compileSnapshot,
186
188
  connectClientToRoom,
187
189
  createAuthContext,
188
190
  createEndpoint,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import { ClockTimer as Clock, Delayed } from '@colyseus/timer';\n\n// Shared types - re-export from @colyseus/shared-types for convenience\nexport {\n Protocol,\n ProtocolModifier,\n ErrorCode,\n CloseCode,\n ResponseStatus,\n type InferState,\n type ExtractRoomMessages,\n type ExtractRoomClientMessages,\n type MessageContext,\n type Rejection,\n type Resolution,\n type ExtractRejectReason,\n type ExtractResponseType,\n} from '@colyseus/shared-types';\n\n// Core classes\nexport { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv, type RoomDefinitions, type ServerOptions, type SDKTypes } from './Server.ts';\nexport { Room, RoomInternalState, validate, type RoomOptions, type DefineInputOptions, type SimulationCallback, type FixedTimestepCallback, type StepContext, type MessageHandlerWithFormat, type Messages, type ExtractRoomState, type ExtractRoomMetadata, type ExtractRoomClient } from './Room.ts';\nexport { InputBufferImpl, compileSanitizer } from './input/InputBuffer.ts';\nexport { type InputAccessor, type InputAPI, type NormalizedInputOptions, type ConsumeOptions, type IdleInput, type IdleContext, type SanitizeInput, type NumericFieldsOf } from './input/types.ts';\nexport { Rewind, RewindView, type RewindOptions, type RewindMode } from './Rewind.ts';\nexport {\n RoomPlugin, definePlugins, attachToTestRoom,\n type RoomPluginOrder, type PluginDependencies, type RoomPluginClass,\n} from './RoomPlugin.ts';\nexport { getMessageBytes } from './Protocol.ts';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler.ts';\nexport { ServerError } from './errors/ServerError.ts';\n\nexport {\n type RoomException,\n type RoomMethodName,\n OnCreateException,\n OnAuthException,\n OnJoinException,\n OnLeaveException,\n OnDisposeException,\n OnMessageException,\n TimestepException,\n SimulationIntervalException,\n TimedEventException,\n} from './errors/RoomExceptions.ts';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker.ts';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby.ts';\nexport { createNodeMatchmakingMiddleware } from './router/node.ts';\n\n// Driver\nexport * from './matchmaker/LocalDriver/LocalDriver.ts';\nexport { initializeRoomCache } from './matchmaker/driver.ts';\n\n// Transport\nexport { type Client, type ClientPrivate, type AuthContext, ClientState, ClientArray, Transport, type ISendOptions, type BeforeUpgradeHandler, runBeforeUpgrade, createAuthContext, connectClientToRoom, enqueueClientRaw } from './Transport.ts';\n\n// Presence\nexport { type Presence } from './presence/Presence.ts';\nexport { LocalPresence } from './presence/LocalPresence.ts';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer.ts';\nexport { SchemaSerializer } from './serializer/SchemaSerializer.ts';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, spliceOne, getBearerToken, dynamicImport } from './utils/Utils.ts';\nexport { isDevMode, setDevMode } from './utils/DevMode.ts';\n\n// IPC\nexport { subscribeIPC, requestFromIPC } from './IPC.ts';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug.ts';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom.ts';\nexport { RelayRoom } from './rooms/RelayRoom.ts';\nexport { QueueRoom, type QueueOptions, type QueueMatchGroup, type QueueMatchTeam, type QueueClientData } from './rooms/QueueRoom.ts';\n\n// Router / Endpoints\nexport {\n createEndpoint,\n createInternalContext,\n createMiddleware,\n createRouter,\n basicAuth,\n type BasicAuthOptions,\n toNodeHandler,\n dualModeEndpoints,\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type ExpressMiddleware,\n type NodeHandler,\n type DualModeHelpers,\n} from './router/index.ts';\n\n// Abstract logging support\nexport { logger } from './Logger.ts';\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAG7C,0BAcO;AAGP,oBAAsM;AACtM,kBAA2R;AAC3R,yBAAkD;AAClD,mBAAgL;AAChL,oBAAwE;AACxE,wBAGO;AACP,sBAAgC;AAChC,+BAAkC;AAClC,yBAA4B;AAE5B,4BAYO;AAGP,iBAA4B;AAE5B,mBAA4C;AAC5C,kBAAgD;AAGhD,0BAAc,qDAtDd;AAuDA,oBAAoC;AAGpC,uBAAiO;AAGjO,sBAA8B;AAC9B,2BAA8B;AAG9B,wBAAgC;AAChC,8BAAiC;AAIjC,mBAA+E;AAC/E,qBAAsC;AAGtC,iBAA6C;AAG7C,mBASO;AAGP,uBAA0B;AAC1B,uBAA0B;AAC1B,uBAA8G;AAG9G,oBAmBO;AAGP,oBAAuB;",
4
+ "sourcesContent": ["import { ClockTimer as Clock, Delayed } from '@colyseus/timer';\n\n// Shared types - re-export from @colyseus/shared-types for convenience\nexport {\n Protocol,\n ProtocolModifier,\n ErrorCode,\n CloseCode,\n ResponseStatus,\n type InferState,\n type ExtractRoomMessages,\n type ExtractRoomClientMessages,\n type MessageContext,\n type Rejection,\n type Resolution,\n type ExtractRejectReason,\n type ExtractResponseType,\n} from '@colyseus/shared-types';\n\n// Core classes\nexport { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv, type RoomDefinitions, type ServerOptions, type SDKTypes } from './Server.ts';\nexport { Room, RoomInternalState, validate, type RoomOptions, type DefineInputOptions, type SimulationCallback, type FixedTimestepCallback, type StepContext, type MessageHandlerWithFormat, type Messages, type ExtractRoomState, type ExtractRoomMetadata, type ExtractRoomClient } from './Room.ts';\nexport { InputBufferImpl, compileSanitizer, compileSnapshot } from './input/InputBuffer.ts';\nexport { type InputAccessor, type InputAPI, type NormalizedInputOptions, type ConsumeOptions, type IdleInput, type IdleContext, type SanitizeInput, type NumericFieldsOf } from './input/types.ts';\nexport { Rewind, RewindView, type RewindOptions, type RewindMode } from './Rewind.ts';\nexport {\n RoomPlugin, definePlugins, attachToTestRoom,\n type RoomPluginOrder, type PluginDependencies, type RoomPluginClass,\n} from './RoomPlugin.ts';\nexport { getMessageBytes } from './Protocol.ts';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler.ts';\nexport { ServerError } from './errors/ServerError.ts';\n\nexport {\n type RoomException,\n type RoomMethodName,\n OnCreateException,\n OnAuthException,\n OnJoinException,\n OnLeaveException,\n OnDisposeException,\n OnMessageException,\n TimestepException,\n SimulationIntervalException,\n TimedEventException,\n} from './errors/RoomExceptions.ts';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker.ts';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby.ts';\nexport { createNodeMatchmakingMiddleware } from './router/node.ts';\n\n// Driver\nexport * from './matchmaker/LocalDriver/LocalDriver.ts';\nexport { initializeRoomCache } from './matchmaker/driver.ts';\n\n// Transport\nexport { type Client, type ClientPrivate, type AuthContext, ClientState, ClientArray, Transport, type ISendOptions, type BeforeUpgradeHandler, runBeforeUpgrade, createAuthContext, connectClientToRoom, enqueueClientRaw } from './Transport.ts';\n\n// Presence\nexport { type Presence } from './presence/Presence.ts';\nexport { LocalPresence } from './presence/LocalPresence.ts';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer.ts';\nexport { SchemaSerializer } from './serializer/SchemaSerializer.ts';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, spliceOne, getBearerToken, dynamicImport } from './utils/Utils.ts';\nexport { isDevMode, setDevMode } from './utils/DevMode.ts';\n\n// IPC\nexport { subscribeIPC, requestFromIPC } from './IPC.ts';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug.ts';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom.ts';\nexport { RelayRoom } from './rooms/RelayRoom.ts';\nexport { QueueRoom, type QueueOptions, type QueueMatchGroup, type QueueMatchTeam, type QueueClientData } from './rooms/QueueRoom.ts';\n\n// Router / Endpoints\nexport {\n createEndpoint,\n createInternalContext,\n createMiddleware,\n createRouter,\n basicAuth,\n type BasicAuthOptions,\n toNodeHandler,\n dualModeEndpoints,\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type ExpressMiddleware,\n type NodeHandler,\n type DualModeHelpers,\n} from './router/index.ts';\n\n// Abstract logging support\nexport { logger } from './Logger.ts';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAG7C,0BAcO;AAGP,oBAAsM;AACtM,kBAA2R;AAC3R,yBAAmE;AACnE,mBAAgL;AAChL,oBAAwE;AACxE,wBAGO;AACP,sBAAgC;AAChC,+BAAkC;AAClC,yBAA4B;AAE5B,4BAYO;AAGP,iBAA4B;AAE5B,mBAA4C;AAC5C,kBAAgD;AAGhD,0BAAc,qDAtDd;AAuDA,oBAAoC;AAGpC,uBAAiO;AAGjO,sBAA8B;AAC9B,2BAA8B;AAG9B,wBAAgC;AAChC,8BAAiC;AAIjC,mBAA+E;AAC/E,qBAAsC;AAGtC,iBAA6C;AAG7C,mBASO;AAGP,uBAA0B;AAC1B,uBAA0B;AAC1B,uBAA8G;AAG9G,oBAmBO;AAGP,oBAAuB;",
6
6
  "names": ["Clock"]
7
7
  }
package/build/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { ClockTimer as Clock, Delayed } from '@colyseus/timer';
2
2
  export { Protocol, ProtocolModifier, ErrorCode, CloseCode, ResponseStatus, type InferState, type ExtractRoomMessages, type ExtractRoomClientMessages, type MessageContext, type Rejection, type Resolution, type ExtractRejectReason, type ExtractResponseType, } from '@colyseus/shared-types';
3
3
  export { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv, type RoomDefinitions, type ServerOptions, type SDKTypes } from './Server.ts';
4
4
  export { Room, RoomInternalState, validate, type RoomOptions, type DefineInputOptions, type SimulationCallback, type FixedTimestepCallback, type StepContext, type MessageHandlerWithFormat, type Messages, type ExtractRoomState, type ExtractRoomMetadata, type ExtractRoomClient } from './Room.ts';
5
- export { InputBufferImpl, compileSanitizer } from './input/InputBuffer.ts';
5
+ export { InputBufferImpl, compileSanitizer, compileSnapshot } from './input/InputBuffer.ts';
6
6
  export { type InputAccessor, type InputAPI, type NormalizedInputOptions, type ConsumeOptions, type IdleInput, type IdleContext, type SanitizeInput, type NumericFieldsOf } from './input/types.ts';
7
7
  export { Rewind, RewindView, type RewindOptions, type RewindMode } from './Rewind.ts';
8
8
  export { RoomPlugin, definePlugins, attachToTestRoom, type RoomPluginOrder, type PluginDependencies, type RoomPluginClass, } from './RoomPlugin.ts';
package/build/index.mjs CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  } from "@colyseus/shared-types";
10
10
  import { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv } from "./Server.mjs";
11
11
  import { Room, RoomInternalState, validate } from "./Room.mjs";
12
- import { InputBufferImpl, compileSanitizer } from "./input/InputBuffer.mjs";
12
+ import { InputBufferImpl, compileSanitizer, compileSnapshot } from "./input/InputBuffer.mjs";
13
13
  import {} from "./input/types.mjs";
14
14
  import { Rewind, RewindView } from "./Rewind.mjs";
15
15
  import {
@@ -106,6 +106,7 @@ export {
106
106
  attachToTestRoom,
107
107
  basicAuth,
108
108
  compileSanitizer,
109
+ compileSnapshot,
109
110
  connectClientToRoom,
110
111
  createAuthContext,
111
112
  createEndpoint,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import { ClockTimer as Clock, Delayed } from '@colyseus/timer';\n\n// Shared types - re-export from @colyseus/shared-types for convenience\nexport {\n Protocol,\n ProtocolModifier,\n ErrorCode,\n CloseCode,\n ResponseStatus,\n type InferState,\n type ExtractRoomMessages,\n type ExtractRoomClientMessages,\n type MessageContext,\n type Rejection,\n type Resolution,\n type ExtractRejectReason,\n type ExtractResponseType,\n} from '@colyseus/shared-types';\n\n// Core classes\nexport { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv, type RoomDefinitions, type ServerOptions, type SDKTypes } from './Server.ts';\nexport { Room, RoomInternalState, validate, type RoomOptions, type DefineInputOptions, type SimulationCallback, type FixedTimestepCallback, type StepContext, type MessageHandlerWithFormat, type Messages, type ExtractRoomState, type ExtractRoomMetadata, type ExtractRoomClient } from './Room.ts';\nexport { InputBufferImpl, compileSanitizer } from './input/InputBuffer.ts';\nexport { type InputAccessor, type InputAPI, type NormalizedInputOptions, type ConsumeOptions, type IdleInput, type IdleContext, type SanitizeInput, type NumericFieldsOf } from './input/types.ts';\nexport { Rewind, RewindView, type RewindOptions, type RewindMode } from './Rewind.ts';\nexport {\n RoomPlugin, definePlugins, attachToTestRoom,\n type RoomPluginOrder, type PluginDependencies, type RoomPluginClass,\n} from './RoomPlugin.ts';\nexport { getMessageBytes } from './Protocol.ts';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler.ts';\nexport { ServerError } from './errors/ServerError.ts';\n\nexport {\n type RoomException,\n type RoomMethodName,\n OnCreateException,\n OnAuthException,\n OnJoinException,\n OnLeaveException,\n OnDisposeException,\n OnMessageException,\n TimestepException,\n SimulationIntervalException,\n TimedEventException,\n} from './errors/RoomExceptions.ts';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker.ts';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby.ts';\nexport { createNodeMatchmakingMiddleware } from './router/node.ts';\n\n// Driver\nexport * from './matchmaker/LocalDriver/LocalDriver.ts';\nexport { initializeRoomCache } from './matchmaker/driver.ts';\n\n// Transport\nexport { type Client, type ClientPrivate, type AuthContext, ClientState, ClientArray, Transport, type ISendOptions, type BeforeUpgradeHandler, runBeforeUpgrade, createAuthContext, connectClientToRoom, enqueueClientRaw } from './Transport.ts';\n\n// Presence\nexport { type Presence } from './presence/Presence.ts';\nexport { LocalPresence } from './presence/LocalPresence.ts';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer.ts';\nexport { SchemaSerializer } from './serializer/SchemaSerializer.ts';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, spliceOne, getBearerToken, dynamicImport } from './utils/Utils.ts';\nexport { isDevMode, setDevMode } from './utils/DevMode.ts';\n\n// IPC\nexport { subscribeIPC, requestFromIPC } from './IPC.ts';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug.ts';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom.ts';\nexport { RelayRoom } from './rooms/RelayRoom.ts';\nexport { QueueRoom, type QueueOptions, type QueueMatchGroup, type QueueMatchTeam, type QueueClientData } from './rooms/QueueRoom.ts';\n\n// Router / Endpoints\nexport {\n createEndpoint,\n createInternalContext,\n createMiddleware,\n createRouter,\n basicAuth,\n type BasicAuthOptions,\n toNodeHandler,\n dualModeEndpoints,\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type ExpressMiddleware,\n type NodeHandler,\n type DualModeHelpers,\n} from './router/index.ts';\n\n// Abstract logging support\nexport { logger } from './Logger.ts';\n"],
5
- "mappings": ";AAAA,SAAS,cAAc,OAAO,eAAe;AAG7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAGP,SAAS,QAAQ,YAAY,cAAc,yBAAyB,2BAA2B,uBAAuB,uBAAgF;AACtM,SAAS,MAAM,mBAAmB,gBAAyP;AAC3R,SAAS,iBAAiB,wBAAwB;AAClD,eAAgL;AAChL,SAAS,QAAQ,kBAAuD;AACxE;AAAA,EACE;AAAA,EAAY;AAAA,EAAe;AAAA,OAEtB;AACP,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,YAAY,gBAAgB;AAE5B,SAAS,aAAa,sBAAsB;AAC5C,SAAS,uCAAuC;AAGhD,cAAc;AACd,SAAS,2BAA2B;AAGpC,SAA4D,aAAa,aAAa,WAAyD,kBAAkB,mBAAmB,qBAAqB,wBAAwB;AAGjO,eAA8B;AAC9B,SAAS,qBAAqB;AAG9B,eAAgC;AAChC,SAAS,wBAAwB;AAIjC,SAAS,YAAY,UAAU,WAAW,gBAAgB,qBAAqB;AAC/E,SAAS,WAAW,kBAAkB;AAGtC,SAAS,cAAc,sBAAsB;AAG7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAqG;AAG9G;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAWK;AAGP,SAAS,cAAc;",
4
+ "sourcesContent": ["import { ClockTimer as Clock, Delayed } from '@colyseus/timer';\n\n// Shared types - re-export from @colyseus/shared-types for convenience\nexport {\n Protocol,\n ProtocolModifier,\n ErrorCode,\n CloseCode,\n ResponseStatus,\n type InferState,\n type ExtractRoomMessages,\n type ExtractRoomClientMessages,\n type MessageContext,\n type Rejection,\n type Resolution,\n type ExtractRejectReason,\n type ExtractResponseType,\n} from '@colyseus/shared-types';\n\n// Core classes\nexport { Server, defineRoom, defineServer, registerRoomDefinitions, unregisterRoomDefinitions, applySimulatedLatency, parseLatencyEnv, type RoomDefinitions, type ServerOptions, type SDKTypes } from './Server.ts';\nexport { Room, RoomInternalState, validate, type RoomOptions, type DefineInputOptions, type SimulationCallback, type FixedTimestepCallback, type StepContext, type MessageHandlerWithFormat, type Messages, type ExtractRoomState, type ExtractRoomMetadata, type ExtractRoomClient } from './Room.ts';\nexport { InputBufferImpl, compileSanitizer, compileSnapshot } from './input/InputBuffer.ts';\nexport { type InputAccessor, type InputAPI, type NormalizedInputOptions, type ConsumeOptions, type IdleInput, type IdleContext, type SanitizeInput, type NumericFieldsOf } from './input/types.ts';\nexport { Rewind, RewindView, type RewindOptions, type RewindMode } from './Rewind.ts';\nexport {\n RoomPlugin, definePlugins, attachToTestRoom,\n type RoomPluginOrder, type PluginDependencies, type RoomPluginClass,\n} from './RoomPlugin.ts';\nexport { getMessageBytes } from './Protocol.ts';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler.ts';\nexport { ServerError } from './errors/ServerError.ts';\n\nexport {\n type RoomException,\n type RoomMethodName,\n OnCreateException,\n OnAuthException,\n OnJoinException,\n OnLeaveException,\n OnDisposeException,\n OnMessageException,\n TimestepException,\n SimulationIntervalException,\n TimedEventException,\n} from './errors/RoomExceptions.ts';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker.ts';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby.ts';\nexport { createNodeMatchmakingMiddleware } from './router/node.ts';\n\n// Driver\nexport * from './matchmaker/LocalDriver/LocalDriver.ts';\nexport { initializeRoomCache } from './matchmaker/driver.ts';\n\n// Transport\nexport { type Client, type ClientPrivate, type AuthContext, ClientState, ClientArray, Transport, type ISendOptions, type BeforeUpgradeHandler, runBeforeUpgrade, createAuthContext, connectClientToRoom, enqueueClientRaw } from './Transport.ts';\n\n// Presence\nexport { type Presence } from './presence/Presence.ts';\nexport { LocalPresence } from './presence/LocalPresence.ts';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer.ts';\nexport { SchemaSerializer } from './serializer/SchemaSerializer.ts';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, spliceOne, getBearerToken, dynamicImport } from './utils/Utils.ts';\nexport { isDevMode, setDevMode } from './utils/DevMode.ts';\n\n// IPC\nexport { subscribeIPC, requestFromIPC } from './IPC.ts';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug.ts';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom.ts';\nexport { RelayRoom } from './rooms/RelayRoom.ts';\nexport { QueueRoom, type QueueOptions, type QueueMatchGroup, type QueueMatchTeam, type QueueClientData } from './rooms/QueueRoom.ts';\n\n// Router / Endpoints\nexport {\n createEndpoint,\n createInternalContext,\n createMiddleware,\n createRouter,\n basicAuth,\n type BasicAuthOptions,\n toNodeHandler,\n dualModeEndpoints,\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type ExpressMiddleware,\n type NodeHandler,\n type DualModeHelpers,\n} from './router/index.ts';\n\n// Abstract logging support\nexport { logger } from './Logger.ts';\n"],
5
+ "mappings": ";AAAA,SAAS,cAAc,OAAO,eAAe;AAG7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAGP,SAAS,QAAQ,YAAY,cAAc,yBAAyB,2BAA2B,uBAAuB,uBAAgF;AACtM,SAAS,MAAM,mBAAmB,gBAAyP;AAC3R,SAAS,iBAAiB,kBAAkB,uBAAuB;AACnE,eAAgL;AAChL,SAAS,QAAQ,kBAAuD;AACxE;AAAA,EACE;AAAA,EAAY;AAAA,EAAe;AAAA,OAEtB;AACP,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,YAAY,gBAAgB;AAE5B,SAAS,aAAa,sBAAsB;AAC5C,SAAS,uCAAuC;AAGhD,cAAc;AACd,SAAS,2BAA2B;AAGpC,SAA4D,aAAa,aAAa,WAAyD,kBAAkB,mBAAmB,qBAAqB,wBAAwB;AAGjO,eAA8B;AAC9B,SAAS,qBAAqB;AAG9B,eAAgC;AAChC,SAAS,wBAAwB;AAIjC,SAAS,YAAY,UAAU,WAAW,gBAAgB,qBAAqB;AAC/E,SAAS,WAAW,kBAAkB;AAGtC,SAAS,cAAc,sBAAsB;AAG7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAqG;AAG9G;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAWK;AAGP,SAAS,cAAc;",
6
6
  "names": []
7
7
  }
@@ -25,10 +25,12 @@ __export(InputBuffer_exports, {
25
25
  InputBufferImpl: () => InputBufferImpl,
26
26
  NO_OP_INPUT_ACCESSOR: () => NO_OP_INPUT_ACCESSOR,
27
27
  compileSanitizer: () => compileSanitizer,
28
+ compileSnapshot: () => compileSnapshot,
28
29
  seedInputZeroValues: () => seedInputZeroValues,
29
30
  validateSubSteps: () => validateSubSteps
30
31
  });
31
32
  module.exports = __toCommonJS(InputBuffer_exports);
33
+ var import_schema = require("@colyseus/schema");
32
34
  var import_Utils = require("../utils/Utils.cjs");
33
35
  function validateSubSteps(subSteps, source) {
34
36
  if (subSteps === void 0) {
@@ -58,7 +60,10 @@ function compileSanitizer(spec) {
58
60
  if (v === void 0) {
59
61
  continue;
60
62
  }
61
- inst[names[i]] = v >= mins[i] ? v <= maxs[i] ? v : maxs[i] : mins[i];
63
+ const clamped = v >= mins[i] ? v <= maxs[i] ? v : maxs[i] : mins[i];
64
+ if (clamped !== v) {
65
+ inst[names[i]] = clamped;
66
+ }
62
67
  }
63
68
  };
64
69
  }
@@ -74,6 +79,51 @@ function fieldNamesOf(ctor) {
74
79
  }
75
80
  return names;
76
81
  }
82
+ var _snapshots = /* @__PURE__ */ new WeakMap();
83
+ function compileSnapshot(ctor) {
84
+ let snapshot = _snapshots.get(ctor);
85
+ if (snapshot !== void 0) {
86
+ return snapshot;
87
+ }
88
+ const md = ctor[import_Utils.$METADATA];
89
+ const names = fieldNamesOf(ctor);
90
+ const plain = md !== void 0 && names.every((_, i) => {
91
+ const type = md[i].type;
92
+ return typeof type === "string" || type !== null && typeof type === "object" && "quantized" in type;
93
+ });
94
+ if (plain) {
95
+ let Frame2 = function(values) {
96
+ this[import_schema.$values] = values;
97
+ };
98
+ var Frame = Frame2;
99
+ const fields = {};
100
+ names.forEach((name, i) => {
101
+ fields[name] = {
102
+ get() {
103
+ return this[import_schema.$values][i];
104
+ },
105
+ set(value) {
106
+ this[import_schema.$values][i] = value;
107
+ },
108
+ enumerable: true,
109
+ configurable: true
110
+ };
111
+ });
112
+ Frame2.prototype = Object.create(ctor.prototype, fields);
113
+ const count = names.length;
114
+ snapshot = (input) => {
115
+ const values = new Array(count);
116
+ for (let i = 0; i < count; i++) {
117
+ values[i] = input[names[i]];
118
+ }
119
+ return new Frame2(values);
120
+ };
121
+ } else {
122
+ snapshot = (input) => input.clone();
123
+ }
124
+ _snapshots.set(ctor, snapshot);
125
+ return snapshot;
126
+ }
77
127
  function seedInputZeroValues(instance, ctor) {
78
128
  const md = ctor[import_Utils.$METADATA];
79
129
  if (!md) {
@@ -558,6 +608,7 @@ var NO_OP_INPUT_ACCESSOR = Object.freeze({
558
608
  InputBufferImpl,
559
609
  NO_OP_INPUT_ACCESSOR,
560
610
  compileSanitizer,
611
+ compileSnapshot,
561
612
  seedInputZeroValues,
562
613
  validateSubSteps
563
614
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/input/InputBuffer.ts"],
4
- "sourcesContent": ["import type { ClientPrivate } from '../Transport.ts';\nimport { $METADATA } from '../utils/Utils.ts';\n\nimport type {\n ConsumeOptions, IdleContext, IdleInput, InputAccessor, SanitizeInput,\n} from './types.ts';\n\n/**\n * @internal Validate a `subSteps` count. Throws on a fractional/non-positive\n * value: both sides loop `subSteps` times at `dt/subSteps`, so anything but a\n * whole number is a determinism bug, not a tunable. Shared by `defineInput`\n * and `setFixedTimestep`.\n */\nexport function validateSubSteps(subSteps: number | undefined, source: string): number | undefined {\n if (subSteps === undefined) { return undefined; }\n if (!Number.isInteger(subSteps) || subSteps < 1) {\n throw new Error(`[${source}] subSteps must be an integer >= 1 (got ${subSteps}).`);\n }\n return subSteps;\n}\n\n/**\n * @internal Compile a {@link SanitizeInput} spec into the per-frame function the\n * decode path applies. The map form precompiles to dense min/max arrays walked\n * with the NaN-safe branch clamp; the callback form passes through.\n */\nexport function compileSanitizer<I>(spec: SanitizeInput<I>): (input: I) => void {\n if (typeof spec === 'function') { return spec; }\n const names = Object.keys(spec);\n const mins = new Float64Array(names.length);\n const maxs = new Float64Array(names.length);\n for (let i = 0; i < names.length; i++) {\n const range = (spec as Record<string, readonly [number, number]>)[names[i]]!;\n mins[i] = range[0];\n maxs[i] = range[1];\n }\n return (input: I) => {\n const inst = input as Record<string, number>;\n for (let i = 0; i < names.length; i++) {\n const v = inst[names[i]];\n // Never-received field: no input to sanitize \u2014 clamping would INVENT\n // one (delta-encoding clients legitimately never transmit fields they\n // never assigned; the range floor turned \"no input\" into \"held stick\").\n if (v === undefined) { continue; }\n // NaN-safe: NaN fails both comparisons \u2192 clamp floor.\n inst[names[i]] = v >= mins[i] ? (v <= maxs[i] ? v : maxs[i]) : mins[i];\n }\n };\n}\n\n/** Field names of an input schema ctor, in declaration order (indices are dense\n * from 0 in the metadata). Resolved ONCE per buffer (cold path). */\nfunction fieldNamesOf(ctor: new () => any): string[] {\n const md = (ctor as any)[$METADATA] as Record<number, { name?: string }> | undefined;\n const names: string[] = [];\n if (md) {\n for (let i = 0; ; i++) {\n const f = md[i];\n if (!f || typeof f.name !== \"string\") break;\n names.push(f.name);\n }\n }\n return names;\n}\n\n/**\n * @internal Seed every declared field that has no construction default with\n * its wire-neutral zero value (0 / false / \"\"; quantized: 0 clamped into the\n * descriptor's range). The input contract is \"the server holds the last\n * received value\" \u2014 before anything is received, that value is the ZERO of\n * the field's type, never `undefined`: a sim would NaN-propagate it and a\n * range sanitizer would clamp it into a phantom input. Clients only transmit\n * fields they assign, so an untouched field stays absent on the wire forever.\n */\nexport function seedInputZeroValues(instance: any, ctor: new () => any): void {\n const md = (ctor as any)[$METADATA] as\n Record<number, { name?: string, type?: unknown }> | undefined;\n if (!md) { return; }\n for (let i = 0; ; i++) {\n const f = md[i];\n if (!f || typeof f.name !== \"string\") break;\n if (instance[f.name] !== undefined) { continue; } // .default() wins\n const type = f.type;\n if (typeof type === \"string\") {\n instance[f.name] = type === \"string\" ? \"\" : type === \"boolean\" ? false : 0;\n } else if (type !== null && typeof type === \"object\" && \"quantized\" in (type as object)) {\n const q = (type as { quantized: { min: number, max: number } }).quantized;\n instance[f.name] = q.min > 0 ? q.min : q.max < 0 ? q.max : 0;\n }\n }\n}\n\n/** Reclaim the consumed prefix once the read cursor passes this many items \u2014\n * bounds the parallel arrays' slack to O(THRESHOLD) between compactions while\n * keeping per-consume work O(1) (no `shift()` re-index on every input). */\nconst COMPACT_THRESHOLD = 32;\n\n/** Shared zero-state \"already done\" iterator \u2014 returned by `consume()` on an\n * empty buffer with no idle policy, and by the no-op accessor. Frozen + a frozen\n * result, so it's allocation-free and safe to share across all callers. */\nconst DONE_RESULT: IteratorResult<any> = Object.freeze({ value: undefined, done: true });\nconst DONE_ITERATOR: IterableIterator<any> = Object.freeze({\n [Symbol.iterator]() { return this; },\n next() { return DONE_RESULT; },\n});\n\n/** @internal */\nexport class InputBufferImpl<I = any> {\n /** Pending snapshots, indexed `[_head, _items.length)`. Consumed inputs are\n * NOT spliced off per-read \u2014 `_head` advances and the prefix is reclaimed in\n * bulk by {@link compact} (a `shift()` per read is O(n), so a burst would be\n * O(n\u00B2)). `_renderTimes`/`_reckonTimes` stay parallel to `_items`. */\n private _items: I[] = [];\n /** Read cursor: index of the oldest UNCONSUMED input (== `_items.length` when empty). */\n private _head = 0;\n private _lastSeq: number = -Infinity;\n private readonly _maxSize: number;\n private readonly _seqField: string | undefined;\n\n /**\n * Cumulative count of inputs CONSUMED from this buffer (via any consume\n * primitive \u2014 {@link next}/{@link take}/{@link drain}/{@link consume} \u2014 plus\n * {@link clear} and overflow). Consumed = \"removed from the pending set\",\n * whether applied to state or discarded. The server echoes this in the TIMED\n * prefix as the reconciliation ack: how many of the client's inputs are\n * reflected in (or finished influencing) the authoritative state, which lags\n * the receive counter by inputs still buffered. Distinct from\n * `_receivedInputCount` (receive-time, for RTT), which leads the state.\n */\n consumedCount = 0;\n\n /** Render times parallel to `_items` (server-clock ms; `0` when unset). */\n private _renderTimes: number[] = [];\n /** Render time of the most recently drained input (see {@link renderTime}). */\n private _lastRenderTime = 0;\n /** Reckon-display stamps parallel to `_items` \u2014 the client's serverNow\n * estimate at input-sample time, i.e. the instant its forward-reckoned\n * entities were displayed at (server-clock ms; `0` when unset). */\n private _reckonTimes: number[] = [];\n /** Reckon stamp of the most recently consumed input (see {@link reckonTime}). */\n private _lastReckonTime = 0;\n /** Framework wire seq per buffered input (parallel to `_items`) \u2014 UNRELIABLE\n * ONLY, lazily created on the first seq-carrying push. Reliable inputs are\n * contiguous, so their consumed-seq-value is always exactly {@link consumedCount}\n * and needs no parallel array; `undefined` here marks that (the common, default\n * path pays nothing). A buffer is single-mode, so this is either never created\n * (reliable) or created once and kept parallel (unreliable). */\n private _seqs?: number[];\n /** Seq VALUE of the last consumed input \u2014 the reconciliation ack echoed to the\n * client (see {@link ackSeq}). Only meaningful when {@link _seqs} is tracked\n * (unreliable); reliable's ack falls back to {@link consumedCount}. */\n private _lastConsumedSeq = 0;\n /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */\n private _lastWasIdle = false;\n\n /** Reused {@link consume} iterator (lazily minted) + its per-call state, so a\n * per-tick loop allocates no generator frame. `_iterRemaining` snapshots the\n * COUNT to walk \u2014 a count, not an index: mid-pass mutations (`next()`/`take()`/\n * `clear()`/compaction) shift indices but can only shorten a count-based pass,\n * never point it past the tail. `_iterIdle` is an optional trailing synthesized\n * frame; `_iterActive` guards against a nested consume() clobbering the shared\n * `_iterRes`. */\n private _iter?: IterableIterator<I>;\n private _iterRemaining = 0;\n private _iterActive = false;\n private _iterIdle?: I;\n private readonly _iterRes: { value: I | undefined; done: boolean } = { value: undefined, done: false };\n\n /** Input schema ctor \u2014 mints the reused idle frame; idle is off without it. */\n private readonly _ctor?: new () => I;\n /** Client slice this buffer belongs to (the live object is `Client & ClientPrivate`)\n * \u2014 feeds the idle callback's ctx (latest + sessionId). */\n private readonly _client?: Pick<ClientPrivate, '_input'> & { sessionId: string };\n /** Room-level idle policy (`defineInput({ idle })`) \u2014 the bare-call default. */\n private readonly _roomIdle?: IdleInput<I>;\n /** Reused synthesized idle frame + the schema's field names/defaults (lazy). */\n private _idle?: I;\n private _fieldNames?: string[];\n private _defaults?: unknown[];\n /** Reused ctx for the idle callback form (see {@link IdleContext}). */\n private readonly _idleCtx: IdleContext<I> = { latest: undefined, sessionId: \"\" };\n\n constructor(maxSize: number, seqField: string | undefined, ctor?: new () => I, client?: Pick<ClientPrivate, '_input'> & { sessionId: string }, idle?: IdleInput<I>) {\n this._maxSize = maxSize;\n this._seqField = seqField;\n this._ctor = ctor;\n this._client = client;\n this._roomIdle = idle;\n }\n\n /** The effective idle policy for one consume call: per-call `false` suppresses,\n * per-call value overrides, else the room-level default (or none). */\n private effectiveIdle(opts?: ConsumeOptions<I>): IdleInput<I> | undefined {\n return opts?.idle === false ? undefined : (opts?.idle ?? this._roomIdle);\n }\n\n /** Resolve an {@link IdleInput} to overrides \u2014 invokes the callback form\n * LAZILY, here at synthesis time (the buffer is known to be empty). */\n private resolveIdle(idle: IdleInput<I>): true | Partial<I> {\n if (typeof idle !== \"function\") return idle;\n this._idleCtx.latest = this._client?._input as I | undefined;\n this._idleCtx.sessionId = this._client?.sessionId ?? \"\";\n return idle(this._idleCtx) ?? true;\n }\n\n /**\n * The synthesized \"no input this tick\" frame: schema defaults overlaid with\n * `overrides` (`true` = none). Copies BY FIELD NAME from the schema metadata \u2014\n * schema fields are prototype accessors (no own props), so `Object.assign`\n * can't source from a schema instance; the name walk reads getters, letting\n * `overrides` be a plain partial OR a schema instance (e.g. `latest`).\n * ONE reused instance \u2014 refilled per call, never advances the ack.\n */\n private idleFrame(overrides: true | Partial<I>): I {\n if (this._idle === undefined) {\n // Lazy mint (cold): the fresh instance doubles as the defaults source.\n this._idle = new this._ctor!();\n seedInputZeroValues(this._idle, this._ctor!);\n this._fieldNames = fieldNamesOf(this._ctor!);\n const fresh = this._idle as Record<string, unknown>;\n this._defaults = this._fieldNames.map((n) => fresh[n]);\n }\n const idle = this._idle as Record<string, unknown>;\n const names = this._fieldNames!;\n const defaults = this._defaults!;\n const ov = overrides === true ? undefined : (overrides as Record<string, unknown>);\n for (let i = 0; i < names.length; i++) {\n const v = ov?.[names[i]];\n idle[names[i]] = v !== undefined ? v : defaults[i];\n }\n return this._idle;\n }\n\n /** The idle frame to synthesize on an empty tick (room policy or per-call\n * `opts.idle`), or `undefined` when no policy is in effect. Reuses the single\n * idle instance; never advances the ack. Callers set {@link wasIdle}. */\n private idleFrameOnEmpty(opts?: ConsumeOptions<I>): I | undefined {\n const idle = this._ctor !== undefined ? this.effectiveIdle(opts) : undefined;\n return idle === undefined ? undefined : this.idleFrame(this.resolveIdle(idle));\n }\n\n /** Consume the input at the cursor: advance cursor + ack, stamp THIS input's\n * render/reckon times, clear {@link wasIdle}. The shared per-input step behind\n * {@link next}, {@link consume}'s iterator, and the re-entrant fallback. */\n private stepHead(): I {\n const i = this._head;\n this._lastWasIdle = false;\n this._lastRenderTime = this._renderTimes[i];\n this._lastReckonTime = this._reckonTimes[i];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[i]; }\n this._head = i + 1;\n this.consumedCount++;\n return this._items[i];\n }\n\n /** Drop ALL slots, reusing the backing arrays' capacity \u2014 the zero-GC reset for\n * the consume/next path ({@link compact}/{@link clear}). `drain()` deliberately\n * does NOT use this (it returns an array, so fresh `[]` is faster there). */\n private truncate(): void {\n this._items.length = 0;\n this._renderTimes.length = 0;\n this._reckonTimes.length = 0;\n if (this._seqs !== undefined) { this._seqs.length = 0; }\n this._head = 0;\n }\n\n /**\n * Append a decoded input snapshot. `seq` is the framework wire seq (unreliable);\n * omit it for reliable inputs, which get an implicit monotonic receive count so\n * {@link ackSeq} stays well-defined in both modes.\n */\n push(snapshot: I, renderTime: number = 0, reckonTime: number = 0, seq?: number): void {\n this._items.push(snapshot);\n this._renderTimes.push(renderTime);\n this._reckonTimes.push(reckonTime);\n // Track the wire seq only for unreliable (seq provided); reliable derives its\n // ack from consumedCount, so it never allocates/maintains this array.\n if (seq !== undefined) { (this._seqs ??= []).push(seq); }\n // Overflow drops the oldest unconsumed input; count it consumed so the ack\n // still advances past it. Advance the cursor (don't shift) \u2014 keeps it O(1).\n if (this.size > this._maxSize) {\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[this._head]; } // dropped oldest counts as acked\n this._head++;\n this.consumedCount++;\n this.compact();\n }\n }\n\n /** Reclaim the consumed prefix `[0, _head)`. Free when fully drained (reuse the\n * arrays); otherwise splice only once the cursor passes {@link COMPACT_THRESHOLD},\n * so the amortized per-input cost stays O(1). */\n private compact(): void {\n if (this._head === 0) { return; }\n if (this._head >= this._items.length) {\n this.truncate();\n } else if (this._head >= COMPACT_THRESHOLD) {\n this._items.splice(0, this._head);\n this._renderTimes.splice(0, this._head);\n this._reckonTimes.splice(0, this._head);\n if (this._seqs !== undefined) { this._seqs.splice(0, this._head); }\n this._head = 0;\n }\n }\n\n /** Returns true if `value` hasn't been seen, and updates the last-seen marker. */\n accept(value: number): boolean {\n if (value <= this._lastSeq) { return false; }\n this._lastSeq = value;\n return true;\n }\n\n drain(opts?: ConsumeOptions<I>): I[] {\n // Empty: synthesize one idle frame (NOT consumed \u2014 no ack bump, stamps\n // untouched) when a policy is in effect, else [].\n if (this.size === 0) {\n const idle = this.idleFrameOnEmpty(opts);\n this._lastWasIdle = idle !== undefined;\n return idle !== undefined ? [idle] : [];\n }\n this._lastWasIdle = false;\n const last = this._items.length - 1;\n this._lastRenderTime = this._renderTimes[last]; // drain reports the NEWEST stamps\n this._lastReckonTime = this._reckonTimes[last];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[last]; }\n // Hand off the backing array untouched when nothing was partially consumed\n // (O(1) \u2014 the caller may retain it); else copy out the unconsumed tail. Fresh\n // arrays here, NOT truncate(): drain already allocates the returned array, and\n // V8 makes `= []` + refill cheaper than `length = 0` reuse (~1.8\u00D7 at small N),\n // so the speed wins and the 3 tiny empties are negligible next to the return.\n const out = this._head === 0 ? this._items : this._items.slice(this._head);\n this.consumedCount += out.length;\n this._items = [];\n this._renderTimes = [];\n this._reckonTimes = [];\n if (this._seqs !== undefined) { this._seqs = []; }\n this._head = 0;\n return out;\n }\n\n /** Consume the single oldest input (ack advances by one); `undefined` if\n * empty \u2014 or the synthesized idle frame when an idle policy is in effect. */\n next(opts?: ConsumeOptions<I>): I | undefined {\n if (this.size === 0) {\n const idle = this.idleFrameOnEmpty(opts);\n this._lastWasIdle = idle !== undefined;\n return idle;\n }\n const item = this.stepHead();\n this.compact();\n return item;\n }\n\n /** Consume up to `n` oldest inputs (ack advances by the count actually taken). */\n take(n: number): I[] {\n this._lastWasIdle = false; // take never synthesizes idle\n const avail = this.size;\n if (n <= 0 || avail === 0) { return []; }\n const count = Math.min(n, avail);\n const start = this._head;\n const out = this._items.slice(start, start + count);\n this._lastRenderTime = this._renderTimes[start + count - 1]; // newest taken input's stamps\n this._lastReckonTime = this._reckonTimes[start + count - 1];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[start + count - 1]; }\n this._head += count;\n this.consumedCount += count;\n this.compact();\n return out;\n }\n\n /**\n * Iterate pending inputs one at a time (per-yield ack + stamp updates), or\n * exactly one synthesized idle frame on an empty buffer with a policy in\n * effect. See {@link InputAccessor.consume}.\n *\n * Returns a POOLED iterator (reused across calls \u2014 no generator frame, no\n * per-call allocation) that consumes at most the pending count snapshotted at\n * the call \u2014 never past the live tail \u2014 plus one optional trailing idle frame.\n * The cursor advances per `next()`, so `break` (which calls `return()`)\n * leaves the rest buffered and compacts. A nested\n * `consume()` of the SAME buffer while one is live falls back to a fresh\n * generator so the pooled `_iterRes` isn't clobbered (nesting is meaningless \u2014\n * both share the cursor \u2014 but it must not corrupt).\n */\n consume(opts?: ConsumeOptions<I>): IterableIterator<I> {\n const empty = this.size === 0;\n const idle = empty ? this.idleFrameOnEmpty(opts) : undefined;\n if (empty && idle === undefined) { this._lastWasIdle = false; return DONE_ITERATOR as IterableIterator<I>; }\n // A nested consume() of this same buffer would clobber the pooled iterator's\n // shared state \u2192 hand the rare case a fresh generator instead.\n if (this._iterActive) { return this.consumeGen(idle); }\n this._iterActive = true;\n this._iterIdle = idle; // one trailing idle frame, or undefined\n this._iterRemaining = this.size; // count snapshot \u2014 a (hypothetical) mid-loop push isn't consumed this pass\n return this.ensureIter();\n }\n\n [Symbol.iterator](): IterableIterator<I> {\n return this.consume();\n }\n\n /** Lazily mint the reused iterator. Closures over `this` so it reads the\n * private cursor directly; one `_iterRes` is reused \u2014 read each result before\n * the next `next()`, as `for..of` / spread / `Array.from` all do. */\n private ensureIter(): IterableIterator<I> {\n if (this._iter !== undefined) { return this._iter; }\n const self = this;\n const res = this._iterRes;\n const finish = (): IteratorResult<I> => {\n self.compact();\n self._iterActive = false;\n self._iterRemaining = 0;\n self._iterIdle = undefined;\n res.value = undefined;\n res.done = true;\n return res as IteratorResult<I>;\n };\n this._iter = {\n [Symbol.iterator]() { return this; },\n next(): IteratorResult<I> {\n // `size > 0` re-checks the live tail: a mid-loop next()/take()/clear()\n // can only shorten the pass, never make it read past the end.\n if (self._iterRemaining > 0 && self.size > 0) { // a buffered input\n self._iterRemaining--;\n res.value = self.stepHead();\n res.done = false;\n return res as IteratorResult<I>;\n }\n if (self._iterIdle !== undefined) { // one trailing idle frame\n self._lastWasIdle = true;\n res.value = self._iterIdle;\n self._iterIdle = undefined;\n res.done = false;\n return res as IteratorResult<I>;\n }\n return finish();\n },\n return(): IteratorResult<I> { return finish(); }, // `break` \u2192 compact + release\n };\n return this._iter;\n }\n\n /** Re-entrant fallback: a fresh generator for a nested `consume()` of this same\n * buffer (the pooled iterator is single-active). Same accounting + compaction. */\n private *consumeGen(idleFrame: I | undefined): IterableIterator<I> {\n let remaining = this.size; // count-based walk, same reason as the pooled pass\n try {\n while (remaining-- > 0 && this.size > 0) { yield this.stepHead(); }\n if (idleFrame !== undefined) { this._lastWasIdle = true; yield idleFrame; }\n } finally {\n this.compact();\n }\n }\n\n peek(): I[] {\n return this._items.slice(this._head);\n }\n\n at(value: number): I | undefined {\n if (this._seqField === undefined) { return undefined; }\n for (let i = this._head; i < this._items.length; i++) {\n if ((this._items[i] as any)[this._seqField] === value) { return this._items[i]; }\n }\n return undefined;\n }\n\n get size(): number {\n return this._items.length - this._head;\n }\n\n /** Render time (server-clock ms) of the most recently drained input; `0`\n * until the first render-time-stamped input is drained. */\n get renderTime(): number {\n return this._lastRenderTime;\n }\n\n /** Reckon-display stamp of the most recently consumed input \u2014 the client's\n * serverNow estimate when it sampled that input, i.e. the EXACT instant its\n * forward-reckoned entities were displayed at. Same consume semantics as\n * {@link renderTime}. RAW: stays `0` until stamped \u2014 the resolved,\n * always-usable value is the accessor's `reckonTime`\n * (`room.inputs.get(sid)`); `rewind.lastSeenBy()`'s midpoint-reconstruction\n * fallback depends on this raw `0`. */\n get reckonTime(): number {\n return this._lastReckonTime;\n }\n\n /** Seq VALUE of the last consumed input \u2014 the reconciliation ack sent to the\n * client. Reliable (no wire seq tracked): falls back to {@link consumedCount}\n * for free. Unreliable: the framework wire seq, so a fully-dropped input doesn't\n * make the ack lag the client's sent seq by the lost count. `0` before the first\n * consume. */\n get ackSeq(): number {\n return this._seqs !== undefined ? this._lastConsumedSeq : this.consumedCount;\n }\n\n /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */\n get wasIdle(): boolean {\n return this._lastWasIdle;\n }\n\n clear(): void {\n // Cleared inputs count as consumed: advance both the count and the seq-value ack\n // past them so the client's pending set drains (capture the newest seq before truncate).\n if (this._seqs !== undefined && this._items.length > 0) { this._lastConsumedSeq = this._seqs[this._items.length - 1]; }\n this.consumedCount += this.size;\n this.truncate();\n this._lastSeq = -Infinity;\n this._iterActive = false; // recovery hatch if a consume() iterator was abandoned unclosed\n this._iterRemaining = 0; // an abandoned iterator must not consume post-clear pushes\n this._iterIdle = undefined;\n }\n}\n\n/**\n * Default per-client accessor. Reads `_input` and `_inputBuffer` off the\n * client at access time \u2014 both are nullable until the room declares input\n * via `defineInput()`. Cached as `client._inputAccessor` at join, so\n * `room.inputs.get(sessionId)` is a Map lookup + property read.\n *\n * @internal\n */\nexport class InputAccessorImpl<I = any> implements InputAccessor<I> {\n private _client: ClientPrivate;\n /** Current room time (`clock.elapsedTime`) \u2014 resolves the {@link reckonTime}\n * fallback. Threaded by `RoomInput.allocate()`; optional so bare\n * constructions (tests) keep the raw 0. */\n private _nowOf?: () => number;\n constructor(client: ClientPrivate, nowOf?: () => number) {\n this._client = client;\n this._nowOf = nowOf;\n }\n get latest(): I | undefined { return this._client._input as I | undefined; }\n at(value: number): I | undefined { return this._client._inputBuffer?.at(value) as I | undefined; }\n consume(opts?: ConsumeOptions<I>): IterableIterator<I> {\n return (this._client._inputBuffer?.consume(opts) ?? DONE_ITERATOR) as IterableIterator<I>;\n }\n [Symbol.iterator](): IterableIterator<I> { return this.consume(); }\n drain(opts?: ConsumeOptions<I>): I[] { return (this._client._inputBuffer?.drain(opts) ?? []) as I[]; }\n next(): I | undefined;\n next(opts: { idle: IdleInput<I> }): I;\n next(opts?: ConsumeOptions<I>): I | undefined { return this._client._inputBuffer?.next(opts) as I | undefined; }\n take(n: number): I[] { return (this._client._inputBuffer?.take(n) ?? []) as I[]; }\n peek(): I[] { return (this._client._inputBuffer?.peek() ?? []) as I[]; }\n get size(): number { return this._client._inputBuffer?.size ?? 0; }\n get consumedCount(): number { return this._client._inputBuffer?.consumedCount ?? 0; }\n get wasIdle(): boolean { return this._client._inputBuffer?.wasIdle ?? false; }\n clear(): void { this._client._inputBuffer?.clear(); }\n get renderTime(): number { return this._client._inputBuffer?.renderTime ?? 0; }\n /** @internal RAW reckon stamp (0 until stamped). The rewind binding reads\n * THIS, not the resolved getter below: `Rewind._aim`'s midpoint fallback\n * must still see 0 for unstamped clients (a resolved value would silently\n * take the direct-stamp clamp path). */\n get rawReckonTime(): number { return this._client._inputBuffer?.reckonTime ?? 0; }\n get reckonTime(): number {\n const raw = this._client._inputBuffer?.reckonTime ?? 0;\n return raw > 0 ? raw : this._nowOf !== undefined ? this._nowOf() : 0;\n }\n}\n\n/**\n * Returned by `room.inputs.get(sessionId)` for unknown sessions and for rooms\n * that didn't call `defineInput()`.\n *\n * @internal\n */\nexport const NO_OP_INPUT_ACCESSOR: InputAccessor<any> = Object.freeze({\n latest: undefined,\n at: () => undefined,\n consume: () => DONE_ITERATOR,\n [Symbol.iterator]: () => DONE_ITERATOR,\n drain: () => [],\n next: () => undefined,\n take: () => [],\n peek: () => [],\n size: 0,\n consumedCount: 0,\n wasIdle: false,\n clear: () => {},\n renderTime: 0,\n reckonTime: 0, // stays 0 \u2014 an unknown session / input-less room has no clock to resolve against\n});\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAA0B;AAYnB,SAAS,iBAAiB,UAA8B,QAAoC;AACjG,MAAI,aAAa,QAAW;AAAE,WAAO;AAAA,EAAW;AAChD,MAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAAG;AAC/C,UAAM,IAAI,MAAM,IAAI,MAAM,2CAA2C,QAAQ,IAAI;AAAA,EACnF;AACA,SAAO;AACT;AAOO,SAAS,iBAAoB,MAA4C;AAC9E,MAAI,OAAO,SAAS,YAAY;AAAE,WAAO;AAAA,EAAM;AAC/C,QAAM,QAAQ,OAAO,KAAK,IAAI;AAC9B,QAAM,OAAO,IAAI,aAAa,MAAM,MAAM;AAC1C,QAAM,OAAO,IAAI,aAAa,MAAM,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,QAAS,KAAmD,MAAM,CAAC,CAAC;AAC1E,SAAK,CAAC,IAAI,MAAM,CAAC;AACjB,SAAK,CAAC,IAAI,MAAM,CAAC;AAAA,EACnB;AACA,SAAO,CAAC,UAAa;AACnB,UAAM,OAAO;AACb,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAM,IAAI,KAAK,MAAM,CAAC,CAAC;AAIvB,UAAI,MAAM,QAAW;AAAE;AAAA,MAAU;AAEjC,WAAK,MAAM,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,IAAK,KAAK,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAK,KAAK,CAAC;AAAA,IACvE;AAAA,EACF;AACF;AAIA,SAAS,aAAa,MAA+B;AACnD,QAAM,KAAM,KAAa,sBAAS;A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AAM,KAAK,WAAW,SAAY,KAAK,OAAO,IAAI;AAAA,EACrE;AACF;AAQO,IAAM,uBAA2C,OAAO,OAAO;AAAA,EACpE,QAAQ;AAAA,EACR,IAAI,MAAM;AAAA,EACV,SAAS,MAAM;AAAA,EACf,CAAC,OAAO,QAAQ,GAAG,MAAM;AAAA,EACzB,OAAO,MAAM,CAAC;AAAA,EACd,MAAM,MAAM;AAAA,EACZ,MAAM,MAAM,CAAC;AAAA,EACb,MAAM,MAAM,CAAC;AAAA,EACb,MAAM;AAAA,EACN,eAAe;AAAA,EACf,SAAS;AAAA,EACT,OAAO,MAAM;AAAA,EAAC;AAAA,EACd,YAAY;AAAA,EACZ,YAAY;AAAA;AACd,CAAC;",
6
- "names": []
4
+ "sourcesContent": ["import { $values } from '@colyseus/schema';\n\nimport type { ClientPrivate } from '../Transport.ts';\nimport { $METADATA } from '../utils/Utils.ts';\n\nimport type {\n ConsumeOptions, IdleContext, IdleInput, InputAccessor, SanitizeInput,\n} from './types.ts';\n\n/**\n * @internal Validate a `subSteps` count. Throws on a fractional/non-positive\n * value: both sides loop `subSteps` times at `dt/subSteps`, so anything but a\n * whole number is a determinism bug, not a tunable. Shared by `defineInput`\n * and `setFixedTimestep`.\n */\nexport function validateSubSteps(subSteps: number | undefined, source: string): number | undefined {\n if (subSteps === undefined) { return undefined; }\n if (!Number.isInteger(subSteps) || subSteps < 1) {\n throw new Error(`[${source}] subSteps must be an integer >= 1 (got ${subSteps}).`);\n }\n return subSteps;\n}\n\n/**\n * @internal Compile a {@link SanitizeInput} spec into the per-frame function the\n * decode path applies. The map form precompiles to dense min/max arrays walked\n * with the NaN-safe branch clamp; the callback form passes through.\n */\nexport function compileSanitizer<I>(spec: SanitizeInput<I>): (input: I) => void {\n if (typeof spec === 'function') { return spec; }\n const names = Object.keys(spec);\n const mins = new Float64Array(names.length);\n const maxs = new Float64Array(names.length);\n for (let i = 0; i < names.length; i++) {\n const range = (spec as Record<string, readonly [number, number]>)[names[i]]!;\n mins[i] = range[0];\n maxs[i] = range[1];\n }\n return (input: I) => {\n const inst = input as Record<string, number>;\n for (let i = 0; i < names.length; i++) {\n const v = inst[names[i]];\n // Never-received field: no input to sanitize \u2014 clamping would INVENT\n // one (delta-encoding clients legitimately never transmit fields they\n // never assigned; the range floor turned \"no input\" into \"held stick\").\n if (v === undefined) { continue; }\n // NaN-safe: NaN fails both comparisons \u2192 clamp floor.\n const clamped = v >= mins[i] ? (v <= maxs[i] ? v : maxs[i]) : mins[i];\n // Honest frames clamp nothing: a keyed write through the setter costs more than the walk.\n if (clamped !== v) { inst[names[i]] = clamped; }\n }\n };\n}\n\n/** Field names of an input schema ctor, in declaration order (indices are dense\n * from 0 in the metadata). Resolved ONCE per buffer (cold path). */\nfunction fieldNamesOf(ctor: new () => any): string[] {\n const md = (ctor as any)[$METADATA] as Record<number, { name?: string }> | undefined;\n const names: string[] = [];\n if (md) {\n for (let i = 0; ; i++) {\n const f = md[i];\n if (!f || typeof f.name !== \"string\") break;\n names.push(f.name);\n }\n }\n return names;\n}\n\n/** One per input schema, so every room's frames share a hidden class. */\nconst _snapshots = new WeakMap<new () => any, (input: any) => any>();\n\n/**\n * @internal Compile how a decoded input is copied into the buffer. `clone()`\n * builds a Schema and its ChangeTree per input, for a frame that's never\n * encoded, so a schema of plain values gets a lighter frame: its own array of\n * values behind the ctor's prototype. Methods, getters, `instanceof`, `clone()`\n * and `toJSON()` all hold, and a field write lands on the copy, untracked. A\n * nested schema or collection keeps `clone()`, whose copy is deep.\n *\n * Fields are read by name, as `clone()` reads them, never by copying `$values`:\n * native class fields (`useDefineForClassFields`) shadow the schema's accessors,\n * so the decoder's values sit on the instance and `$values` stays empty.\n */\nexport function compileSnapshot<I>(ctor: new () => I): (input: I) => I {\n let snapshot = _snapshots.get(ctor);\n if (snapshot !== undefined) { return snapshot; }\n\n const md = (ctor as any)[$METADATA] as Record<number, { type?: unknown }> | undefined;\n const names = fieldNamesOf(ctor);\n const plain = md !== undefined && names.every((_, i) => {\n const type = md[i].type;\n return typeof type === \"string\" || (type !== null && typeof type === \"object\" && \"quantized\" in type);\n });\n\n if (plain) {\n const fields: PropertyDescriptorMap = {};\n names.forEach((name, i) => {\n fields[name] = {\n get(this: any) { return this[$values][i]; },\n set(this: any, value: unknown) { this[$values][i] = value; },\n enumerable: true,\n configurable: true,\n };\n });\n // A function, not a class: `constructor` must stay the schema's (clone/toJSON read its metadata).\n function Frame(this: any, values: unknown[]) { this[$values] = values; }\n Frame.prototype = Object.create(ctor.prototype, fields);\n const count = names.length;\n snapshot = (input) => {\n const values = new Array(count);\n for (let i = 0; i < count; i++) { values[i] = input[names[i]]; }\n return new (Frame as any)(values);\n };\n } else {\n snapshot = (input) => input.clone();\n }\n\n _snapshots.set(ctor, snapshot!);\n return snapshot!;\n}\n\n/**\n * @internal Seed every declared field that has no construction default with\n * its wire-neutral zero value (0 / false / \"\"; quantized: 0 clamped into the\n * descriptor's range). The input contract is \"the server holds the last\n * received value\" \u2014 before anything is received, that value is the ZERO of\n * the field's type, never `undefined`: a sim would NaN-propagate it and a\n * range sanitizer would clamp it into a phantom input. Clients only transmit\n * fields they assign, so an untouched field stays absent on the wire forever.\n */\nexport function seedInputZeroValues(instance: any, ctor: new () => any): void {\n const md = (ctor as any)[$METADATA] as\n Record<number, { name?: string, type?: unknown }> | undefined;\n if (!md) { return; }\n for (let i = 0; ; i++) {\n const f = md[i];\n if (!f || typeof f.name !== \"string\") break;\n if (instance[f.name] !== undefined) { continue; } // .default() wins\n const type = f.type;\n if (typeof type === \"string\") {\n instance[f.name] = type === \"string\" ? \"\" : type === \"boolean\" ? false : 0;\n } else if (type !== null && typeof type === \"object\" && \"quantized\" in (type as object)) {\n const q = (type as { quantized: { min: number, max: number } }).quantized;\n instance[f.name] = q.min > 0 ? q.min : q.max < 0 ? q.max : 0;\n }\n }\n}\n\n/** Reclaim the consumed prefix once the read cursor passes this many items \u2014\n * bounds the parallel arrays' slack to O(THRESHOLD) between compactions while\n * keeping per-consume work O(1) (no `shift()` re-index on every input). */\nconst COMPACT_THRESHOLD = 32;\n\n/** Shared zero-state \"already done\" iterator \u2014 returned by `consume()` on an\n * empty buffer with no idle policy, and by the no-op accessor. Frozen + a frozen\n * result, so it's allocation-free and safe to share across all callers. */\nconst DONE_RESULT: IteratorResult<any> = Object.freeze({ value: undefined, done: true });\nconst DONE_ITERATOR: IterableIterator<any> = Object.freeze({\n [Symbol.iterator]() { return this; },\n next() { return DONE_RESULT; },\n});\n\n/** @internal */\nexport class InputBufferImpl<I = any> {\n /** Pending snapshots, indexed `[_head, _items.length)`. Consumed inputs are\n * NOT spliced off per-read \u2014 `_head` advances and the prefix is reclaimed in\n * bulk by {@link compact} (a `shift()` per read is O(n), so a burst would be\n * O(n\u00B2)). `_renderTimes`/`_reckonTimes` stay parallel to `_items`. */\n private _items: I[] = [];\n /** Read cursor: index of the oldest UNCONSUMED input (== `_items.length` when empty). */\n private _head = 0;\n private _lastSeq: number = -Infinity;\n private readonly _maxSize: number;\n private readonly _seqField: string | undefined;\n\n /**\n * Cumulative count of inputs CONSUMED from this buffer (via any consume\n * primitive \u2014 {@link next}/{@link take}/{@link drain}/{@link consume} \u2014 plus\n * {@link clear} and overflow). Consumed = \"removed from the pending set\",\n * whether applied to state or discarded. The server echoes this in the TIMED\n * prefix as the reconciliation ack: how many of the client's inputs are\n * reflected in (or finished influencing) the authoritative state, which lags\n * the receive counter by inputs still buffered. Distinct from\n * `_receivedInputCount` (receive-time, for RTT), which leads the state.\n */\n consumedCount = 0;\n\n /** Render times parallel to `_items` (server-clock ms; `0` when unset). */\n private _renderTimes: number[] = [];\n /** Render time of the most recently drained input (see {@link renderTime}). */\n private _lastRenderTime = 0;\n /** Reckon-display stamps parallel to `_items` \u2014 the client's serverNow\n * estimate at input-sample time, i.e. the instant its forward-reckoned\n * entities were displayed at (server-clock ms; `0` when unset). */\n private _reckonTimes: number[] = [];\n /** Reckon stamp of the most recently consumed input (see {@link reckonTime}). */\n private _lastReckonTime = 0;\n /** Framework wire seq per buffered input (parallel to `_items`) \u2014 UNRELIABLE\n * ONLY, lazily created on the first seq-carrying push. Reliable inputs are\n * contiguous, so their consumed-seq-value is always exactly {@link consumedCount}\n * and needs no parallel array; `undefined` here marks that (the common, default\n * path pays nothing). A buffer is single-mode, so this is either never created\n * (reliable) or created once and kept parallel (unreliable). */\n private _seqs?: number[];\n /** Seq VALUE of the last consumed input \u2014 the reconciliation ack echoed to the\n * client (see {@link ackSeq}). Only meaningful when {@link _seqs} is tracked\n * (unreliable); reliable's ack falls back to {@link consumedCount}. */\n private _lastConsumedSeq = 0;\n /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */\n private _lastWasIdle = false;\n\n /** Reused {@link consume} iterator (lazily minted) + its per-call state, so a\n * per-tick loop allocates no generator frame. `_iterRemaining` snapshots the\n * COUNT to walk \u2014 a count, not an index: mid-pass mutations (`next()`/`take()`/\n * `clear()`/compaction) shift indices but can only shorten a count-based pass,\n * never point it past the tail. `_iterIdle` is an optional trailing synthesized\n * frame; `_iterActive` guards against a nested consume() clobbering the shared\n * `_iterRes`. */\n private _iter?: IterableIterator<I>;\n private _iterRemaining = 0;\n private _iterActive = false;\n private _iterIdle?: I;\n private readonly _iterRes: { value: I | undefined; done: boolean } = { value: undefined, done: false };\n\n /** Input schema ctor \u2014 mints the reused idle frame; idle is off without it. */\n private readonly _ctor?: new () => I;\n /** Client slice this buffer belongs to (the live object is `Client & ClientPrivate`)\n * \u2014 feeds the idle callback's ctx (latest + sessionId). */\n private readonly _client?: Pick<ClientPrivate, '_input'> & { sessionId: string };\n /** Room-level idle policy (`defineInput({ idle })`) \u2014 the bare-call default. */\n private readonly _roomIdle?: IdleInput<I>;\n /** Reused synthesized idle frame + the schema's field names/defaults (lazy). */\n private _idle?: I;\n private _fieldNames?: string[];\n private _defaults?: unknown[];\n /** Reused ctx for the idle callback form (see {@link IdleContext}). */\n private readonly _idleCtx: IdleContext<I> = { latest: undefined, sessionId: \"\" };\n\n constructor(maxSize: number, seqField: string | undefined, ctor?: new () => I, client?: Pick<ClientPrivate, '_input'> & { sessionId: string }, idle?: IdleInput<I>) {\n this._maxSize = maxSize;\n this._seqField = seqField;\n this._ctor = ctor;\n this._client = client;\n this._roomIdle = idle;\n }\n\n /** The effective idle policy for one consume call: per-call `false` suppresses,\n * per-call value overrides, else the room-level default (or none). */\n private effectiveIdle(opts?: ConsumeOptions<I>): IdleInput<I> | undefined {\n return opts?.idle === false ? undefined : (opts?.idle ?? this._roomIdle);\n }\n\n /** Resolve an {@link IdleInput} to overrides \u2014 invokes the callback form\n * LAZILY, here at synthesis time (the buffer is known to be empty). */\n private resolveIdle(idle: IdleInput<I>): true | Partial<I> {\n if (typeof idle !== \"function\") return idle;\n this._idleCtx.latest = this._client?._input as I | undefined;\n this._idleCtx.sessionId = this._client?.sessionId ?? \"\";\n return idle(this._idleCtx) ?? true;\n }\n\n /**\n * The synthesized \"no input this tick\" frame: schema defaults overlaid with\n * `overrides` (`true` = none). Copies BY FIELD NAME from the schema metadata \u2014\n * schema fields are prototype accessors (no own props), so `Object.assign`\n * can't source from a schema instance; the name walk reads getters, letting\n * `overrides` be a plain partial OR a schema instance (e.g. `latest`).\n * ONE reused instance \u2014 refilled per call, never advances the ack.\n */\n private idleFrame(overrides: true | Partial<I>): I {\n if (this._idle === undefined) {\n // Lazy mint (cold): the fresh instance doubles as the defaults source.\n this._idle = new this._ctor!();\n seedInputZeroValues(this._idle, this._ctor!);\n this._fieldNames = fieldNamesOf(this._ctor!);\n const fresh = this._idle as Record<string, unknown>;\n this._defaults = this._fieldNames.map((n) => fresh[n]);\n }\n const idle = this._idle as Record<string, unknown>;\n const names = this._fieldNames!;\n const defaults = this._defaults!;\n const ov = overrides === true ? undefined : (overrides as Record<string, unknown>);\n for (let i = 0; i < names.length; i++) {\n const v = ov?.[names[i]];\n idle[names[i]] = v !== undefined ? v : defaults[i];\n }\n return this._idle;\n }\n\n /** The idle frame to synthesize on an empty tick (room policy or per-call\n * `opts.idle`), or `undefined` when no policy is in effect. Reuses the single\n * idle instance; never advances the ack. Callers set {@link wasIdle}. */\n private idleFrameOnEmpty(opts?: ConsumeOptions<I>): I | undefined {\n const idle = this._ctor !== undefined ? this.effectiveIdle(opts) : undefined;\n return idle === undefined ? undefined : this.idleFrame(this.resolveIdle(idle));\n }\n\n /** Consume the input at the cursor: advance cursor + ack, stamp THIS input's\n * render/reckon times, clear {@link wasIdle}. The shared per-input step behind\n * {@link next}, {@link consume}'s iterator, and the re-entrant fallback. */\n private stepHead(): I {\n const i = this._head;\n this._lastWasIdle = false;\n this._lastRenderTime = this._renderTimes[i];\n this._lastReckonTime = this._reckonTimes[i];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[i]; }\n this._head = i + 1;\n this.consumedCount++;\n return this._items[i];\n }\n\n /** Drop ALL slots, reusing the backing arrays' capacity \u2014 the zero-GC reset for\n * the consume/next path ({@link compact}/{@link clear}). `drain()` deliberately\n * does NOT use this (it returns an array, so fresh `[]` is faster there). */\n private truncate(): void {\n this._items.length = 0;\n this._renderTimes.length = 0;\n this._reckonTimes.length = 0;\n if (this._seqs !== undefined) { this._seqs.length = 0; }\n this._head = 0;\n }\n\n /**\n * Append a decoded input snapshot. `seq` is the framework wire seq (unreliable);\n * omit it for reliable inputs, which get an implicit monotonic receive count so\n * {@link ackSeq} stays well-defined in both modes.\n */\n push(snapshot: I, renderTime: number = 0, reckonTime: number = 0, seq?: number): void {\n this._items.push(snapshot);\n this._renderTimes.push(renderTime);\n this._reckonTimes.push(reckonTime);\n // Track the wire seq only for unreliable (seq provided); reliable derives its\n // ack from consumedCount, so it never allocates/maintains this array.\n if (seq !== undefined) { (this._seqs ??= []).push(seq); }\n // Overflow drops the oldest unconsumed input; count it consumed so the ack\n // still advances past it. Advance the cursor (don't shift) \u2014 keeps it O(1).\n if (this.size > this._maxSize) {\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[this._head]; } // dropped oldest counts as acked\n this._head++;\n this.consumedCount++;\n this.compact();\n }\n }\n\n /** Reclaim the consumed prefix `[0, _head)`. Free when fully drained (reuse the\n * arrays); otherwise splice only once the cursor passes {@link COMPACT_THRESHOLD},\n * so the amortized per-input cost stays O(1). */\n private compact(): void {\n if (this._head === 0) { return; }\n if (this._head >= this._items.length) {\n this.truncate();\n } else if (this._head >= COMPACT_THRESHOLD) {\n this._items.splice(0, this._head);\n this._renderTimes.splice(0, this._head);\n this._reckonTimes.splice(0, this._head);\n if (this._seqs !== undefined) { this._seqs.splice(0, this._head); }\n this._head = 0;\n }\n }\n\n /** Returns true if `value` hasn't been seen, and updates the last-seen marker. */\n accept(value: number): boolean {\n if (value <= this._lastSeq) { return false; }\n this._lastSeq = value;\n return true;\n }\n\n drain(opts?: ConsumeOptions<I>): I[] {\n // Empty: synthesize one idle frame (NOT consumed \u2014 no ack bump, stamps\n // untouched) when a policy is in effect, else [].\n if (this.size === 0) {\n const idle = this.idleFrameOnEmpty(opts);\n this._lastWasIdle = idle !== undefined;\n return idle !== undefined ? [idle] : [];\n }\n this._lastWasIdle = false;\n const last = this._items.length - 1;\n this._lastRenderTime = this._renderTimes[last]; // drain reports the NEWEST stamps\n this._lastReckonTime = this._reckonTimes[last];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[last]; }\n // Hand off the backing array untouched when nothing was partially consumed\n // (O(1) \u2014 the caller may retain it); else copy out the unconsumed tail. Fresh\n // arrays here, NOT truncate(): drain already allocates the returned array, and\n // V8 makes `= []` + refill cheaper than `length = 0` reuse (~1.8\u00D7 at small N),\n // so the speed wins and the 3 tiny empties are negligible next to the return.\n const out = this._head === 0 ? this._items : this._items.slice(this._head);\n this.consumedCount += out.length;\n this._items = [];\n this._renderTimes = [];\n this._reckonTimes = [];\n if (this._seqs !== undefined) { this._seqs = []; }\n this._head = 0;\n return out;\n }\n\n /** Consume the single oldest input (ack advances by one); `undefined` if\n * empty \u2014 or the synthesized idle frame when an idle policy is in effect. */\n next(opts?: ConsumeOptions<I>): I | undefined {\n if (this.size === 0) {\n const idle = this.idleFrameOnEmpty(opts);\n this._lastWasIdle = idle !== undefined;\n return idle;\n }\n const item = this.stepHead();\n this.compact();\n return item;\n }\n\n /** Consume up to `n` oldest inputs (ack advances by the count actually taken). */\n take(n: number): I[] {\n this._lastWasIdle = false; // take never synthesizes idle\n const avail = this.size;\n if (n <= 0 || avail === 0) { return []; }\n const count = Math.min(n, avail);\n const start = this._head;\n const out = this._items.slice(start, start + count);\n this._lastRenderTime = this._renderTimes[start + count - 1]; // newest taken input's stamps\n this._lastReckonTime = this._reckonTimes[start + count - 1];\n if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[start + count - 1]; }\n this._head += count;\n this.consumedCount += count;\n this.compact();\n return out;\n }\n\n /**\n * Iterate pending inputs one at a time (per-yield ack + stamp updates), or\n * exactly one synthesized idle frame on an empty buffer with a policy in\n * effect. See {@link InputAccessor.consume}.\n *\n * Returns a POOLED iterator (reused across calls \u2014 no generator frame, no\n * per-call allocation) that consumes at most the pending count snapshotted at\n * the call \u2014 never past the live tail \u2014 plus one optional trailing idle frame.\n * The cursor advances per `next()`, so `break` (which calls `return()`)\n * leaves the rest buffered and compacts. A nested\n * `consume()` of the SAME buffer while one is live falls back to a fresh\n * generator so the pooled `_iterRes` isn't clobbered (nesting is meaningless \u2014\n * both share the cursor \u2014 but it must not corrupt).\n */\n consume(opts?: ConsumeOptions<I>): IterableIterator<I> {\n const empty = this.size === 0;\n const idle = empty ? this.idleFrameOnEmpty(opts) : undefined;\n if (empty && idle === undefined) { this._lastWasIdle = false; return DONE_ITERATOR as IterableIterator<I>; }\n // A nested consume() of this same buffer would clobber the pooled iterator's\n // shared state \u2192 hand the rare case a fresh generator instead.\n if (this._iterActive) { return this.consumeGen(idle); }\n this._iterActive = true;\n this._iterIdle = idle; // one trailing idle frame, or undefined\n this._iterRemaining = this.size; // count snapshot \u2014 a (hypothetical) mid-loop push isn't consumed this pass\n return this.ensureIter();\n }\n\n [Symbol.iterator](): IterableIterator<I> {\n return this.consume();\n }\n\n /** Lazily mint the reused iterator. Closures over `this` so it reads the\n * private cursor directly; one `_iterRes` is reused \u2014 read each result before\n * the next `next()`, as `for..of` / spread / `Array.from` all do. */\n private ensureIter(): IterableIterator<I> {\n if (this._iter !== undefined) { return this._iter; }\n const self = this;\n const res = this._iterRes;\n const finish = (): IteratorResult<I> => {\n self.compact();\n self._iterActive = false;\n self._iterRemaining = 0;\n self._iterIdle = undefined;\n res.value = undefined;\n res.done = true;\n return res as IteratorResult<I>;\n };\n this._iter = {\n [Symbol.iterator]() { return this; },\n next(): IteratorResult<I> {\n // `size > 0` re-checks the live tail: a mid-loop next()/take()/clear()\n // can only shorten the pass, never make it read past the end.\n if (self._iterRemaining > 0 && self.size > 0) { // a buffered input\n self._iterRemaining--;\n res.value = self.stepHead();\n res.done = false;\n return res as IteratorResult<I>;\n }\n if (self._iterIdle !== undefined) { // one trailing idle frame\n self._lastWasIdle = true;\n res.value = self._iterIdle;\n self._iterIdle = undefined;\n res.done = false;\n return res as IteratorResult<I>;\n }\n return finish();\n },\n return(): IteratorResult<I> { return finish(); }, // `break` \u2192 compact + release\n };\n return this._iter;\n }\n\n /** Re-entrant fallback: a fresh generator for a nested `consume()` of this same\n * buffer (the pooled iterator is single-active). Same accounting + compaction. */\n private *consumeGen(idleFrame: I | undefined): IterableIterator<I> {\n let remaining = this.size; // count-based walk, same reason as the pooled pass\n try {\n while (remaining-- > 0 && this.size > 0) { yield this.stepHead(); }\n if (idleFrame !== undefined) { this._lastWasIdle = true; yield idleFrame; }\n } finally {\n this.compact();\n }\n }\n\n peek(): I[] {\n return this._items.slice(this._head);\n }\n\n at(value: number): I | undefined {\n if (this._seqField === undefined) { return undefined; }\n for (let i = this._head; i < this._items.length; i++) {\n if ((this._items[i] as any)[this._seqField] === value) { return this._items[i]; }\n }\n return undefined;\n }\n\n get size(): number {\n return this._items.length - this._head;\n }\n\n /** Render time (server-clock ms) of the most recently drained input; `0`\n * until the first render-time-stamped input is drained. */\n get renderTime(): number {\n return this._lastRenderTime;\n }\n\n /** Reckon-display stamp of the most recently consumed input \u2014 the client's\n * serverNow estimate when it sampled that input, i.e. the EXACT instant its\n * forward-reckoned entities were displayed at. Same consume semantics as\n * {@link renderTime}. RAW: stays `0` until stamped \u2014 the resolved,\n * always-usable value is the accessor's `reckonTime`\n * (`room.inputs.get(sid)`); `rewind.lastSeenBy()`'s midpoint-reconstruction\n * fallback depends on this raw `0`. */\n get reckonTime(): number {\n return this._lastReckonTime;\n }\n\n /** Seq VALUE of the last consumed input \u2014 the reconciliation ack sent to the\n * client. Reliable (no wire seq tracked): falls back to {@link consumedCount}\n * for free. Unreliable: the framework wire seq, so a fully-dropped input doesn't\n * make the ack lag the client's sent seq by the lost count. `0` before the first\n * consume. */\n get ackSeq(): number {\n return this._seqs !== undefined ? this._lastConsumedSeq : this.consumedCount;\n }\n\n /** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */\n get wasIdle(): boolean {\n return this._lastWasIdle;\n }\n\n clear(): void {\n // Cleared inputs count as consumed: advance both the count and the seq-value ack\n // past them so the client's pending set drains (capture the newest seq before truncate).\n if (this._seqs !== undefined && this._items.length > 0) { this._lastConsumedSeq = this._seqs[this._items.length - 1]; }\n this.consumedCount += this.size;\n this.truncate();\n this._lastSeq = -Infinity;\n this._iterActive = false; // recovery hatch if a consume() iterator was abandoned unclosed\n this._iterRemaining = 0; // an abandoned iterator must not consume post-clear pushes\n this._iterIdle = undefined;\n }\n}\n\n/**\n * Default per-client accessor. Reads `_input` and `_inputBuffer` off the\n * client at access time \u2014 both are nullable until the room declares input\n * via `defineInput()`. Cached as `client._inputAccessor` at join, so\n * `room.inputs.get(sessionId)` is a Map lookup + property read.\n *\n * @internal\n */\nexport class InputAccessorImpl<I = any> implements InputAccessor<I> {\n private _client: ClientPrivate;\n /** Current room time (`clock.elapsedTime`) \u2014 resolves the {@link reckonTime}\n * fallback. Threaded by `RoomInput.allocate()`; optional so bare\n * constructions (tests) keep the raw 0. */\n private _nowOf?: () => number;\n constructor(client: ClientPrivate, nowOf?: () => number) {\n this._client = client;\n this._nowOf = nowOf;\n }\n get latest(): I | undefined { return this._client._input as I | undefined; }\n at(value: number): I | undefined { return this._client._inputBuffer?.at(value) as I | undefined; }\n consume(opts?: ConsumeOptions<I>): IterableIterator<I> {\n return (this._client._inputBuffer?.consume(opts) ?? DONE_ITERATOR) as IterableIterator<I>;\n }\n [Symbol.iterator](): IterableIterator<I> { return this.consume(); }\n drain(opts?: ConsumeOptions<I>): I[] { return (this._client._inputBuffer?.drain(opts) ?? []) as I[]; }\n next(): I | undefined;\n next(opts: { idle: IdleInput<I> }): I;\n next(opts?: ConsumeOptions<I>): I | undefined { return this._client._inputBuffer?.next(opts) as I | undefined; }\n take(n: number): I[] { return (this._client._inputBuffer?.take(n) ?? []) as I[]; }\n peek(): I[] { return (this._client._inputBuffer?.peek() ?? []) as I[]; }\n get size(): number { return this._client._inputBuffer?.size ?? 0; }\n get consumedCount(): number { return this._client._inputBuffer?.consumedCount ?? 0; }\n get wasIdle(): boolean { return this._client._inputBuffer?.wasIdle ?? false; }\n clear(): void { this._client._inputBuffer?.clear(); }\n get renderTime(): number { return this._client._inputBuffer?.renderTime ?? 0; }\n /** @internal RAW reckon stamp (0 until stamped). The rewind binding reads\n * THIS, not the resolved getter below: `Rewind._aim`'s midpoint fallback\n * must still see 0 for unstamped clients (a resolved value would silently\n * take the direct-stamp clamp path). */\n get rawReckonTime(): number { return this._client._inputBuffer?.reckonTime ?? 0; }\n get reckonTime(): number {\n const raw = this._client._inputBuffer?.reckonTime ?? 0;\n return raw > 0 ? raw : this._nowOf !== undefined ? this._nowOf() : 0;\n }\n}\n\n/**\n * Returned by `room.inputs.get(sessionId)` for unknown sessions and for rooms\n * that didn't call `defineInput()`.\n *\n * @internal\n */\nexport const NO_OP_INPUT_ACCESSOR: InputAccessor<any> = Object.freeze({\n latest: undefined,\n at: () => undefined,\n consume: () => DONE_ITERATOR,\n [Symbol.iterator]: () => DONE_ITERATOR,\n drain: () => [],\n next: () => undefined,\n take: () => [],\n peek: () => [],\n size: 0,\n consumedCount: 0,\n wasIdle: false,\n clear: () => {},\n renderTime: 0,\n reckonTime: 0, // stays 0 \u2014 an unknown session / input-less room has no clock to resolve against\n});\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAwB;AAGxB,mBAA0B;AAYnB,SAAS,iBAAiB,UAA8B,QAAoC;AACjG,MAAI,aAAa,QAAW;AAAE,WAAO;AAAA,EAAW;AAChD,MAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAAG;AAC/C,UAAM,IAAI,MAAM,IAAI,MAAM,2CAA2C,QAAQ,IAAI;AAAA,EACnF;AACA,SAAO;AACT;AAOO,SAAS,iBAAoB,MAA4C;AAC9E,MAAI,OAAO,SAAS,YAAY;AAAE,WAAO;AAAA,EAAM;AAC/C,QAAM,QAAQ,OAAO,KAAK,IAAI;AAC9B,QAAM,OAAO,IAAI,aAAa,MAAM,MAAM;AAC1C,QAAM,OAAO,IAAI,aAAa,MAAM,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,QAAS,KAAmD,MAAM,CAAC,CAAC;AAC1E,SAAK,CAAC,IAAI,MAAM,CAAC;AACjB,SAAK,CAAC,IAAI,MAAM,CAAC;AAAA,EACnB;AACA,SAAO,CAAC,UAAa;AACnB,UAAM,OAAO;AACb,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAM,IAAI,KAAK,MAAM,CAAC,CAAC;AAIvB,UAAI,MAAM,QAAW;AAAE;AAAA,MAAU;AAEjC,YAAM,UAAU,KAAK,KAAK,CAAC,IAAK,KAAK,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAK,KAAK,CAAC;AAEpE,UAAI,YAAY,GAAG;AAAE,aAAK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F,IAAI,aAAqB;AACvB,UAAM,MAAM,KAAK,QAAQ,cAAc,cAAc;AACrD,WAAO,MAAM,IAAI,MAAM,KAAK,WAAW,SAAY,KAAK,OAAO,IAAI;AAAA,EACrE;AACF;AAQO,IAAM,uBAA2C,OAAO,OAAO;AAAA,EACpE,QAAQ;AAAA,EACR,IAAI,MAAM;AAAA,EACV,SAAS,MAAM;AAAA,EACf,CAAC,OAAO,QAAQ,GAAG,MAAM;AAAA,EACzB,OAAO,MAAM,CAAC;AAAA,EACd,MAAM,MAAM;AAAA,EACZ,MAAM,MAAM,CAAC;AAAA,EACb,MAAM,MAAM,CAAC;AAAA,EACb,MAAM;AAAA,EACN,eAAe;AAAA,EACf,SAAS;AAAA,EACT,OAAO,MAAM;AAAA,EAAC;AAAA,EACd,YAAY;AAAA,EACZ,YAAY;AAAA;AACd,CAAC;",
6
+ "names": ["Frame"]
7
7
  }
@@ -13,6 +13,19 @@ export declare function validateSubSteps(subSteps: number | undefined, source: s
13
13
  * with the NaN-safe branch clamp; the callback form passes through.
14
14
  */
15
15
  export declare function compileSanitizer<I>(spec: SanitizeInput<I>): (input: I) => void;
16
+ /**
17
+ * @internal Compile how a decoded input is copied into the buffer. `clone()`
18
+ * builds a Schema and its ChangeTree per input, for a frame that's never
19
+ * encoded, so a schema of plain values gets a lighter frame: its own array of
20
+ * values behind the ctor's prototype. Methods, getters, `instanceof`, `clone()`
21
+ * and `toJSON()` all hold, and a field write lands on the copy, untracked. A
22
+ * nested schema or collection keeps `clone()`, whose copy is deep.
23
+ *
24
+ * Fields are read by name, as `clone()` reads them, never by copying `$values`:
25
+ * native class fields (`useDefineForClassFields`) shadow the schema's accessors,
26
+ * so the decoder's values sit on the instance and `$values` stays empty.
27
+ */
28
+ export declare function compileSnapshot<I>(ctor: new () => I): (input: I) => I;
16
29
  /**
17
30
  * @internal Seed every declared field that has no construction default with
18
31
  * its wire-neutral zero value (0 / false / ""; quantized: 0 clamped into the
@@ -1,4 +1,5 @@
1
1
  // packages/core/src/input/InputBuffer.ts
2
+ import { $values } from "@colyseus/schema";
2
3
  import { $METADATA } from "../utils/Utils.mjs";
3
4
  function validateSubSteps(subSteps, source) {
4
5
  if (subSteps === void 0) {
@@ -28,7 +29,10 @@ function compileSanitizer(spec) {
28
29
  if (v === void 0) {
29
30
  continue;
30
31
  }
31
- inst[names[i]] = v >= mins[i] ? v <= maxs[i] ? v : maxs[i] : mins[i];
32
+ const clamped = v >= mins[i] ? v <= maxs[i] ? v : maxs[i] : mins[i];
33
+ if (clamped !== v) {
34
+ inst[names[i]] = clamped;
35
+ }
32
36
  }
33
37
  };
34
38
  }
@@ -44,6 +48,51 @@ function fieldNamesOf(ctor) {
44
48
  }
45
49
  return names;
46
50
  }
51
+ var _snapshots = /* @__PURE__ */ new WeakMap();
52
+ function compileSnapshot(ctor) {
53
+ let snapshot = _snapshots.get(ctor);
54
+ if (snapshot !== void 0) {
55
+ return snapshot;
56
+ }
57
+ const md = ctor[$METADATA];
58
+ const names = fieldNamesOf(ctor);
59
+ const plain = md !== void 0 && names.every((_, i) => {
60
+ const type = md[i].type;
61
+ return typeof type === "string" || type !== null && typeof type === "object" && "quantized" in type;
62
+ });
63
+ if (plain) {
64
+ let Frame2 = function(values) {
65
+ this[$values] = values;
66
+ };
67
+ var Frame = Frame2;
68
+ const fields = {};
69
+ names.forEach((name, i) => {
70
+ fields[name] = {
71
+ get() {
72
+ return this[$values][i];
73
+ },
74
+ set(value) {
75
+ this[$values][i] = value;
76
+ },
77
+ enumerable: true,
78
+ configurable: true
79
+ };
80
+ });
81
+ Frame2.prototype = Object.create(ctor.prototype, fields);
82
+ const count = names.length;
83
+ snapshot = (input) => {
84
+ const values = new Array(count);
85
+ for (let i = 0; i < count; i++) {
86
+ values[i] = input[names[i]];
87
+ }
88
+ return new Frame2(values);
89
+ };
90
+ } else {
91
+ snapshot = (input) => input.clone();
92
+ }
93
+ _snapshots.set(ctor, snapshot);
94
+ return snapshot;
95
+ }
47
96
  function seedInputZeroValues(instance, ctor) {
48
97
  const md = ctor[$METADATA];
49
98
  if (!md) {
@@ -527,6 +576,7 @@ export {
527
576
  InputBufferImpl,
528
577
  NO_OP_INPUT_ACCESSOR,
529
578
  compileSanitizer,
579
+ compileSnapshot,
530
580
  seedInputZeroValues,
531
581
  validateSubSteps
532
582
  };