@margoengine/netcode 0.0.0-stage → 1.0.0

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 (66) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1387 -2
  4. package/dist/client.d.ts +167 -0
  5. package/dist/clock.d.ts +29 -0
  6. package/dist/extrapolate.d.ts +42 -0
  7. package/dist/extrapolate.js +25 -0
  8. package/dist/game.d.ts +68 -0
  9. package/dist/generate-rust.d.ts +14 -0
  10. package/dist/generate-rust.js +184 -0
  11. package/dist/generate.d.ts +25 -0
  12. package/dist/generate.js +156 -0
  13. package/dist/hitboxes.d.ts +74 -0
  14. package/dist/hitboxes.js +124 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +457 -0
  17. package/dist/interest.d.ts +101 -0
  18. package/dist/interest.js +166 -0
  19. package/dist/interpolation-delay.d.ts +114 -0
  20. package/dist/interpolation-delay.js +79 -0
  21. package/dist/interpolation-fields.d.ts +117 -0
  22. package/dist/interpolation-fields.js +147 -0
  23. package/dist/interpolation-timeline.d.ts +100 -0
  24. package/dist/interpolation-timeline.js +122 -0
  25. package/dist/interpolation.d.ts +39 -0
  26. package/dist/interpolation.js +61 -0
  27. package/dist/lag.d.ts +62 -0
  28. package/dist/lobby.d.ts +77 -0
  29. package/dist/lobby.js +96 -0
  30. package/dist/loopback.d.ts +92 -0
  31. package/dist/media.d.ts +215 -0
  32. package/dist/media.js +305 -0
  33. package/dist/migrate.d.ts +113 -0
  34. package/dist/migrate.js +289 -0
  35. package/dist/node.d.ts +101 -0
  36. package/dist/node.js +166 -0
  37. package/dist/physics.d.ts +133 -0
  38. package/dist/physics.js +169 -0
  39. package/dist/presence.d.ts +156 -0
  40. package/dist/presence.js +226 -0
  41. package/dist/protocol-asi_qndb.js +122 -0
  42. package/dist/protocol.d.ts +75 -0
  43. package/dist/relay.d.ts +152 -0
  44. package/dist/relay.js +235 -0
  45. package/dist/rollback.d.ts +131 -0
  46. package/dist/rollback.js +194 -0
  47. package/dist/rooms.d.ts +366 -0
  48. package/dist/rooms.js +479 -0
  49. package/dist/schema-CMfqK4Gu.js +616 -0
  50. package/dist/schema.d.ts +263 -0
  51. package/dist/server-DAVzHcWW.js +203 -0
  52. package/dist/server.d.ts +147 -0
  53. package/dist/shared/bytes.d.ts +38 -0
  54. package/dist/signal.d.ts +156 -0
  55. package/dist/signal.js +261 -0
  56. package/dist/smoothing.d.ts +76 -0
  57. package/dist/smoothing.js +155 -0
  58. package/dist/transport-DeQodwyv.js +49 -0
  59. package/dist/transport.d.ts +76 -0
  60. package/dist/webrtc.d.ts +32 -0
  61. package/dist/webrtc.js +64 -0
  62. package/dist/websocket.d.ts +27 -0
  63. package/dist/websocket.js +42 -0
  64. package/dist/webtransport.d.ts +83 -0
  65. package/dist/webtransport.js +120 -0
  66. package/package.json +138 -4
@@ -0,0 +1,366 @@
1
+ import type { SchemaCodec, SchemaShape, UntypedSchema } from './schema.js';
2
+ import { type Connection } from './transport.js';
3
+ declare const METHODS: readonly ['create', 'join', 'joinOrCreate', 'joinById', 'reconnect'];
4
+ /** How a client asks for a room. */
5
+ export type JoinMethod = (typeof METHODS)[number];
6
+ /** One client in a room, on the server. */
7
+ export declare class RoomClient {
8
+ /** @internal */ connection: Connection;
9
+ private readonly limit;
10
+ /** Unique id of this seat. */
11
+ readonly sessionId: string;
12
+ /** Anything your room wants to keep per client. */
13
+ userData: unknown;
14
+ /** What `onAuth` returned. */
15
+ auth: unknown;
16
+ /** @internal The secret that brings this client back to its seat, '' when the room keeps no seats. */
17
+ secret: string;
18
+ /** @internal */
19
+ constructor(sessionId: string,
20
+ /** @internal */ connection: Connection, limit: number);
21
+ /**
22
+ * Sends message `type` with a JSON payload to this client, reliably.
23
+ * @throws RangeError when the JSON is over the room's message limit.
24
+ */
25
+ send(type: string, message?: unknown): void;
26
+ /** Removes this client from the room (its `onLeave` sees `consented: false`). */
27
+ leave(code?: number, reason?: string): void;
28
+ }
29
+ /** Options a room gets in `onCreate` and the client in `join`. JSON values only. */
30
+ export type RoomOptions = Record<string, unknown>;
31
+ /**
32
+ * A room: subclass it, give it a schema and the struct of its state, and handle the lifecycle.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * class Lobby extends Room<{ players: Map<number, { x: number }> }> {
37
+ * schema = schema;
38
+ * stateType = 'State';
39
+ * maxClients = 8;
40
+ * onCreate() {
41
+ * this.setState({ players: new Map() });
42
+ * this.onMessage('move', (client, message: { x: number }) => {
43
+ * const player = this.state.players.get(this.idOf(client));
44
+ * if (player && Math.abs(message.x) <= 1) player.x += message.x;
45
+ * });
46
+ * }
47
+ * onJoin(client: RoomClient) { this.state.players.set(this.idOf(client), { x: 0 }); }
48
+ * onLeave(client: RoomClient) { this.state.players.delete(this.idOf(client)); }
49
+ * }
50
+ * ```
51
+ */
52
+ export declare abstract class Room<State = unknown> {
53
+ /** The schema that encodes the state. */
54
+ abstract schema: SchemaCodec<SchemaShape> | UntypedSchema;
55
+ /** The state's struct name in `schema`. */
56
+ abstract stateType: string;
57
+ /** Most clients at once (default 64); a full room refuses joins and matchmaking skips it. */
58
+ maxClients: number;
59
+ /** Dispose of the room once the last client leaves (default true). */
60
+ autoDispose: boolean;
61
+ /** Largest message (either way) in bytes (default 4096). */
62
+ maxMessageBytes: number;
63
+ /**
64
+ * Milliseconds a dropped client keeps its seat (default 0: none). While the seat is held `onDrop` has run, it counts
65
+ * against `maxClients` and the room stays alive; `RoomsClient.reconnect` brings the same `RoomClient` back and
66
+ * `onReconnect` runs, or the time runs out and `onLeave` runs as for any leave.
67
+ */
68
+ reconnectWindow: number;
69
+ /**
70
+ * Messages per second a client may send on average (default: the RoomServer's `limits.messagesPerSecond`, 120). A
71
+ * client past it, once its burst is spent, is closed with `CloseCode.rateLimit`.
72
+ */
73
+ maxMessagesPerSecond: number | undefined;
74
+ /** Messages a client may send at once (default: the RoomServer's `limits.burst`, 60). */
75
+ messageBurst: number | undefined;
76
+ /** The room's id. */
77
+ roomId: string;
78
+ /** The name it was defined under. */
79
+ roomName: string;
80
+ /** The clients in the room, in join order. */
81
+ readonly clients: RoomClient[];
82
+ /** Clients that dropped and may still come back, with the timer of each. */
83
+ private held;
84
+ private secrets;
85
+ private current;
86
+ private sent;
87
+ private handlers;
88
+ private patchTimer;
89
+ private patchRate;
90
+ private simulationTimer;
91
+ private lockedByHand;
92
+ private disposed;
93
+ private ids;
94
+ /** Each client's message bucket: tokens left and when it was last refilled. */
95
+ private buckets;
96
+ private nextId;
97
+ /** The onJoin or onReconnect still running for a client: its drop waits for it, so onLeave never runs first. */
98
+ private hooks;
99
+ /** @internal */ onEmpty: (() => void) | null;
100
+ /** @internal Where errors thrown by this room's hooks and handlers go (its RoomServer's `onerror`). */
101
+ report: (error: unknown) => void;
102
+ /** The synced state (set it with {@link Room.setState}). */
103
+ get state(): State;
104
+ /** Whether the room accepts no more joins (locked by hand, or full). */
105
+ get locked(): boolean;
106
+ /** Clients whose seat is held for them to come back. */
107
+ get dropped(): RoomClient[];
108
+ /** @internal No client in the room and no seat held. */
109
+ get empty(): boolean;
110
+ /** Admission extension point, called synchronously after authentication and immediately before seating. */
111
+ protected claimSeat(_options: RoomOptions): boolean;
112
+ /** A small integer id for `client`, unique in this room (handy as a map key in the state). */
113
+ idOf(client: RoomClient): number;
114
+ /** Sets the state clients see; it is sent in full to each client, then as deltas at the patch rate. */
115
+ setState(state: State): void;
116
+ /**
117
+ * Milliseconds between state patches (default 50); 0 stops automatic patches (call {@link Room.patch}). When a
118
+ * timed patch throws (a state the schema cannot encode), the room is stopped as for `setSimulationInterval`.
119
+ */
120
+ setPatchRate(ms: number): void;
121
+ /**
122
+ * Runs `step(deltaMs)` every `ms` milliseconds (default 1000 / 60) until the room is disposed. When `step` throws
123
+ * (or returns a promise that rejects), the error goes to the RoomServer's `onerror(error, room)`, every client is
124
+ * closed with `CloseCode.error` and the room is disposed.
125
+ */
126
+ setSimulationInterval(step: (deltaMs: number) => void, ms?: number): void;
127
+ /** Runs a timer's work; a throw or a rejection stops the room instead of escaping as an uncaught error. */
128
+ private guard;
129
+ /** Reports `error`, closes every client with CloseCode.error and disposes of the room. */
130
+ private stop;
131
+ /** Handles client messages of `type` (`'*'` for any type without its own handler). */
132
+ onMessage<T = unknown>(type: string, handler: (client: RoomClient, message: T) => void): void;
133
+ /** Sends message `type` to every client (but `except`). */
134
+ broadcast(type: string, message?: unknown, { except }?: {
135
+ except?: RoomClient | RoomClient[];
136
+ }): void;
137
+ /** Stops matchmaking from putting new clients here. */
138
+ lock(): void;
139
+ /** Lets matchmaking put new clients here again. */
140
+ unlock(): void;
141
+ /** Sends every client the change since its last patch (or the whole state the first time). */
142
+ patch(): void;
143
+ /** Closes every client and disposes of the room. */
144
+ disconnect(): void;
145
+ /** Same as {@link Room.disconnect}, for `using`. */
146
+ [Symbol.dispose](): void;
147
+ /**
148
+ * Called once when the room is made, with the creating client's options. Clients see the room only after it
149
+ * resolves; if it throws, the room is disposed (`onDispose` runs) and the creating client is closed with
150
+ * `CloseCode.error`.
151
+ */
152
+ onCreate(_options: RoomOptions): void | Promise<void>;
153
+ /** Return false (or throw) to refuse `client`; what it returns is kept as `client.auth`. */
154
+ onAuth(_client: RoomClient, _options: RoomOptions): unknown;
155
+ /** Called when `client` has joined. If it throws, the client is closed with `CloseCode.error` and `onLeave` runs. */
156
+ onJoin(_client: RoomClient, _options: RoomOptions): void | Promise<void>;
157
+ /**
158
+ * Called when `client` left for good: `consented` is true when it called `leave()` itself. With a `reconnectWindow`
159
+ * a dropped client gets here only when the time ran out.
160
+ */
161
+ onLeave(_client: RoomClient, _consented: boolean): void | Promise<void>;
162
+ /** Called when `client` dropped and its seat is held for `reconnectWindow`. An error goes to `rooms.onerror`. */
163
+ onDrop(_client: RoomClient): void | Promise<void>;
164
+ /** Called when a dropped `client` is back in its seat; it then gets the whole state. As `onJoin` if it throws. */
165
+ onReconnect(_client: RoomClient): void | Promise<void>;
166
+ /** Called once when the room is disposed. */
167
+ onDispose(): void | Promise<void>;
168
+ /** @internal Seats a client: 'joined', 'refused' (by onAuth, or the room is full or gone) or 'failed' (onJoin threw). */
169
+ admit(connection: Connection, sessionId: string, options: RoomOptions): Promise<'joined' | 'refused' | 'failed'>;
170
+ /** Puts `client` on `connection`, with a new secret, and tells the other end. */
171
+ private seat;
172
+ /**
173
+ * @internal Brings the client of `secret` back on `connection`. A client still seated is one whose old connection
174
+ * died without the server noticing yet: the new connection takes over from it.
175
+ */
176
+ resume(connection: Connection, secret: string): Promise<'joined' | 'refused' | 'failed'>;
177
+ /**
178
+ * Runs a join hook of `client`, recording it so a drop that comes while it runs waits for it: a client that closes
179
+ * during an async onJoin would otherwise get onLeave first, and onJoin would then put it back in the state.
180
+ */
181
+ private during;
182
+ private forget;
183
+ /** Reports `error` and closes `client` with CloseCode.error (its `onLeave` then runs). */
184
+ private fail;
185
+ private receive;
186
+ private drop;
187
+ /** `client` is gone for good. */
188
+ private expire;
189
+ /** @internal */
190
+ release(): void;
191
+ }
192
+ /** A room class: what {@link RoomServer.define} takes. */
193
+ export type RoomClass = new () => Room<unknown>;
194
+ /** Per-client message rate of a {@link RoomServer}'s rooms; a room may set its own. */
195
+ export interface RoomRateLimits {
196
+ /** Messages per second refilled into each client's bucket (default 120); `Room.maxMessagesPerSecond` overrides it. */
197
+ messagesPerSecond?: number;
198
+ /** Bucket size: the most messages at once (default 60); `Room.messageBurst` overrides it. */
199
+ burst?: number;
200
+ }
201
+ /** Options of {@link RoomServer}. Every limit has a safe default. */
202
+ export interface RoomServerOptions {
203
+ /** Milliseconds a new connection has to send its join; then it is closed with `CloseCode.timeout` (default 10,000). */
204
+ joinTimeout?: number;
205
+ /** Connections at once, in rooms or still joining (default 1,024); the next is closed with `CloseCode.full`. */
206
+ maxConnections?: number;
207
+ /**
208
+ * Rooms at once, those still in `onCreate` included (default 256). Past it `create` rejects with MargoError
209
+ * `'failed'`, and a client's `create` or `joinOrCreate` that would make one more is refused.
210
+ */
211
+ maxRooms?: number;
212
+ /** Message rate per client (defaults 120 per second, bursts of 60); a client over it is closed with `CloseCode.rateLimit`. */
213
+ limits?: RoomRateLimits;
214
+ }
215
+ /**
216
+ * Hosts rooms and matches clients to them. Hand it connections (`listener.onconnection = (c) => rooms.accept(c)`);
217
+ * each connection's first message names the room it wants.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * const rooms = new RoomServer({ maxRooms: 100 });
222
+ * rooms.define('lobby', Lobby);
223
+ * listener.onconnection = (connection) => rooms.accept(connection);
224
+ * ```
225
+ */
226
+ export declare class RoomServer {
227
+ private readonly classes;
228
+ private readonly live;
229
+ /** Rooms whose onCreate is still running: not joinable yet, but joins for them wait for it. */
230
+ private readonly creating;
231
+ /** Connections that have not sent their join yet. */
232
+ private readonly joining;
233
+ private open;
234
+ private sessions;
235
+ private closed;
236
+ private readonly joinTimeout;
237
+ private readonly maxConnections;
238
+ private readonly maxRooms;
239
+ private readonly rate;
240
+ private readonly burst;
241
+ /**
242
+ * Called with each error a room hook (`onCreate`, `onJoin`, `onLeave`, `onDispose`), message handler, timed patch
243
+ * or `setSimulationInterval` step threw, and the room (undefined when its `onCreate` threw). The client concerned
244
+ * is closed with `CloseCode.error`; a throwing patch or step stops its whole room (every client closed with
245
+ * `CloseCode.error`, the room disposed). The server keeps running. Default: `console.error`.
246
+ */
247
+ onerror: ((error: unknown, room: Room | undefined) => void) | null;
248
+ /** @throws RangeError for an option that is not a number in range. */
249
+ constructor(options?: RoomServerOptions);
250
+ /** Every live room. */
251
+ get rooms(): Room[];
252
+ /** Connections open now: in rooms, or still joining. */
253
+ get connections(): number;
254
+ private report;
255
+ /**
256
+ * Makes rooms named `name` from `Class`, created with `defaults` merged under the client's options.
257
+ * @throws TypeError for a name defined twice.
258
+ */
259
+ define(name: string, Class: RoomClass, defaults?: RoomOptions): this;
260
+ /**
261
+ * Creates a room named `name` now, without a client. The room is listed and joinable once its `onCreate` resolved;
262
+ * when `onCreate` throws, the room is disposed and the promise rejects with that error.
263
+ * @throws MargoError `failed` for an undefined name or when `maxRooms` rooms exist, `disposed` once the server is
264
+ * closed; RangeError when the room class sets `maxMessagesPerSecond` or `messageBurst` out of range.
265
+ */
266
+ create(name: string, options?: RoomOptions): Promise<Room>;
267
+ /** Whether `maxRooms` rooms exist (those in `onCreate` count). */
268
+ private get full();
269
+ /**
270
+ * Takes a new client connection; its first message (a join) picks or creates the room. When a room hook throws
271
+ * during the join, `onerror` gets the error and the connection closes with `CloseCode.error`. A connection past
272
+ * `maxConnections` is closed at once with `CloseCode.full`; one that sends no join within `joinTimeout` is closed
273
+ * with `CloseCode.timeout`.
274
+ * @throws MargoError `disposed` once closed.
275
+ */
276
+ accept(connection: Connection): void;
277
+ private refuse;
278
+ private join;
279
+ /** Disconnects every room and closes connections still joining. */
280
+ close(): void;
281
+ /** Same as close, for `using`. */
282
+ [Symbol.dispose](): void;
283
+ }
284
+ /** A joined room, on the client. */
285
+ export declare class JoinedRoom<State = unknown> {
286
+ private readonly connection;
287
+ private readonly schema;
288
+ private readonly stateType;
289
+ /** The room's id (for `joinById`). */
290
+ readonly roomId: string;
291
+ /** This client's seat id. */
292
+ readonly sessionId: string;
293
+ /**
294
+ * What `RoomsClient.reconnect` takes to come back to this seat, '' when the room keeps no seats. Good once: a
295
+ * reconnect gives a new one. Keep it private to this player: whoever holds it can take the seat.
296
+ */
297
+ readonly reconnectionToken: string;
298
+ private current;
299
+ private readonly stateHandlers;
300
+ private readonly messageHandlers;
301
+ private readonly leaveHandlers;
302
+ /** @internal */
303
+ constructor(connection: Connection, schema: UntypedSchema, stateType: string, roomId: string, sessionId: string, reconnectionToken: string);
304
+ /** The newest state (undefined until the first arrives). Treat it as read-only. */
305
+ get state(): State;
306
+ private receive;
307
+ /** Calls `handler` with each new state. Returns a function that removes it. */
308
+ onStateChange(handler: (state: State) => void): () => void;
309
+ /** Calls `handler` with each message of `type` (`'*'` for types without their own handler). Returns a remover. */
310
+ onMessage<T = unknown>(type: string, handler: (message: T) => void): () => void;
311
+ /** Calls `handler` with the close code when this client leaves or is removed. Returns a remover. */
312
+ onLeave(handler: (code: number) => void): () => void;
313
+ /** The states as an async iterator, until the client leaves or `signal` aborts. */
314
+ states({ signal }?: {
315
+ signal?: AbortSignal;
316
+ }): AsyncGenerator<State, void, undefined>;
317
+ /** Sends message `type` with a JSON payload to the room. */
318
+ send(type: string, message?: unknown): void;
319
+ /** Leaves the room (its `onLeave` sees `consented: true`). */
320
+ leave(): void;
321
+ /** Same as leave, for `using`. */
322
+ [Symbol.dispose](): void;
323
+ }
324
+ /** Options of a {@link RoomsClient} join. */
325
+ export interface JoinOptions<S> {
326
+ /** The schema the room's state uses (the same as the server's). */
327
+ schema: SchemaCodec<SchemaShape> | UntypedSchema;
328
+ /** The state's struct name. */
329
+ stateType: string;
330
+ /** Aborts the join. */
331
+ signal?: AbortSignal;
332
+ /** @internal phantom type of the state */
333
+ state?: S;
334
+ }
335
+ /**
336
+ * Joins rooms. `connect` opens a new connection for each join (one room per connection), for example
337
+ * `() => openWebSocket(url)`.
338
+ *
339
+ * @example
340
+ * ```ts
341
+ * const client = new RoomsClient(() => openWebSocket('wss://game.example.com'));
342
+ * const room = await client.joinOrCreate('lobby', { mode: 'duel' }, { schema, stateType: 'State' });
343
+ * room.onStateChange((state) => draw(state));
344
+ * room.send('move', { x: 1 });
345
+ * ```
346
+ */
347
+ export declare class RoomsClient {
348
+ private readonly connect;
349
+ /** @param connect Opens one connection to the room server. */
350
+ constructor(connect: () => Promise<Connection>);
351
+ /** Joins an open room named `name`, or creates one. */
352
+ joinOrCreate<S>(name: string, options: RoomOptions, join: JoinOptions<S>): Promise<JoinedRoom<S>>;
353
+ /** Creates a new room named `name`. */
354
+ create<S>(name: string, options: RoomOptions, join: JoinOptions<S>): Promise<JoinedRoom<S>>;
355
+ /** Joins an open room named `name`; fails when there is none. */
356
+ join<S>(name: string, options: RoomOptions, join: JoinOptions<S>): Promise<JoinedRoom<S>>;
357
+ /** Joins the room with id `roomId`. */
358
+ joinById<S>(roomId: string, options: RoomOptions, join: JoinOptions<S>): Promise<JoinedRoom<S>>;
359
+ /**
360
+ * Goes back to a held seat with the `reconnectionToken` of a dropped {@link JoinedRoom}, while the room's
361
+ * `reconnectWindow` lasts. The room's whole state follows. Rejects with MargoError `failed` once the seat is gone.
362
+ */
363
+ reconnect<S>(token: string, join: JoinOptions<S>): Promise<JoinedRoom<S>>;
364
+ private open;
365
+ }
366
+ export {};