@crowdedkingdoms/crowdyjs 18.39.1 → 18.40.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/MIGRATION.md +62 -0
  2. package/README.md +420 -17
  3. package/dist/binary-wire.d.ts +94 -1
  4. package/dist/binary-wire.d.ts.map +1 -1
  5. package/dist/binary-wire.js +122 -20
  6. package/dist/crowdy-client.d.ts +7 -0
  7. package/dist/crowdy-client.d.ts.map +1 -1
  8. package/dist/crowdy-client.js +3 -0
  9. package/dist/default-origin.d.ts +6 -6
  10. package/dist/default-origin.d.ts.map +1 -1
  11. package/dist/default-origin.js +6 -6
  12. package/dist/domains/admin.d.ts +7 -0
  13. package/dist/domains/admin.d.ts.map +1 -1
  14. package/dist/domains/admin.js +1 -0
  15. package/dist/domains/exec.d.ts +91 -3
  16. package/dist/domains/exec.d.ts.map +1 -1
  17. package/dist/domains/exec.js +132 -5
  18. package/dist/domains/fleetSessions.d.ts +87 -0
  19. package/dist/domains/fleetSessions.d.ts.map +1 -0
  20. package/dist/domains/fleetSessions.js +87 -0
  21. package/dist/dropped-read.d.ts +2 -1
  22. package/dist/dropped-read.d.ts.map +1 -1
  23. package/dist/dropped-read.js +2 -6
  24. package/dist/errors.d.ts +59 -0
  25. package/dist/errors.d.ts.map +1 -1
  26. package/dist/errors.js +70 -0
  27. package/dist/fleet/index.d.ts +4 -0
  28. package/dist/fleet/index.d.ts.map +1 -0
  29. package/dist/fleet/index.js +21 -0
  30. package/dist/fleet/session.d.ts +730 -0
  31. package/dist/fleet/session.d.ts.map +1 -0
  32. package/dist/fleet/session.js +1376 -0
  33. package/dist/fleet/socket.d.ts +59 -0
  34. package/dist/fleet/socket.d.ts.map +1 -0
  35. package/dist/fleet/socket.js +111 -0
  36. package/dist/fleet-wire.d.ts +272 -0
  37. package/dist/fleet-wire.d.ts.map +1 -0
  38. package/dist/fleet-wire.js +472 -0
  39. package/dist/generated/graphql-schema.d.ts +176 -13
  40. package/dist/generated/graphql-schema.d.ts.map +1 -1
  41. package/dist/generated/graphql-schema.js +15 -3
  42. package/dist/generated/graphql.d.ts +79 -0
  43. package/dist/generated/graphql.d.ts.map +1 -1
  44. package/dist/generated/graphql.js +5 -0
  45. package/dist/index.d.ts +6 -3
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +7 -3
  48. package/dist/server-only.d.ts +54 -0
  49. package/dist/server-only.d.ts.map +1 -0
  50. package/dist/server-only.js +55 -0
  51. package/package.json +5 -1
@@ -0,0 +1,730 @@
1
+ import { type ChannelSendInput, type SpatialSendBase } from '../binary-wire.js';
2
+ import { CrowdyError } from '../errors.js';
3
+ import { type FleetId } from '../fleet-wire.js';
4
+ import type { CrowdyLogger } from '../logger.js';
5
+ import type { UdpNotification, UdpNotificationHandlers } from '../realtime.js';
6
+ import { type FleetServer, type FleetSocketFactory } from './socket.js';
7
+ /**
8
+ * What a fleet session is made from and refreshed with: the answer of the Application API's
9
+ * `openFleetSession` or `refreshFleetSession` (`client.fleetSessions.open` / `refresh`), or
10
+ * the same fields from your own HTTP client.
11
+ */
12
+ export interface FleetSessionGrant {
13
+ /** The fleet token: 64 characters. It signs the session and stays on your server. */
14
+ token: string;
15
+ /** The fleet token's id, as a decimal string. */
16
+ gameTokenId: string;
17
+ /** The app the session is in, as a decimal string. */
18
+ appId: string;
19
+ /** When the session ends unless it is refreshed first (ISO 8601). */
20
+ expiresAt?: string | null;
21
+ /** How many players the session may carry at once. */
22
+ maxPlayers?: number | null;
23
+ /** The realtime server to connect to. */
24
+ server: FleetServer;
25
+ }
26
+ /** A player's app token, as `mintManagedPlayerToken` or `refreshAppToken` answered it. */
27
+ export interface FleetPlayerToken {
28
+ /** The player's app token: 64 characters. It proves the carry and is not sent. */
29
+ token: string;
30
+ /** The player's app token's id. */
31
+ gameTokenId: FleetId;
32
+ /**
33
+ * After `refreshAppToken`: the game token id this session carries the same player under
34
+ * now. With it the row moves to the new id at once and the player stays carried
35
+ * throughout: sends for the player name the new id from the moment the `FLEET_CARRY` goes
36
+ * out, and the old id's late frames are ignored. Without it the session learns that the two
37
+ * tokens are one player only from the carry's answer, so sends for the new id are refused
38
+ * here until then. It must name the same player.
39
+ */
40
+ replaces?: FleetId | null;
41
+ }
42
+ /**
43
+ * How a carry ended. The first five are `FLEET_CARRY_RESULT`'s status; the rest are this
44
+ * session's own.
45
+ */
46
+ export type FleetCarryOutcome =
47
+ /** The session carries the player; the result names their user id. */
48
+ 'carried'
49
+ /**
50
+ * No live token by that id: it expired, the sign-in ended, or it is another app's. The
51
+ * session asks once more, 250 ms later, before it settles on this: a token minted a moment
52
+ * ago may not have reached the realtime server yet.
53
+ */
54
+ | 'noLiveToken'
55
+ /** The token belongs to another organization's player. */
56
+ | 'otherOrganization'
57
+ /**
58
+ * The proof or its time failed: a wrong token, or this machine's clock is more than 30
59
+ * seconds from the server's.
60
+ */
61
+ | 'proofFailed'
62
+ /** The session already carries as many players as it may (`maxPlayers`). */
63
+ | 'sessionFull'
64
+ /** A status this build does not know; `wireStatus` has the byte. */
65
+ | 'refused'
66
+ /** No answer came within `carryTimeoutMs` of the first send. */
67
+ | 'timedOut'
68
+ /**
69
+ * The session's table is full, so nothing was sent: it holds `maxPlayers` rows and
70
+ * {@link FLEET_TABLE_MARGIN} more, carried players and carries waiting together. Release
71
+ * players who left, or open another session.
72
+ */
73
+ | 'tableFull'
74
+ /** `release` was called for the player before the answer came. */
75
+ | 'released'
76
+ /** The session was closed before the answer came. */
77
+ | 'closed';
78
+ /** The result of {@link FleetSession.carry}. */
79
+ export interface FleetCarryResult {
80
+ playerGameTokenId: string;
81
+ /** The player's user id when carried (what `ExecConnection.callAs` takes); null otherwise. */
82
+ userId: string | null;
83
+ status: FleetCarryOutcome;
84
+ /** The status byte the server sent; null when none came. */
85
+ wireStatus: number | null;
86
+ /** True when `status` is `'carried'`. */
87
+ carried: boolean;
88
+ }
89
+ /** The server ended a carry (`FLEET_RELEASED`). */
90
+ export interface FleetReleased {
91
+ playerGameTokenId: string;
92
+ /** The player's user id when this session knew it; null otherwise. */
93
+ userId: string | null;
94
+ /**
95
+ * `FleetReleaseReason`: 1 another session carries the player (they moved to another of
96
+ * your servers); 2 the player's sign-in ended; 5 no gameplay input from the player for the
97
+ * app's idle timeout. Treat a value not listed as the carry having ended.
98
+ */
99
+ reason: number;
100
+ }
101
+ /** One row of {@link FleetSession.players}. */
102
+ export interface FleetPlayer {
103
+ gameTokenId: string;
104
+ /** Null until a carry is confirmed. */
105
+ userId: string | null;
106
+ /** The server confirmed a carry and nothing ended it: sends for the player are accepted. */
107
+ carried: boolean;
108
+ /** A `FLEET_CARRY` is waiting for its result. */
109
+ pending: boolean;
110
+ }
111
+ /**
112
+ * Which carried players a notification is for.
113
+ *
114
+ * - **A list** (1 to 32 game token ids): the notification arrived inside a `FLEET_DELIVERY`.
115
+ * Deliver it to these players and no others. Every communication arrives this way (spatial
116
+ * voice, text and video, direct messages, channel messages and channel audio), and so does
117
+ * a client's event or an app-defined spatial message that only some of your players may
118
+ * receive.
119
+ * - **`null`**: the notification arrived plain, once for the session. It is for every one of
120
+ * your players in range, however many that is. State arrives this way (actor updates and
121
+ * departures, voxel edits, events, app-defined spatial messages, chunk changes).
122
+ */
123
+ export type FleetPlayers = readonly string[] | null;
124
+ type Notified<K extends keyof UdpNotificationHandlers> = Parameters<NonNullable<UdpNotificationHandlers[K]>>[0];
125
+ /**
126
+ * A fleet session's callbacks: the realtime client's notification handlers, each with the
127
+ * players the notification is for ({@link FleetPlayers}), and the session's own events. Every
128
+ * handler is optional. A handler that throws is reported to {@link error} and stops nothing.
129
+ */
130
+ export interface FleetHandlers {
131
+ actorUpdate?(notification: Notified<'actorUpdate'>, players: FleetPlayers): void;
132
+ voxelUpdate?(notification: Notified<'voxelUpdate'>, players: FleetPlayers): void;
133
+ actorLeft?(notification: Notified<'actorLeft'>, players: FleetPlayers): void;
134
+ chunkChanged?(notification: Notified<'chunkChanged'>, players: FleetPlayers): void;
135
+ clientEvent?(notification: Notified<'clientEvent'>, players: FleetPlayers): void;
136
+ serverEvent?(notification: Notified<'serverEvent'>, players: FleetPlayers): void;
137
+ genericSpatial?(notification: Notified<'genericSpatial'>, players: FleetPlayers): void;
138
+ audio?(notification: Notified<'audio'>, players: FleetPlayers): void;
139
+ video?(notification: Notified<'video'>, players: FleetPlayers): void;
140
+ text?(notification: Notified<'text'>, players: FleetPlayers): void;
141
+ singleActorMessage?(notification: Notified<'singleActorMessage'>, players: FleetPlayers): void;
142
+ channelMessage?(notification: Notified<'channelMessage'>, players: FleetPlayers): void;
143
+ channelAudio?(notification: Notified<'channelAudio'>, players: FleetPlayers): void;
144
+ /** Every notification above, before its own handler. */
145
+ any?(notification: UdpNotification, players: FleetPlayers): void;
146
+ /**
147
+ * The server refused one send, by its sequence number. `UNAUTHORIZED` answers a message for
148
+ * a player the server does not count as carried by this session, or a player whose access
149
+ * to the app was suspended or ended: stop serving that player. `TOKEN_EXPIRED` answers a
150
+ * send that landed just before the carried player's own token expired; `FLEET_RELEASED`
151
+ * with reason 2 follows. The sequence number is one byte shared by everything the session
152
+ * sends, so match it against the sequence numbers your sends resolved with, soon after: a
153
+ * refusal names no player.
154
+ *
155
+ * `verified` is true when the refusal arrived inside a signed bundle the session verified
156
+ * with the fleet token. Realtime servers from v0.50.3 send a session's refusals that way.
157
+ * An earlier server sends a refusal alone, as `[3][seq][code]`, which has no room for an
158
+ * HMAC, and then `verified` is false: anyone who can reach the session's socket could have
159
+ * forged it. **Treat an unverified refusal as a hint.** Stop sending for the player it
160
+ * points at, then carry the player again (the answer to a carry is always verified) or
161
+ * check the player's access through the Application API, and act on that answer. The
162
+ * session itself changes no state on a refusal, whatever its code: the signed word that
163
+ * the session's own token ended is `sessionReleased`.
164
+ */
165
+ genericError?(notification: Notified<'genericError'>, verified: boolean): void;
166
+ /**
167
+ * Every carry the server answered or that timed out, including the carries made again
168
+ * after the session moved. A carry ended here before it was sent (`'tableFull'`,
169
+ * `'released'`, `'closed'`) reaches only the promise `carry` returned.
170
+ */
171
+ carryResult?(result: FleetCarryResult): void;
172
+ /** The server ended a carry. The session no longer carries the player when this fires. */
173
+ released?(released: FleetReleased): void;
174
+ /**
175
+ * The session needs another realtime server: the one it is on told it to connect elsewhere
176
+ * (and keeps answering for about 5 seconds), or said nothing for `silenceTimeoutMs`.
177
+ * `refreshDue()` is true: call `refreshFleetSession` without a `currentServer`
178
+ * (`refreshInput()` leaves it out) and give the answer to `applyRefresh`. A session that was
179
+ * closed through the Application API is told by `sessionReleased` with reason 0 on realtime
180
+ * servers from v0.50.3; an earlier server sends it nothing, so the silence shows it here.
181
+ * Either way the refresh answers `NOT_FOUND`.
182
+ */
183
+ moveOrdered?(): void;
184
+ /**
185
+ * The realtime server released the session, in a frame signed with the fleet token
186
+ * (`SessionReleaseReason`): it answers this session no more and its carries have ended.
187
+ * Reason 0 is the fleet token revoked (the session was closed through the Application API,
188
+ * or its organization token was revoked); 2 is the fleet token expiring; 1, 3 and 4 are
189
+ * staleness, overload and a move.
190
+ * Whatever the reason, `refreshDue()` is true and `refreshInput()` names no server, as
191
+ * after a move order. A refresh that succeeds reconnects and carries every player again;
192
+ * one refused `NOT_FOUND` means the session ended (after reason 0 or 2 it has), so open a new
193
+ * one.
194
+ */
195
+ sessionReleased?(reason: number): void;
196
+ status?(status: FleetSessionStatus): void;
197
+ /** A socket failure, or a handler that threw. */
198
+ error?(error: Error): void;
199
+ }
200
+ /**
201
+ * - `idle`: made, and not yet connected.
202
+ * - `connecting`: the socket is open and the capabilities are sent; nothing has verified yet.
203
+ * - `connected`: the realtime server answered with something that verified.
204
+ * - `released`: the realtime server released the session; refresh it.
205
+ * - `closed`: `close()` was called.
206
+ */
207
+ export type FleetSessionStatus = 'idle' | 'connecting' | 'connected' | 'released' | 'closed';
208
+ export interface FleetSessionConfig {
209
+ /** `openFleetSession`'s answer (`client.fleetSessions.open(appId)`). */
210
+ session: FleetSessionGrant;
211
+ handlers?: FleetHandlers;
212
+ /**
213
+ * Ask for the state this session's own carried players sent, when another of its carried
214
+ * players is in range (`ClientCapability.FLEET_OWN_STATE`). Default false: a game server
215
+ * simulates its own players. A voxel edit reaches the session that sent it either way.
216
+ */
217
+ fleetOwnState?: boolean;
218
+ /**
219
+ * Ask for a carried speaker's own spatial voice and video inside the deliveries
220
+ * (`ClientCapability.OWN_MEDIA_ECHO`). Default false.
221
+ */
222
+ ownMediaEcho?: boolean;
223
+ /** An unanswered `FLEET_CARRY` is sent again this often, with a new time and proof. Default 250. */
224
+ carryRetryMs?: number;
225
+ /** A carry with no answer this long after its first send ends `'timedOut'`. Default 5,000. */
226
+ carryTimeoutMs?: number;
227
+ /**
228
+ * The most `FLEET_CARRY` messages sent in any one second, first sends and retries together.
229
+ * Default 60, and never above 63: the realtime servers drop a session's carries past 64 a
230
+ * second without an answer.
231
+ */
232
+ maxCarriesPerSecond?: number;
233
+ /** How often the session's own keepalive (a heartbeat with no actor) is sent. Default 2,000. */
234
+ keepAliveIntervalMs?: number;
235
+ /**
236
+ * A carried player's actor that sent nothing for this long is kept present with a heartbeat
237
+ * under the player's id. Default 2,000; 0 leaves heartbeats to you (`sendHeartbeat`).
238
+ */
239
+ actorHeartbeatMs?: number;
240
+ /**
241
+ * How often the capabilities are sent again once the server answered. Default 15,000, and
242
+ * never more than a third of `silenceTimeoutMs`. The server acknowledges each one with a
243
+ * signed frame, which is what an otherwise idle session hears: one every 15 seconds, so the
244
+ * acknowledgements of two in a row can be lost before 45 seconds of silence have passed.
245
+ */
246
+ capabilitiesIntervalMs?: number;
247
+ /** How often the capabilities are sent again until the server answers. Default 500. */
248
+ bindRetryMs?: number;
249
+ /**
250
+ * How long the realtime server may say nothing that verifies before the session takes it
251
+ * for gone: `refreshDue()` turns true, and the refresh that follows carries every player
252
+ * again. Default 45,000, three times `capabilitiesIntervalMs`; at least 3,000; 0 never
253
+ * does.
254
+ */
255
+ silenceTimeoutMs?: number;
256
+ /**
257
+ * How often the session does its timed work (carry sends and retries, keepalives), in
258
+ * milliseconds. Default 20. 0 starts no timer: call {@link FleetSession.tick} yourself.
259
+ */
260
+ tickIntervalMs?: number;
261
+ /** The UDP socket. Default: `node:dgram` (`nodeFleetSocket()`). */
262
+ socket?: FleetSocketFactory;
263
+ /** Epoch milliseconds. Default `Date.now`. A carry's time comes from it. */
264
+ now?: () => number;
265
+ logger?: CrowdyLogger;
266
+ }
267
+ /** {@link FleetSession.stats}. */
268
+ export interface FleetSessionStats {
269
+ datagramsSent: number;
270
+ bytesSent: number;
271
+ /** Messages sent, by type: 49 and 50 count carries and releases. */
272
+ sentByType: Record<number, number>;
273
+ datagramsReceived: number;
274
+ bytesReceived: number;
275
+ /** Frames dropped because their HMAC did not verify. */
276
+ hmacFailures: number;
277
+ /** Frames dropped because they could not be read. */
278
+ malformed: number;
279
+ /** Notifications dropped because they carried no signature. */
280
+ unsigned: number;
281
+ /**
282
+ * Notifications dropped because they named another app than the session's. A fleet
283
+ * session is in one app, so state or a communication of another app is never its own,
284
+ * however it was signed. Anything but 0 is worth reporting to Crowded Kingdoms.
285
+ */
286
+ wrongApp: number;
287
+ /** Datagrams dropped because they were above 1,242 bytes. */
288
+ oversized: number;
289
+ /** Control frames dropped: bound to another connection, or unbound after the server acknowledged the bound forms. */
290
+ staleControl: number;
291
+ /**
292
+ * `CONTROL_BOUND_ACK`s (46) verified for this connection's nonce: the realtime server's
293
+ * answer to each of the session's capabilities.
294
+ */
295
+ boundControlAcks: number;
296
+ /** `FLEET_CARRY_RESULT`s that matched no carry waiting for one. */
297
+ unmatchedCarryResults: number;
298
+ /** Carries answered "no live token" that were asked once more before settling. */
299
+ noLiveTokenRetries: number;
300
+ /**
301
+ * `FLEET_CARRY_RESULT` and `FLEET_RELEASED` frames that named a game token id this session
302
+ * has replaced with the same player's newer one. They are late words about the old token,
303
+ * and change nothing.
304
+ */
305
+ replacedIdFrames: number;
306
+ /** `GenericErrorResponse`s received, verified or not. */
307
+ errorsReceived: number;
308
+ /** Of those, `UNAUTHORIZED`. */
309
+ unauthorizedReceived: number;
310
+ /** Of `errorsReceived`, those that arrived outside a signed bundle, so nothing verifies them. */
311
+ unverifiedErrorsReceived: number;
312
+ /** Carries refused here because the table was full (`'tableFull'`). */
313
+ carriesRefusedTableFull: number;
314
+ }
315
+ /**
316
+ * A send named a player this session does not carry now: never carried, a carry still
317
+ * waiting for its result, or one that ended. Nothing was sent.
318
+ */
319
+ export declare class FleetNotCarriedError extends CrowdyError {
320
+ readonly code = "FLEET_NOT_CARRIED";
321
+ readonly playerGameTokenId: string;
322
+ constructor(playerGameTokenId: string);
323
+ }
324
+ /** A send's input without what the session supplies: the app and the sequence number. */
325
+ type ForSession<T> = Omit<T, 'appId' | 'sequenceNumber'>;
326
+ type SpatialInput = ForSession<SpatialSendBase>;
327
+ /** The speakers whose spatial voice and video a carried player receives. */
328
+ export interface FleetSpeakerChange {
329
+ /** Only these actors (none for `[]`), everyone in range for `null`; left as it is when omitted. */
330
+ voice?: readonly string[] | null;
331
+ video?: readonly string[] | null;
332
+ }
333
+ /**
334
+ * How many rows a session's table may hold past its `maxPlayers`: room for carries that wait
335
+ * for an answer while the table is full, such as a player's carry with a refreshed token
336
+ * before it replaces the row the same user had. The realtime servers allow a session the
337
+ * same 32 carries past `maxPlayers` at once.
338
+ */
339
+ export declare const FLEET_TABLE_MARGIN = 32;
340
+ /**
341
+ * A fleet session: one realtime session an organization's game server opens for itself, in
342
+ * which it carries the players who are on it (realtime servers v0.50.3). It connects to the
343
+ * realtime server over UDP, so it runs on Node, on a server the organization runs.
344
+ *
345
+ * **Security: an org token and a fleet token never go into a browser page or a game
346
+ * client.** The fleet token signs for every player the session carries. Keep it where the
347
+ * org token is kept, on a server your organization runs. A game on a player's device uses
348
+ * that player's own app token (`client.udp`).
349
+ *
350
+ * ```ts
351
+ * import { createCrowdyClient } from '@crowdedkingdoms/crowdyjs';
352
+ * import { FleetSession } from '@crowdedkingdoms/crowdyjs/fleet';
353
+ *
354
+ * const api = createCrowdyClient({ httpUrl });
355
+ * api.setToken(process.env.CK_ORG_TOKEN); // cko_…, scope fleet:session
356
+ *
357
+ * const fleet = new FleetSession({
358
+ * session: await api.fleetSessions.open(appId), // one session for each game server
359
+ * handlers: {
360
+ * actorUpdate: (n) => world.apply(n), // state: once for the session
361
+ * text: (n, players) => players?.forEach((p) => chat.deliver(p, n)), // only these players
362
+ * released: (r) => roster.remove(r.playerGameTokenId),
363
+ * },
364
+ * });
365
+ * await fleet.connect();
366
+ *
367
+ * // A player joined this server. The token and its id are the player's app token's.
368
+ * const carry = await fleet.carry({ token: player.token, gameTokenId: player.gameTokenId });
369
+ * if (carry.carried) await fleet.sendActorUpdate(carry.playerGameTokenId, { chunk, uuid, state });
370
+ *
371
+ * // Now and then: keep the session, and follow it to another realtime server.
372
+ * if (fleet.refreshDue()) await fleet.applyRefresh(await api.fleetSessions.refresh(fleet.refreshInput()));
373
+ * ```
374
+ *
375
+ * What the session sends: for a carried player, the message that player's own session would
376
+ * send, with the player's game token id in its tail and the HMAC keyed with the fleet token.
377
+ * Under its own game token id it sends only its capabilities (29), `FLEET_CARRY` (49),
378
+ * `FLEET_RELEASE` (50) and its keepalive (26). The platform applies each carried player's own
379
+ * permissions, blocks, age rules, speaker lists, rate budget (500 messages a second, bursts
380
+ * to 1,000) and idle timeout.
381
+ *
382
+ * What it receives: state once for the session, and communications inside `FLEET_DELIVERY`
383
+ * with the carried players who may receive them ({@link FleetPlayers}). Every notification
384
+ * is verified with the fleet token before a handler sees it, and no option turns that off.
385
+ * One that names another app than the session's is dropped and counted (`stats().wrongApp`).
386
+ * A refusal of a send has no room for a signature when it arrives alone, so `genericError`
387
+ * is told whether it was verified.
388
+ *
389
+ * The session makes no Application API call. {@link refreshDue} says when to call
390
+ * `refreshFleetSession`, and {@link applyRefresh} takes the answer.
391
+ */
392
+ export declare class FleetSession {
393
+ private grant;
394
+ private handlers;
395
+ private readonly logger;
396
+ private readonly socketFactory;
397
+ private readonly now;
398
+ private readonly carryRetryMs;
399
+ private readonly carryTimeoutMs;
400
+ private readonly maxCarriesPerSecond;
401
+ private readonly keepAliveIntervalMs;
402
+ private readonly actorHeartbeatMs;
403
+ private readonly capabilitiesIntervalMs;
404
+ private readonly bindRetryMs;
405
+ private readonly silenceTimeoutMs;
406
+ private readonly tickIntervalMs;
407
+ private ctx;
408
+ private socket;
409
+ private server;
410
+ /** Counts connections: a datagram or a send of an earlier one is dropped. */
411
+ private generation;
412
+ private controlNonce;
413
+ /** The server acknowledged this connection's nonce: it sends no unbound control frame. */
414
+ private boundAcked;
415
+ /** Something from the server verified on this connection. */
416
+ private answered;
417
+ /** When the server last said something that verified, or when this connection was opened. */
418
+ private lastHeardAt;
419
+ /** The connection is being opened: nothing goes out before its capabilities. */
420
+ private binding;
421
+ private currentStatus;
422
+ private capabilityFlags;
423
+ private moveWasOrdered;
424
+ /** The server holds no carry for this session: the next refresh carries every player again. */
425
+ private carriesLost;
426
+ private expiresAtMs;
427
+ private grantedAtMs;
428
+ private readonly table;
429
+ /** A player's previous game token id, while the carry that replaces it waits: id -> row key. */
430
+ private readonly aliases;
431
+ /** Game token ids replaced by the same player's newer one, and when: late frames are ignored. */
432
+ private readonly replaced;
433
+ private attemptOrder;
434
+ /** Each `FLEET_CARRY` of the last second: when it was sent, and whether it was a retry. */
435
+ private carrySends;
436
+ private nextSequence;
437
+ private nextCapabilitiesAt;
438
+ private lastKeepAliveAt;
439
+ private timer;
440
+ private ticking;
441
+ private inbound;
442
+ private connecting;
443
+ private readonly counters;
444
+ constructor(config: FleetSessionConfig);
445
+ /** The app the session is in. */
446
+ get appId(): string;
447
+ /** The session's own game token id: what `refreshFleetSession` and `closeFleetSession` name it by. */
448
+ get gameTokenId(): string;
449
+ /** How many players the session may carry at once, when the grant said. */
450
+ get maxPlayers(): number | null;
451
+ /** When the session ends unless it is refreshed first, in epoch milliseconds; null when unknown. */
452
+ get expiresAt(): number | null;
453
+ /** The realtime server the session is on, or will connect to. */
454
+ get currentServer(): FleetServer;
455
+ get status(): FleetSessionStatus;
456
+ /** Replace the handlers. */
457
+ setHandlers(handlers: FleetHandlers): void;
458
+ /** A copy of the session's counters. */
459
+ stats(): FleetSessionStats;
460
+ /** Never the tokens: what a log line or `JSON.stringify` shows of a session. */
461
+ toJSON(): Record<string, unknown>;
462
+ /**
463
+ * Open the socket to the realtime server and bind the session: its capabilities are its
464
+ * first datagram, under its own game token id. Resolves once they are sent. The
465
+ * capabilities go again every `bindRetryMs` until the server answers, since the session's
466
+ * token may reach the server a moment after `openFleetSession` returns; the status is then
467
+ * `'connected'`. Carries asked for before that wait and are sent in order.
468
+ */
469
+ connect(): Promise<void>;
470
+ private open;
471
+ /**
472
+ * Close the socket and stop the timers. Carries waiting for an answer end `'closed'`, and
473
+ * the table is emptied. This does not end the session on the platform: call
474
+ * `client.fleetSessions.close` for that, or it ends at its `expiresAt`.
475
+ */
476
+ close(): void;
477
+ /**
478
+ * True after the realtime server told the session to move, released it (for any reason, the
479
+ * fleet token expiring among them) or went quiet for `silenceTimeoutMs`, until a refresh is
480
+ * applied.
481
+ */
482
+ get moveOrdered(): boolean;
483
+ /**
484
+ * True when it is time to call `refreshFleetSession`: a move was ordered
485
+ * ({@link moveOrdered}), or less than half of the session's lifetime is left (12 hours into
486
+ * a 24-hour session, counted from when this object was given the grant). The session makes
487
+ * no call itself: ask this from your own loop.
488
+ */
489
+ refreshDue(): boolean;
490
+ /**
491
+ * The input of `refreshFleetSession` for this session (`client.fleetSessions.refresh`). It
492
+ * names the realtime server the session is on, so the session stays there while that
493
+ * server still serves the app. After a move was ordered it names none, and the answer's
494
+ * server is the next one.
495
+ *
496
+ * `currentServer` is an IPv4 address and a port, which is all the Application API takes.
497
+ * Every realtime server has an IPv4 address. A session that was given none (it connected
498
+ * over `ip6`) sends no `currentServer`, so each refresh may answer another server.
499
+ */
500
+ refreshInput(): {
501
+ appId: string;
502
+ gameTokenId: string;
503
+ currentServer?: {
504
+ ip4: string;
505
+ clientPort: number;
506
+ };
507
+ };
508
+ /**
509
+ * Take the answer of `refreshFleetSession`: the new expiry and the realtime server.
510
+ *
511
+ * - **The same server:** the carries stand. The session sends its capabilities again and no
512
+ * `FLEET_CARRY`.
513
+ * - **Another server**, or the same one after it released the session or went quiet: the
514
+ * server holds no carry. The session connects there, sends its capabilities, then a new `FLEET_CARRY` (a
515
+ * new time and proof) for every player, paced under 64 a second. Until each is answered,
516
+ * sends for that player are refused locally; each answer reaches `handlers.carryResult`.
517
+ *
518
+ * @throws {CrowdyError} with nothing changed, for an answer that is another session's (a
519
+ * different app or `gameTokenId`) or carries no usable token or server.
520
+ */
521
+ applyRefresh(answer: FleetSessionGrant): Promise<void>;
522
+ /**
523
+ * Start or stop asking for the state this session's own carried players sent
524
+ * (`ClientCapability.FLEET_OWN_STATE`). Advertised at once when connected and it changed.
525
+ */
526
+ setFleetOwnState(on: boolean): Promise<void>;
527
+ /** Start or stop asking for a carried speaker's own spatial voice and video. */
528
+ setOwnMediaEcho(on: boolean): Promise<void>;
529
+ private setCapability;
530
+ /**
531
+ * Start carrying a player. `FLEET_CARRY` is sent when the session is connected and its turn
532
+ * comes (carries are paced under 64 a second), and again every `carryRetryMs` with a new
533
+ * time and proof until `FLEET_CARRY_RESULT` arrives or `carryTimeoutMs` passes. Resolves
534
+ * with how it ended; it does not reject for a refusal. Sends for the player are accepted
535
+ * from the moment the result is `'carried'`.
536
+ *
537
+ * **After you refresh a carried player's token**, call it with the new token and
538
+ * `replaces: <the id the player is carried under>`. The player stays carried throughout,
539
+ * with their actors and speaker lists: the carry made with the old token stands until the
540
+ * new one takes effect, and there is no `released` event. From the moment the new
541
+ * `FLEET_CARRY` goes out, every send for the player names the new id, whichever of the two
542
+ * ids you pass to the send; the realtime server holds those sends behind the carry. Once
543
+ * the result is `'carried'` the old id names nothing in this session. If the new carry is
544
+ * refused, the player stays carried under the old id.
545
+ *
546
+ * A carry answered "no live token" is asked once more, 250 ms later, before it settles. A
547
+ * carry that is refused or times out leaves the player not carried under that game token
548
+ * id; the session sends `FLEET_RELEASE` for one that timed out, since the server may hold a
549
+ * carry whose answers were lost.
550
+ *
551
+ * A carry for a new player when the table is full ends `'tableFull'` with nothing sent
552
+ * ({@link tableLimit}).
553
+ *
554
+ * @throws {RangeError} (as a rejection) for a token that is not 64 characters, or a game
555
+ * token id that is not a number or is the session's own.
556
+ */
557
+ carry(player: FleetPlayerToken): Promise<FleetCarryResult>;
558
+ /** The row a game token id names: its own, or the one a waiting replacement moved it to. */
559
+ private rowOf;
560
+ /** `id` was replaced by the same player's newer token: late frames that name it are ignored. */
561
+ private retire;
562
+ /**
563
+ * Move a player's row to the id of their refreshed token. A carried player stays carried:
564
+ * the carry under the old id stands, and sends keep naming it, until the `FLEET_CARRY` for
565
+ * the new id goes out. A row whose own carry was never confirmed simply takes the new token.
566
+ */
567
+ private supersede;
568
+ /**
569
+ * The player left the game: sends `FLEET_RELEASE` and takes them out of the table at once.
570
+ * Their actors leave as when a player's own session ends, about 5 seconds after their last
571
+ * message. A carry still waiting for the player ends `'released'`. The message has no
572
+ * answer; one that is lost leaves the carry on the server until the player is carried
573
+ * elsewhere, their sign-in ends, or they idle out. Stop sending for a player before you hand
574
+ * them to another server: the other session's carry is what moves them, and no release is
575
+ * needed for it.
576
+ */
577
+ release(playerGameTokenId: FleetId): Promise<void>;
578
+ /**
579
+ * True when the server confirmed a carry of this player and nothing ended it. While a carry
580
+ * with a refreshed token waits, both of the player's ids answer true.
581
+ */
582
+ carries(playerGameTokenId: FleetId): boolean;
583
+ /** Every row of the table: carried players and carries still waiting. */
584
+ players(): FleetPlayer[];
585
+ /**
586
+ * The most rows the table holds, carried players and carries waiting together: `maxPlayers`
587
+ * (1,024 when the grant named none) and {@link FLEET_TABLE_MARGIN} more. A `carry` for a
588
+ * new player past it ends `'tableFull'`.
589
+ */
590
+ get tableLimit(): number;
591
+ /** How many players the server confirmed and nothing ended. */
592
+ get carriedCount(): number;
593
+ /**
594
+ * An actor update for one of the player's actors. The session then keeps that actor
595
+ * present with heartbeats while it sends nothing (`actorHeartbeatMs`), until
596
+ * {@link forgetActor} or the carry ends.
597
+ */
598
+ sendActorUpdate(player: FleetId, input: SpatialInput & {
599
+ state: string;
600
+ }): Promise<number>;
601
+ /** A voxel edit. The player's grid permissions decide it. */
602
+ sendVoxelUpdate(player: FleetId, input: SpatialInput & {
603
+ voxel: {
604
+ x: number;
605
+ y: number;
606
+ z: number;
607
+ };
608
+ voxelType: number;
609
+ voxelState?: string;
610
+ }): Promise<number>;
611
+ /** A client event (`eventType` and a base64 `state`). */
612
+ sendClientEvent(player: FleetId, input: SpatialInput & {
613
+ eventType: number;
614
+ state: string;
615
+ }): Promise<number>;
616
+ /** Spatial text. The player's tier needs `use_text_chat`. */
617
+ sendTextPacket(player: FleetId, input: SpatialInput & {
618
+ text: string;
619
+ }): Promise<number>;
620
+ /** Spatial voice (base64 `audioData`). It does not keep the player from idling out. */
621
+ sendAudioPacket(player: FleetId, input: SpatialInput & {
622
+ audioData: string;
623
+ }): Promise<number>;
624
+ /** One webcam video fragment (base64 `videoData`, from `fragmentFrame`). */
625
+ sendVideoPacket(player: FleetId, input: SpatialInput & {
626
+ videoData: string;
627
+ }): Promise<number>;
628
+ /** An app-defined spatial message (base64 `payload`, at most 1,123 bytes). */
629
+ sendGenericSpatial(player: FleetId, input: SpatialInput & {
630
+ payload?: string | null;
631
+ }): Promise<number>;
632
+ /** A direct message to one actor, named by its chunk and uuid. */
633
+ sendSingleActorMessage(player: FleetId, input: {
634
+ chunk: {
635
+ x: string;
636
+ y: string;
637
+ z: string;
638
+ };
639
+ targetUuid: string;
640
+ payload?: string | null;
641
+ }): Promise<number>;
642
+ /** A channel message. */
643
+ sendChannelMessage(player: FleetId, input: ForSession<ChannelSendInput>): Promise<number>;
644
+ /** Channel audio. */
645
+ sendChannelAudio(player: FleetId, input: ForSession<ChannelSendInput>): Promise<number>;
646
+ /** A channel message only members within `maxDistance` chunks of `chunk` receive. */
647
+ sendRangedChannelMessage(player: FleetId, input: ForSession<ChannelSendInput> & {
648
+ chunk: {
649
+ x: string;
650
+ y: string;
651
+ z: string;
652
+ };
653
+ maxDistance: number;
654
+ }): Promise<number>;
655
+ /**
656
+ * A heartbeat for one of the player's actors, under the player's id: it keeps the actor
657
+ * present without sending its state. The session sends these itself for actors it knows
658
+ * from {@link sendActorUpdate}; call this for an actor it does not know, or with
659
+ * `actorHeartbeatMs: 0`. A heartbeat is not gameplay input: it does not hold off the app's
660
+ * idle timeout.
661
+ */
662
+ sendHeartbeat(player: FleetId, actor: {
663
+ chunk: {
664
+ x: string;
665
+ y: string;
666
+ z: string;
667
+ };
668
+ uuid: string;
669
+ }): Promise<number>;
670
+ /** Stop keeping one of the player's actors present. It leaves about 5 seconds later. */
671
+ forgetActor(player: FleetId, uuid: string): void;
672
+ /**
673
+ * The speakers whose spatial voice and video a carried player receives
674
+ * (`CLIENT_MEDIA_SPEAKERS`, under the player's id). Each carried player has their own
675
+ * lists. A changed kind is sent at once, and every list again with each periodic
676
+ * capabilities advertisement and after the player is carried again.
677
+ * @throws {CrowdyRealtimeError} `SPEAKER_LIST_TOO_LONG` over 32 names; {@link FleetNotCarriedError}.
678
+ */
679
+ setSpeakers(player: FleetId, change: FleetSpeakerChange): Promise<void>;
680
+ private sendSpeakers;
681
+ private resendSpeakers;
682
+ private touchActor;
683
+ private sequence;
684
+ private transmit;
685
+ /** A message for a carried player: the player's id in the tail, signed with the fleet token. */
686
+ private sendFor;
687
+ /**
688
+ * A message of the session's own, under its own game token id. Only four kinds exist: the
689
+ * realtime servers answer any other `UNAUTHORIZED`.
690
+ */
691
+ private sendOwn;
692
+ private sendCapabilities;
693
+ private sendRelease;
694
+ /**
695
+ * Do the session's timed work once: the capabilities and keepalive that are due, the
696
+ * `FLEET_CARRY` sends and retries that are due and that the pace allows, the carries that
697
+ * timed out, and the heartbeats of carried players' actors. The session calls this itself
698
+ * every `tickIntervalMs`; call it yourself with `tickIntervalMs: 0`.
699
+ */
700
+ tick(): Promise<void>;
701
+ private driveCarries;
702
+ private heartbeatActors;
703
+ private onDatagram;
704
+ /**
705
+ * Resolves once every datagram received so far has been verified and its handlers have
706
+ * run: what to wait for before `close()` when nothing received may be lost.
707
+ */
708
+ settled(): Promise<void>;
709
+ private read;
710
+ private handle;
711
+ /**
712
+ * The session needs a refresh before anything else: the server asked it to move, or went
713
+ * quiet. `carriesLost` when the server may hold no carry.
714
+ */
715
+ private orderMove;
716
+ private onSessionReleased;
717
+ private onCarryResult;
718
+ private onReleased;
719
+ /** End a row's waiting carry, if it has one, and tell whoever waits. */
720
+ private settle;
721
+ /** A refusal of one send. It reaches the handler either way, with whether it was verified. */
722
+ private dispatchError;
723
+ /** A verified notification, and the players it is for. */
724
+ private dispatch;
725
+ private setStatus;
726
+ private call;
727
+ private report;
728
+ }
729
+ export {};
730
+ //# sourceMappingURL=session.d.ts.map