@antha/multiplayer-p2p-authoritative-host 0.0.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.
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @antha/multiplayer-p2p-authoritative-host
2
+
3
+ A multiplayer strategy for Antha where the room host owns canonical state and peers send inputs to that host.
@@ -0,0 +1,41 @@
1
+ import { type ApiAndRoomConnectionState, type MultiplayerClientRooms } from '@antha/multiplayer-core';
2
+ import { type JsonCompatibleValue, type PartialWithUndefined, type SelectFrom } from '@augment-vir/common';
3
+ import { P2pAuthoritativeHostMultiplayerController, type P2pAuthoritativeHostMultiplayerControllerParams } from './p2p-authoritative-host-multiplayer-controller.js';
4
+ /**
5
+ * Engine state added by the p2p-authoritative-host multiplayer mod.
6
+ *
7
+ * @category Internal
8
+ */
9
+ export type AnthaMultiplayerP2pAuthoritativeHostState<Input extends JsonCompatibleValue = any, State extends JsonCompatibleValue = any> = {
10
+ /** P2p-authoritative-host controller state. */
11
+ multiplayerP2pAuthoritativeHost: {
12
+ /** Controller used to drive singleplayer or multiplayer state sync. */
13
+ multiplayerController: P2pAuthoritativeHostMultiplayerController<Input, State>;
14
+ /** Current backend API and room connection state. */
15
+ connectionState: ApiAndRoomConnectionState;
16
+ /** Rooms currently available for joining. */
17
+ availableRooms: MultiplayerClientRooms;
18
+ /** Latest state emitted by the multiplayer controller. */
19
+ currentState: State;
20
+ };
21
+ };
22
+ /**
23
+ * Options for {@link createAnthaMultiplayerP2pAuthoritativeHostMod}.
24
+ *
25
+ * @category Internal
26
+ */
27
+ export type AnthaMultiplayerP2pAuthoritativeHostOptions<Input extends JsonCompatibleValue = any, State extends JsonCompatibleValue = any> = SelectFrom<P2pAuthoritativeHostMultiplayerControllerParams<Input, State>, {
28
+ applyInput: true;
29
+ createInitialState: true;
30
+ }> & PartialWithUndefined<SelectFrom<P2pAuthoritativeHostMultiplayerControllerParams<Input, State>, {
31
+ acceptConnection: true;
32
+ gameId: true;
33
+ shouldAcceptInput: true;
34
+ tick: true;
35
+ }>>;
36
+ /**
37
+ * Create the engine mod that owns p2p-authoritative-host multiplayer state.
38
+ *
39
+ * @category Main
40
+ */
41
+ export declare function createAnthaMultiplayerP2pAuthoritativeHostMod<const Input extends JsonCompatibleValue = any, const State extends JsonCompatibleValue = any>(options: Readonly<AnthaMultiplayerP2pAuthoritativeHostOptions<Input, State>>): import("@antha/engine").AnthaMod<NoInfer<AnthaMultiplayerP2pAuthoritativeHostState<NoInfer<Input>, State>>>;
@@ -0,0 +1,61 @@
1
+ import { defineAnthaMod } from '@antha/engine';
2
+ import { ControllerConnectionEvent, ControllerRoomListEvent, emptyApiAndRoomConnectionState, } from '@antha/multiplayer-core';
3
+ import { ControllerStateEvent, P2pAuthoritativeHostMultiplayerController, } from './p2p-authoritative-host-multiplayer-controller.js';
4
+ /**
5
+ * Create the engine mod that owns p2p-authoritative-host multiplayer state.
6
+ *
7
+ * @category Main
8
+ */
9
+ export function createAnthaMultiplayerP2pAuthoritativeHostMod(options) {
10
+ return defineAnthaMod({
11
+ modName: 'antha-multiplayer-p2p-authoritative-host',
12
+ execute({ state }) {
13
+ if (!state.multiplayerP2pAuthoritativeHost) {
14
+ state.multiplayerP2pAuthoritativeHost = createP2pAuthoritativeHostState(options);
15
+ state.multiplayerP2pAuthoritativeHost.multiplayerController.listen(ControllerConnectionEvent, ({ detail: newConnectionState }) => {
16
+ if (!state.multiplayerP2pAuthoritativeHost) {
17
+ return;
18
+ }
19
+ state.multiplayerP2pAuthoritativeHost.connectionState = newConnectionState;
20
+ });
21
+ state.multiplayerP2pAuthoritativeHost.multiplayerController.listen(ControllerRoomListEvent, ({ detail: rooms }) => {
22
+ if (!state.multiplayerP2pAuthoritativeHost) {
23
+ return;
24
+ }
25
+ state.multiplayerP2pAuthoritativeHost.availableRooms = rooms;
26
+ });
27
+ state.multiplayerP2pAuthoritativeHost.multiplayerController.listen((ControllerStateEvent), ({ detail }) => {
28
+ if (!state.multiplayerP2pAuthoritativeHost) {
29
+ return;
30
+ }
31
+ state.multiplayerP2pAuthoritativeHost.currentState = detail.state;
32
+ });
33
+ }
34
+ },
35
+ cleanup({ state }) {
36
+ state.multiplayerP2pAuthoritativeHost?.multiplayerController.destroy();
37
+ },
38
+ });
39
+ }
40
+ function createP2pAuthoritativeHostState(options) {
41
+ const multiplayerController = new P2pAuthoritativeHostMultiplayerController({
42
+ gameId: options.gameId || 'antha',
43
+ applyInput: options.applyInput,
44
+ createInitialState: options.createInitialState,
45
+ ...(options.acceptConnection && {
46
+ acceptConnection: options.acceptConnection,
47
+ }),
48
+ ...(options.shouldAcceptInput && {
49
+ shouldAcceptInput: options.shouldAcceptInput,
50
+ }),
51
+ ...(options.tick && {
52
+ tick: options.tick,
53
+ }),
54
+ });
55
+ return {
56
+ multiplayerController,
57
+ connectionState: emptyApiAndRoomConnectionState,
58
+ availableRooms: {},
59
+ currentState: multiplayerController.getState(),
60
+ };
61
+ }
@@ -0,0 +1,2 @@
1
+ export * from './antha-multiplayer-p2p-authoritative-host.mod.js';
2
+ export * from './p2p-authoritative-host-multiplayer-controller.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './antha-multiplayer-p2p-authoritative-host.mod.js';
2
+ export * from './p2p-authoritative-host-multiplayer-controller.js';
@@ -0,0 +1,247 @@
1
+ import { type ApiAndRoomConnectionState, type ClientId, ControllerClientEvent, ControllerConnectionEvent, ControllerRoomListEvent, type MultiplayerInitParams, type MultiplayerRoomConnection, MultiplayerRoomController, type RoomInput, RoomRejectionError } from '@antha/multiplayer-core';
2
+ import { type JsonCompatibleValue, type MaybePromise, type PartialWithUndefined } from '@augment-vir/common';
3
+ import { ListenTarget, type TypedCustomEventInit } from 'typed-event-target';
4
+ /**
5
+ * Message type for {@link P2pAuthoritativeHostMessage}.
6
+ *
7
+ * @category Internal
8
+ */
9
+ export declare enum P2pAuthoritativeHostMessageType {
10
+ Input = "input",
11
+ StateSnapshot = "state-snapshot"
12
+ }
13
+ /**
14
+ * A state snapshot emitted when the authoritative state changes.
15
+ *
16
+ * @category Internal
17
+ */
18
+ export type P2pAuthoritativeHostStateSnapshot<State extends JsonCompatibleValue> = {
19
+ sequence: number;
20
+ state: State;
21
+ };
22
+ /**
23
+ * Data received from {@link ControllerStateEvent}.
24
+ *
25
+ * @category Internal
26
+ */
27
+ export type StateEventDetail<Input extends JsonCompatibleValue, State extends JsonCompatibleValue> = P2pAuthoritativeHostStateSnapshot<State> & PartialWithUndefined<{
28
+ clientId: ClientId;
29
+ input: Input;
30
+ }>;
31
+ /**
32
+ * Messages exchanged by the authoritative-host state strategy.
33
+ *
34
+ * @category Internal
35
+ */
36
+ export type P2pAuthoritativeHostMessage<Input extends JsonCompatibleValue, State extends JsonCompatibleValue> = {
37
+ type: P2pAuthoritativeHostMessageType.Input;
38
+ input: Input;
39
+ } | ({
40
+ type: P2pAuthoritativeHostMessageType.StateSnapshot;
41
+ } & StateEventDetail<Input, State>);
42
+ /**
43
+ * Game-specific logic for an authoritative-host connection.
44
+ *
45
+ * @category Internal
46
+ */
47
+ export type P2pAuthoritativeHostGameDefinition<Input extends JsonCompatibleValue, State extends JsonCompatibleValue> = {
48
+ /** Create the initial game state before singleplayer or multiplayer starts. */
49
+ createInitialState: () => State;
50
+ /** Apply an accepted input to the current authoritative state. */
51
+ applyInput: (params: Readonly<{
52
+ clientId: ClientId;
53
+ input: Readonly<Input>;
54
+ state: Readonly<State>;
55
+ }>) => State;
56
+ /** Return `false` to reject an input before it changes authoritative state. */
57
+ shouldAcceptInput?: (params: Readonly<{
58
+ clientId: ClientId;
59
+ input: Readonly<Input>;
60
+ state: Readonly<State>;
61
+ }>) => boolean | undefined;
62
+ /** Advance authoritative state from elapsed time without a player input. */
63
+ tick?: (params: Readonly<{
64
+ elapsedMs: number;
65
+ state: Readonly<State>;
66
+ }>) => State;
67
+ };
68
+ /**
69
+ * Constructor parameters for {@link P2pAuthoritativeHostMultiplayerController}.
70
+ *
71
+ * @category Internal
72
+ */
73
+ export type P2pAuthoritativeHostMultiplayerControllerParams<Input extends JsonCompatibleValue, State extends JsonCompatibleValue> = {
74
+ /**
75
+ * A unique string id that represents your game so that your lobby server can serve multiple
76
+ * games at once. Your lobby server will need to know this game id ahead of time and match it to
77
+ * your frontend's origin.
78
+ */
79
+ gameId: string;
80
+ } & P2pAuthoritativeHostGameDefinition<Input, State> & PartialWithUndefined<{
81
+ /**
82
+ * This is fired when a WebRTC peer attempts to connect to the host client. Return `true` to
83
+ * accept the connection. Return `false` to reject it.
84
+ *
85
+ * @default accept all connections
86
+ */
87
+ acceptConnection?: ((connectingClientId: ClientId, controller: P2pAuthoritativeHostMultiplayerController<Input, State>) => MaybePromise<boolean>) | undefined;
88
+ }>;
89
+ declare const ControllerStateEvent_base: (new (eventInitDict: {
90
+ bubbles?: boolean;
91
+ cancelable?: boolean;
92
+ composed?: boolean;
93
+ detail: any;
94
+ }) => import("typed-event-target").TypedCustomEvent<any, "controller-state">) & Pick<{
95
+ new (type: string, eventInitDict?: EventInit): Event;
96
+ prototype: Event;
97
+ readonly NONE: 0;
98
+ readonly CAPTURING_PHASE: 1;
99
+ readonly AT_TARGET: 2;
100
+ readonly BUBBLING_PHASE: 3;
101
+ }, "prototype" | "NONE" | "CAPTURING_PHASE" | "AT_TARGET" | "BUBBLING_PHASE"> & Pick<import("typed-event-target").TypedCustomEvent<any, "controller-state">, "type">;
102
+ /**
103
+ * This is fired whenever the local authoritative-host state view updates.
104
+ *
105
+ * @category Events
106
+ */
107
+ export declare class ControllerStateEvent<State extends JsonCompatibleValue, Input extends JsonCompatibleValue = any> extends ControllerStateEvent_base {
108
+ detail: Readonly<StateEventDetail<Input, State>>;
109
+ constructor(eventInitDict: TypedCustomEventInit<Readonly<StateEventDetail<Input, State>>>);
110
+ }
111
+ /**
112
+ * All events emitted by this controller.
113
+ *
114
+ * @category Internal
115
+ */
116
+ export type AllP2pAuthoritativeHostMultiplayerControllerEvents<Input extends JsonCompatibleValue, State extends JsonCompatibleValue> = ControllerStateEvent<State, Input> | ControllerRoomListEvent | ControllerClientEvent | ControllerConnectionEvent;
117
+ /**
118
+ * An all-in-one controller for singleplayer or p2p-authoritative-host multiplayer game state.
119
+ *
120
+ * @category Main
121
+ */
122
+ export declare class P2pAuthoritativeHostMultiplayerController<Input extends JsonCompatibleValue = any, State extends JsonCompatibleValue = any> extends ListenTarget<AllP2pAuthoritativeHostMultiplayerControllerEvents<Input, State>> {
123
+ protected readonly params: P2pAuthoritativeHostMultiplayerControllerParams<Input, State>;
124
+ /** All events emitted by this controller. */
125
+ static readonly events: {
126
+ ControllerStateEvent: typeof ControllerStateEvent;
127
+ };
128
+ /** All events emitted by this controller. */
129
+ readonly events: {
130
+ ControllerStateEvent: typeof ControllerStateEvent;
131
+ };
132
+ static readonly knownErrors: {
133
+ RoomRejectionError: typeof RoomRejectionError;
134
+ };
135
+ readonly knownErrors: {
136
+ RoomRejectionError: typeof RoomRejectionError;
137
+ };
138
+ /** Core multiplayer room controller that owns API, room polling, signaling, and transport. */
139
+ readonly roomController: MultiplayerRoomController<P2pAuthoritativeHostMessage<Input, State>>;
140
+ protected readonly localClientId: ClientId;
141
+ protected roomConnection: MultiplayerRoomConnection<P2pAuthoritativeHostMessage<Input, State>> | undefined;
142
+ protected currentState: State;
143
+ protected currentSequence: number;
144
+ protected singleplayer: boolean;
145
+ constructor(params: P2pAuthoritativeHostMultiplayerControllerParams<Input, State>);
146
+ /** Current p2p-authoritative-host connection, exposed for compatibility checks. */
147
+ get currentConnection(): this | undefined;
148
+ /** The current client id. */
149
+ get clientId(): ClientId;
150
+ /**
151
+ * Set to `false` to disable room updates, even when still not connected to a room in
152
+ * multiplayer mode.
153
+ */
154
+ get enableRoomUpdates(): boolean;
155
+ /** Update whether room list polling is enabled while not connected to a room. */
156
+ set enableRoomUpdates(value: boolean);
157
+ /** Currently joined room id. If a room has not been joined yet, this will be empty. */
158
+ get roomId(): import("@antha/multiplayer-core").RoomId | undefined;
159
+ /** The current connection state of the controller's connection to a backend API. */
160
+ get apiConnectionState(): ApiAndRoomConnectionState['api'];
161
+ /** The current connection state of the controller's connection to a multiplayer room. */
162
+ get roomConnectionState(): ApiAndRoomConnectionState['room'];
163
+ /** The current multiplayer API client. This will be `undefined` if playing in single player. */
164
+ get multiplayerApiClient(): Readonly<import("@rest-vir/api").RestVirClient<{
165
+ apiName: string;
166
+ endpoints: Readonly<Record<"/" | "/health" | "/rooms", Readonly<import("@rest-vir/api").EndpointDefinition>>>;
167
+ webSockets: Readonly<Record<"/connect", Readonly<import("@rest-vir/api").WebSocketDefinition>>>;
168
+ }>> | undefined;
169
+ /**
170
+ * Get the current client's WebRTC client id. This will return `undefined` if there is no
171
+ * current connection.
172
+ */
173
+ getClientId(): ClientId | undefined;
174
+ /**
175
+ * Get all connected client ids.
176
+ *
177
+ * - For host clients, this indicates how many member clients are connected to the host client,
178
+ * _not_ including the host itself.
179
+ * - For non-host clients, this only lists the local connection used to reach the host.
180
+ */
181
+ getConnectedClientIds(): ClientId[];
182
+ /**
183
+ * Get all room client ids.
184
+ *
185
+ * - For host clients, this indicates how many clients are connected to the room, including the
186
+ * host client itself.
187
+ * - For non-host clients, this includes the member client and the host client once connected.
188
+ */
189
+ getAllClientIds(): ClientId[];
190
+ /** Get the latest local state view. */
191
+ getState(): State;
192
+ /** Start multiplayer mode. This delegates API connectivity and room polling to multiplayer core. */
193
+ initMultiplayer(params: Readonly<MultiplayerInitParams>): Promise<void>;
194
+ /** Start singleplayer mode. */
195
+ startSingleplayer(): void;
196
+ /** Send or apply a local input. */
197
+ act(input: Readonly<Input>): void;
198
+ /** Advance authoritative time-based state. Only the host advances canonical state. */
199
+ tick(elapsedMs?: number): void;
200
+ /** Detects if this controller is the room host or not. */
201
+ isHost(): boolean;
202
+ /** Detects if this controller is connected to a room or not. */
203
+ isConnected(): boolean;
204
+ /** Cleanup everything. */
205
+ destroy(): void;
206
+ /**
207
+ * Join or create a room.
208
+ *
209
+ * @throws `Error` if this controller is already connected to a room.
210
+ */
211
+ joinOrCreateRoom(room: Readonly<RoomInput>): Promise<void>;
212
+ /** Leave the current room or single player connection. */
213
+ leaveRoom(): void;
214
+ /** Forward core room-controller events into this state-sync controller. */
215
+ protected listenToRoomController(): void;
216
+ /** Attach an established room transport and publish the current state view. */
217
+ protected attachMultiplayerRoomConnection(roomConnection: Readonly<MultiplayerRoomConnection<P2pAuthoritativeHostMessage<Input, State>>>): void;
218
+ /** Send the latest authoritative state to a newly connected member. */
219
+ protected syncNewMember(clientId: ClientId): void;
220
+ /** Apply received inputs on the host or received state snapshots on member clients. */
221
+ protected handleReceivedMessage(sourceClientId: ClientId, message: Readonly<P2pAuthoritativeHostMessage<Input, State>>): void;
222
+ /** Validate and apply an input against the current authoritative state. */
223
+ protected applyInput({ clientId, input, }: Readonly<{
224
+ clientId: ClientId;
225
+ input: Readonly<Input>;
226
+ }>): void;
227
+ /** Publish a new authoritative state that was not caused by a player input. */
228
+ protected updateState(state: State): void;
229
+ /** Publish a new authoritative state caused by a player input. */
230
+ protected updateStateFromInput({ clientId, input, state, }: Readonly<{
231
+ clientId: ClientId;
232
+ input: Readonly<Input>;
233
+ state: State;
234
+ }>): void;
235
+ /** Dispatch the typed state event to local listeners. */
236
+ protected dispatchState(detail: Readonly<StateEventDetail<Input, State>>): void;
237
+ /** Broadcast a state snapshot when the local client is the host. */
238
+ protected sendStateSnapshot(detail: Readonly<StateEventDetail<Input, State>>): void;
239
+ /** Create a network message from state event detail. */
240
+ protected createStateSnapshotMessage(detail: Readonly<StateEventDetail<Input, State>>): P2pAuthoritativeHostMessage<Input, State>;
241
+ /** Create the local state event detail for the current sequence and state. */
242
+ protected createStateEventDetail(source?: Readonly<PartialWithUndefined<{
243
+ clientId: ClientId;
244
+ input: Readonly<Input>;
245
+ }>>): StateEventDetail<Input, State>;
246
+ }
247
+ export {};
@@ -0,0 +1,342 @@
1
+ import { ControllerClientEvent, ControllerConnectionEvent, ControllerMessageEvent, ControllerRoomListEvent, createMultiplayerId, emptyApiAndRoomConnectionState, MultiplayerConnectionState, MultiplayerRoomController, RoomRejectionError, } from '@antha/multiplayer-core';
2
+ import { defineTypedCustomEvent, ListenTarget } from 'typed-event-target';
3
+ /**
4
+ * Message type for {@link P2pAuthoritativeHostMessage}.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export var P2pAuthoritativeHostMessageType;
9
+ (function (P2pAuthoritativeHostMessageType) {
10
+ P2pAuthoritativeHostMessageType["Input"] = "input";
11
+ P2pAuthoritativeHostMessageType["StateSnapshot"] = "state-snapshot";
12
+ })(P2pAuthoritativeHostMessageType || (P2pAuthoritativeHostMessageType = {}));
13
+ /**
14
+ * This is fired whenever the local authoritative-host state view updates.
15
+ *
16
+ * @category Events
17
+ */
18
+ export class ControllerStateEvent extends defineTypedCustomEvent()('controller-state') {
19
+ constructor(eventInitDict) {
20
+ super(eventInitDict);
21
+ }
22
+ }
23
+ /**
24
+ * An all-in-one controller for singleplayer or p2p-authoritative-host multiplayer game state.
25
+ *
26
+ * @category Main
27
+ */
28
+ export class P2pAuthoritativeHostMultiplayerController extends ListenTarget {
29
+ params;
30
+ /** All events emitted by this controller. */
31
+ static events = {
32
+ ControllerStateEvent,
33
+ };
34
+ /** All events emitted by this controller. */
35
+ events = P2pAuthoritativeHostMultiplayerController.events;
36
+ static knownErrors = {
37
+ RoomRejectionError,
38
+ };
39
+ knownErrors = P2pAuthoritativeHostMultiplayerController.knownErrors;
40
+ /** Core multiplayer room controller that owns API, room polling, signaling, and transport. */
41
+ roomController;
42
+ localClientId = createMultiplayerId.client();
43
+ roomConnection;
44
+ currentState;
45
+ currentSequence = 0;
46
+ singleplayer = false;
47
+ constructor(params) {
48
+ super();
49
+ this.params = params;
50
+ this.currentState = params.createInitialState();
51
+ this.roomController = new MultiplayerRoomController({
52
+ gameId: params.gameId,
53
+ acceptConnection: params.acceptConnection
54
+ ? (connectingClientId) => {
55
+ return params.acceptConnection?.(connectingClientId, this) ?? true;
56
+ }
57
+ : undefined,
58
+ });
59
+ this.listenToRoomController();
60
+ }
61
+ /** Current p2p-authoritative-host connection, exposed for compatibility checks. */
62
+ get currentConnection() {
63
+ return this.isConnected() ? this : undefined;
64
+ }
65
+ /** The current client id. */
66
+ get clientId() {
67
+ return this.roomConnection?.clientId || this.localClientId;
68
+ }
69
+ /**
70
+ * Set to `false` to disable room updates, even when still not connected to a room in
71
+ * multiplayer mode.
72
+ */
73
+ get enableRoomUpdates() {
74
+ return this.roomController.enableRoomUpdates;
75
+ }
76
+ /** Update whether room list polling is enabled while not connected to a room. */
77
+ set enableRoomUpdates(value) {
78
+ this.roomController.enableRoomUpdates = value;
79
+ }
80
+ /** Currently joined room id. If a room has not been joined yet, this will be empty. */
81
+ get roomId() {
82
+ return this.roomController.roomId;
83
+ }
84
+ /** The current connection state of the controller's connection to a backend API. */
85
+ get apiConnectionState() {
86
+ return this.roomController.apiConnectionState;
87
+ }
88
+ /** The current connection state of the controller's connection to a multiplayer room. */
89
+ get roomConnectionState() {
90
+ return this.roomController.roomConnectionState;
91
+ }
92
+ /** The current multiplayer API client. This will be `undefined` if playing in single player. */
93
+ get multiplayerApiClient() {
94
+ return this.roomController.multiplayerApiClient;
95
+ }
96
+ /**
97
+ * Get the current client's WebRTC client id. This will return `undefined` if there is no
98
+ * current connection.
99
+ */
100
+ getClientId() {
101
+ if (this.singleplayer) {
102
+ return this.localClientId;
103
+ }
104
+ return this.roomConnection?.clientId || this.roomController.getClientId();
105
+ }
106
+ /**
107
+ * Get all connected client ids.
108
+ *
109
+ * - For host clients, this indicates how many member clients are connected to the host client,
110
+ * _not_ including the host itself.
111
+ * - For non-host clients, this only lists the local connection used to reach the host.
112
+ */
113
+ getConnectedClientIds() {
114
+ return this.roomConnection?.getConnectedClientIds() || [];
115
+ }
116
+ /**
117
+ * Get all room client ids.
118
+ *
119
+ * - For host clients, this indicates how many clients are connected to the room, including the
120
+ * host client itself.
121
+ * - For non-host clients, this includes the member client and the host client once connected.
122
+ */
123
+ getAllClientIds() {
124
+ if (this.singleplayer) {
125
+ return [
126
+ this.localClientId,
127
+ ];
128
+ }
129
+ return this.roomConnection?.getAllClientIds() || [];
130
+ }
131
+ /** Get the latest local state view. */
132
+ getState() {
133
+ return this.currentState;
134
+ }
135
+ /** Start multiplayer mode. This delegates API connectivity and room polling to multiplayer core. */
136
+ async initMultiplayer(params) {
137
+ await this.roomController.initMultiplayer(params);
138
+ }
139
+ /** Start singleplayer mode. */
140
+ startSingleplayer() {
141
+ if (this.currentConnection) {
142
+ throw new Error('Cannot start singleplayer with a connection already present.');
143
+ }
144
+ this.singleplayer = true;
145
+ this.dispatchState(this.createStateEventDetail());
146
+ this.dispatch(new ControllerConnectionEvent({
147
+ detail: {
148
+ ...emptyApiAndRoomConnectionState,
149
+ api: MultiplayerConnectionState.Connected,
150
+ },
151
+ }));
152
+ }
153
+ /** Send or apply a local input. */
154
+ act(input) {
155
+ if (!this.currentConnection || !this.currentConnection.isConnected()) {
156
+ throw new Error('Cannot perform input: not connected to a room.');
157
+ }
158
+ if (this.isHost()) {
159
+ this.applyInput({
160
+ clientId: this.clientId,
161
+ input,
162
+ });
163
+ }
164
+ else {
165
+ this.roomConnection?.sendMessage({
166
+ type: P2pAuthoritativeHostMessageType.Input,
167
+ input,
168
+ });
169
+ }
170
+ }
171
+ /** Advance authoritative time-based state. Only the host advances canonical state. */
172
+ tick(elapsedMs = 0) {
173
+ if (!this.isHost() || !this.params.tick) {
174
+ return;
175
+ }
176
+ this.updateState(this.params.tick({
177
+ elapsedMs,
178
+ state: this.currentState,
179
+ }));
180
+ }
181
+ /** Detects if this controller is the room host or not. */
182
+ isHost() {
183
+ return this.singleplayer || this.roomConnection?.isHost() || false;
184
+ }
185
+ /** Detects if this controller is connected to a room or not. */
186
+ isConnected() {
187
+ return this.singleplayer || this.roomConnection?.isConnected() || false;
188
+ }
189
+ /** Cleanup everything. */
190
+ destroy() {
191
+ this.roomConnection = undefined;
192
+ this.singleplayer = false;
193
+ this.roomController.destroy();
194
+ super.destroy();
195
+ }
196
+ /**
197
+ * Join or create a room.
198
+ *
199
+ * @throws `Error` if this controller is already connected to a room.
200
+ */
201
+ async joinOrCreateRoom(room) {
202
+ if (this.currentConnection) {
203
+ throw new Error('Cannot join room: connection already established.');
204
+ }
205
+ try {
206
+ await this.roomController.joinOrCreateRoom(room);
207
+ if (!this.roomController.currentConnection) {
208
+ throw new Error('Cannot start p2p-authoritative-host multiplayer: room connection is missing.');
209
+ }
210
+ this.attachMultiplayerRoomConnection(this.roomController.currentConnection);
211
+ }
212
+ catch (error) {
213
+ this.roomConnection = undefined;
214
+ throw error;
215
+ }
216
+ }
217
+ /** Leave the current room or single player connection. */
218
+ leaveRoom() {
219
+ if (!this.currentConnection) {
220
+ return;
221
+ }
222
+ this.roomConnection = undefined;
223
+ this.singleplayer = false;
224
+ this.roomController.leaveRoom();
225
+ }
226
+ /** Forward core room-controller events into this state-sync controller. */
227
+ listenToRoomController() {
228
+ this.roomController.listen(ControllerRoomListEvent, (event) => {
229
+ this.dispatch(event);
230
+ });
231
+ this.roomController.listen(ControllerConnectionEvent, (event) => {
232
+ this.dispatch(event);
233
+ });
234
+ this.roomController.listen(ControllerClientEvent, (event) => {
235
+ if ('newMember' in event.detail) {
236
+ this.syncNewMember(event.detail.newMember);
237
+ }
238
+ this.dispatch(event);
239
+ });
240
+ this.roomController.listen((ControllerMessageEvent), (event) => {
241
+ this.handleReceivedMessage(event.sourceClientId, event.detail);
242
+ });
243
+ }
244
+ /** Attach an established room transport and publish the current state view. */
245
+ attachMultiplayerRoomConnection(roomConnection) {
246
+ this.roomConnection = roomConnection;
247
+ this.dispatchState(this.createStateEventDetail());
248
+ if (this.isHost()) {
249
+ this.sendStateSnapshot(this.createStateEventDetail());
250
+ }
251
+ }
252
+ /** Send the latest authoritative state to a newly connected member. */
253
+ syncNewMember(clientId) {
254
+ if (this.roomConnection && this.isHost()) {
255
+ this.roomConnection.sendToOnlyOneClient(clientId, this.createStateSnapshotMessage(this.createStateEventDetail()));
256
+ }
257
+ }
258
+ /** Apply received inputs on the host or received state snapshots on member clients. */
259
+ handleReceivedMessage(sourceClientId, message) {
260
+ if (!this.roomConnection) {
261
+ return;
262
+ }
263
+ if (this.isHost() && message.type === P2pAuthoritativeHostMessageType.Input) {
264
+ this.applyInput({
265
+ clientId: sourceClientId,
266
+ input: message.input,
267
+ });
268
+ }
269
+ else if (!this.isHost() &&
270
+ message.type === P2pAuthoritativeHostMessageType.StateSnapshot &&
271
+ message.sequence >= this.currentSequence) {
272
+ this.currentSequence = message.sequence;
273
+ this.currentState = message.state;
274
+ this.dispatchState(message);
275
+ }
276
+ }
277
+ /** Validate and apply an input against the current authoritative state. */
278
+ applyInput({ clientId, input, }) {
279
+ const shouldAcceptInput = this.params.shouldAcceptInput?.({
280
+ clientId,
281
+ input,
282
+ state: this.currentState,
283
+ }) ?? true;
284
+ if (shouldAcceptInput) {
285
+ this.updateStateFromInput({
286
+ clientId,
287
+ input,
288
+ state: this.params.applyInput({
289
+ clientId,
290
+ input,
291
+ state: this.currentState,
292
+ }),
293
+ });
294
+ }
295
+ }
296
+ /** Publish a new authoritative state that was not caused by a player input. */
297
+ updateState(state) {
298
+ this.currentState = state;
299
+ this.currentSequence++;
300
+ const detail = this.createStateEventDetail();
301
+ this.dispatchState(detail);
302
+ this.sendStateSnapshot(detail);
303
+ }
304
+ /** Publish a new authoritative state caused by a player input. */
305
+ updateStateFromInput({ clientId, input, state, }) {
306
+ this.currentState = state;
307
+ this.currentSequence++;
308
+ const detail = this.createStateEventDetail({
309
+ clientId,
310
+ input,
311
+ });
312
+ this.dispatchState(detail);
313
+ this.sendStateSnapshot(detail);
314
+ }
315
+ /** Dispatch the typed state event to local listeners. */
316
+ dispatchState(detail) {
317
+ this.dispatch(new ControllerStateEvent({
318
+ detail,
319
+ }));
320
+ }
321
+ /** Broadcast a state snapshot when the local client is the host. */
322
+ sendStateSnapshot(detail) {
323
+ if (this.roomConnection && this.isHost()) {
324
+ this.roomConnection.sendMessage(this.createStateSnapshotMessage(detail));
325
+ }
326
+ }
327
+ /** Create a network message from state event detail. */
328
+ createStateSnapshotMessage(detail) {
329
+ return {
330
+ ...detail,
331
+ type: P2pAuthoritativeHostMessageType.StateSnapshot,
332
+ };
333
+ }
334
+ /** Create the local state event detail for the current sequence and state. */
335
+ createStateEventDetail(source = {}) {
336
+ return {
337
+ ...source,
338
+ sequence: this.currentSequence,
339
+ state: this.currentState,
340
+ };
341
+ }
342
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@antha/multiplayer-p2p-authoritative-host",
3
+ "version": "0.0.1",
4
+ "description": "P2P authoritative-host multiplayer strategy for the Antha engine.",
5
+ "keywords": [
6
+ "vir",
7
+ "antha",
8
+ "WebRTC",
9
+ "signal server",
10
+ "multiplayer",
11
+ "gaming"
12
+ ],
13
+ "homepage": "https://github.com/electrovir/antha",
14
+ "bugs": {
15
+ "url": "https://github.com/electrovir/antha/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/electrovir/antha.git"
20
+ },
21
+ "license": "(MIT OR CC0-1.0)",
22
+ "author": {
23
+ "name": "electrovir",
24
+ "url": "https://github.com/electrovir"
25
+ },
26
+ "sideEffects": false,
27
+ "type": "module",
28
+ "main": "dist/index.js",
29
+ "module": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "scripts": {
32
+ "compile": "virmator compile",
33
+ "docs": "virmator docs",
34
+ "test": "virmator test web",
35
+ "test:coverage": "npm test coverage",
36
+ "test:docs": "virmator docs check"
37
+ },
38
+ "dependencies": {
39
+ "@augment-vir/common": "^31.73.1",
40
+ "typed-event-target": "^4.3.1"
41
+ },
42
+ "devDependencies": {
43
+ "@augment-vir/assert": "^31.73.1",
44
+ "@augment-vir/test": "^31.73.1",
45
+ "@web/dev-server-esbuild": "^1.0.5",
46
+ "@web/test-runner": "^0.20.2",
47
+ "@web/test-runner-playwright": "^0.11.1",
48
+ "istanbul-smart-text-reporter": "^1.1.5"
49
+ },
50
+ "peerDependencies": {
51
+ "@antha/multiplayer-core": "^0.0.1"
52
+ },
53
+ "engines": {
54
+ "node": ">=22"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ }
59
+ }