peerodactyl 0.0.0-stage → 0.1.2

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gian
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 CHANGED
@@ -1,3 +1,238 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">peerodactyl</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ Peer-to-peer game rooms where <b>one player is the server</b>.<br />
5
+ Host-authoritative, reconnection-proof, and independent of your game.
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/peerodactyl">npm</a> ·
10
+ <a href="https://gianluks90.github.io/peerodactyl/">Live demo</a> ·
11
+ <a href="#quick-start">Quick start</a>
12
+ </p>
13
+
14
+ ---
15
+
16
+ One player hosts the room. Everyone else joins with a short code. Guests send **intents**
17
+ ("I want to move here"), the host validates them against your rules and broadcasts **events**
18
+ ("Bronto moved here"). Peerodactyl only carries those messages. It knows nothing about your game.
19
+
20
+ - **Host-authoritative.** One place holds the rules, so guests cannot cheat.
21
+ - **No game server to run.** Browsers connect directly over WebRTC.
22
+ - **Built for flaky connections.** Heartbeat, automatic reconnection and seat recovery after a page reload.
23
+ - **Transport-agnostic.** Real P2P through [Trystero](https://github.com/dmotz/trystero), same-browser tabs, or in-memory for tests.
24
+ - **Small and typed.** TypeScript throughout, no runtime dependencies, optional Angular signals.
25
+
26
+ > Early but tested: 54 unit tests, end-to-end runs in Chrome, and a real phone on mobile data.
27
+
28
+ ```
29
+ npm install peerodactyl
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ Create one client, then host or join. Host and guest share the same API, so your code does not
35
+ care which role it plays. You define three types: intents (guest to host), events (host to
36
+ everyone) and the snapshot (the full state).
37
+
38
+ ```ts
39
+ import { PeerodactylClient, trysteroTransport } from 'peerodactyl'
40
+ import { joinRoom } from 'trystero' // any Trystero strategy works
41
+
42
+ type Intent = { move: [number, number] }
43
+ type Event = { moved: { by: string; to: [number, number] } }
44
+ type State = { tokens: Record<string, [number, number]> }
45
+
46
+ const pd = new PeerodactylClient<Intent, Event, State>({
47
+ transport: trysteroTransport(joinRoom, { appId: 'my-unique-app-id' })
48
+ })
49
+
50
+ // Host only: the single place where your rules live.
51
+ pd.setSnapshot(() => state)
52
+ pd.on('intent', (intent, from) => {
53
+ if (!allowed(intent, from)) return
54
+ pd.broadcast({ moved: { by: from, to: intent.move } })
55
+ })
56
+
57
+ // Everyone, host included: apply events with the same code.
58
+ pd.on('event', (e) => apply(e))
59
+ pd.on('snapshot', (s) => (state = s)) // guests: full state on join and after reconnection
60
+ pd.on('ended', (reason) => showLobby(reason)) // 'closed' | 'kicked' | 'lost'
61
+
62
+ const code = await pd.hostRoom() // "K7QM": share it
63
+ await pd.joinRoom('K7QM') // or join a room
64
+ pd.sendIntent({ move: [3, 4] }) // same call for host and guest
65
+ pd.leave()
66
+ ```
67
+
68
+ Render from `pd.state` (status, role, code, players with online or away, latency, snapshot)
69
+ and `pd.subscribe(listener)`. It maps directly onto signals, `useSyncExternalStore` or any store.
70
+
71
+ After a page reload, `await pd.rejoin()` gives the guest its seat back. The client remembers
72
+ the room in `sessionStorage`.
73
+
74
+ ### Angular
75
+
76
+ ```ts
77
+ // app.config.ts
78
+ import { providePeerodactyl } from 'peerodactyl/angular'
79
+
80
+ export const appConfig = {
81
+ providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }) })]
82
+ }
83
+
84
+ // any component or service
85
+ import { injectPeerodactyl } from 'peerodactyl/angular'
86
+
87
+ pd = injectPeerodactyl<Intent, Event, State>()
88
+ // template: @if (pd.status() === 'reconnecting') { ... } @for (p of pd.players(); track p.id) { ... }
89
+ // code: await pd.client.hostRoom()
90
+ ```
91
+
92
+ `@angular/core` (17 or later) is an optional peer dependency, needed only for `peerodactyl/angular`.
93
+
94
+ ### Lower level
95
+
96
+ `host()` and `join()` return `HostRoom` and `GuestRoom` directly, if you want the raw pieces.
97
+
98
+ ```ts
99
+ const room = await host<Intent, Event, State>({ transport })
100
+ room.on('intent', (intent, from) => room.broadcast(/* ... */))
101
+
102
+ const guest = await join<Intent, Event, State>({ transport, code: room.code })
103
+ guest.on('event', apply)
104
+ guest.sendIntent({ move: [3, 4] })
105
+ ```
106
+
107
+ ## What is in the box
108
+
109
+ | Piece | Purpose |
110
+ | --- | --- |
111
+ | `PeerodactylClient` | The entry point. One object for host and guest: state, subscribe, events, intents, rejoin after reload |
112
+ | `peerodactyl/angular` | `providePeerodactyl()` and `injectPeerodactyl()`: the client state as signals |
113
+ | `host()` / `HostRoom` | Opens a room, validates joins, receives intents, broadcasts events and snapshots |
114
+ | `join()` / `GuestRoom` | Finds the host by room code, receives the snapshot, sends intents |
115
+ | `Transport` | A small interface (`send`, `onMessage`, `onPeerJoin`, `onPeerLeave`, `leave`). Factories may be async |
116
+ | `trysteroTransport()` | Real P2P over Trystero (WebRTC with public signaling). You pass the `joinRoom` you prefer, so peerodactyl has no dependency on it |
117
+ | `broadcastChannelTransport()` | Tabs of the same browser talk to each other, no network. For development, demos and tests |
118
+ | `createMemoryNetwork()` | In-process transport for unit tests, with simulated partitions and crashes |
119
+ | `debug: true` | Logs connection events, with a dinosaur scream (customise it with `screams`) |
120
+
121
+ Game rules, dice, maps and line of sight are not included on purpose. They belong to your app.
122
+
123
+ ## Heartbeat and reconnection
124
+
125
+ Phones lock, tabs reload and Wi-Fi drops. Peerodactyl handles it so your app does not have to.
126
+
127
+ - Every guest has a **stable id** (`guest.selfId`) that survives reconnection, so the host can key
128
+ game state on it (a token, a character) without losing it.
129
+ - Guests ping the host and the host answers. Silence for `timeoutMs` (default 3 × `heartbeatMs`)
130
+ marks a guest **away** (`guestAway`). Its seat is kept for `graceMs` (default 60 s), then the
131
+ host emits `guestLeave(id, 'timeout')`. An explicit `leave()` frees the seat at once (`'bye'`),
132
+ and `kick()` reports `'kicked'`.
133
+ - When a guest returns, `guestBack` fires and it receives a fresh snapshot. Events missed while
134
+ away are dropped, because the snapshot replaces them.
135
+ - The guest reconnects by itself (`reconnect: true`, `reconnectTimeoutMs`, default 30 s):
136
+ `reconnecting`, then `reconnected(resumed)`. If it gives up, `hostLeft('lost')`. If the host
137
+ closed the room, `hostLeft('closed')` and no retries.
138
+ - **Surviving a page reload:** save `guest.selfId` (for example in `sessionStorage`) and pass it
139
+ as `join({ sessionId })`. The host gives the same seat back (`guest.resumed === true`).
140
+
141
+ ```ts
142
+ host.on('guestAway', (id) => markOffline(id))
143
+ host.on('guestBack', (id) => markOnline(id))
144
+ host.on('guestLeave', (id, reason) => removeToken(id)) // 'bye' | 'timeout' | 'kicked'
145
+
146
+ const guest = await join({ transport, code, sessionId: saved?.sid })
147
+ guest.on('reconnecting', () => showBanner('Reconnecting...'))
148
+ guest.on('reconnected', (resumed) => hideBanner())
149
+ guest.on('hostLeft', (reason) => goToLobby(reason)) // 'closed' | 'kicked' | 'lost'
150
+ sessionStorage.setItem('sid', guest.selfId)
151
+ ```
152
+
153
+ To simulate failures in tests, `createMemoryNetwork()` offers `partition(peerId)` (silent drop),
154
+ `heal(peerId)` and `kill(peerId)` (abrupt disconnect).
155
+
156
+ ## TURN fallback for strict networks
157
+
158
+ WebRTC tries a direct path first (STUN). On some networks, such as mobile carriers with CGNAT or
159
+ corporate firewalls, that fails and the peers need a **TURN relay** to forward their traffic.
160
+ The signaling relays only help peers find each other and never carry game data, so TURN is a
161
+ separate concern.
162
+
163
+ This is a one-time setup **for you, the developer**. Your players never see it.
164
+
165
+ The simplest way is to point `turnUrl` at a tiny endpoint (for example a Cloudflare Worker) that
166
+ returns fresh credentials as `[{ urls, username, credential }]`.
167
+
168
+ ```ts
169
+ trysteroTransport(joinRoom, { appId: 'my-game' }, { turnUrl: 'https://your-worker.workers.dev' })
170
+ ```
171
+
172
+ Credentials are fetched when the room opens and cached for 30 minutes. If the endpoint is down,
173
+ peerodactyl carries on without TURN. You can also pass static servers:
174
+
175
+ ```ts
176
+ trysteroTransport(joinRoom, {
177
+ appId: 'my-game',
178
+ turnConfig: [{ urls: 'turn:YOUR-TURN-HOST:443?transport=tcp', username: '...', credential: '...' }]
179
+ })
180
+ ```
181
+
182
+ - Use the same TURN configuration on host and guests. Port 443 over TCP or TLS passes the strictest firewalls.
183
+ - Options to consider (check current limits): Cloudflare Realtime TURN, Metered Open Relay, or your own `coturn`.
184
+ - Short-lived credentials beat static ones. Never commit TURN secrets to a public repository.
185
+ - Only relayed connections use TURN bandwidth, and a game made of small messages barely registers.
186
+
187
+ **Testing it.** In the demo, open "Network options", add your TURN endpoint and tick "Force relay".
188
+ If two devices still connect, your TURN setup works. On a phone, turn Wi-Fi off and use mobile data
189
+ to exercise the real worst case.
190
+
191
+ ## Try the demo
192
+
193
+ The live demo is at **https://gianluks90.github.io/peerodactyl/**. To run it locally:
194
+
195
+ ```
196
+ npm install
197
+ npm run demo
198
+ ```
199
+
200
+ Pick **Same browser, two tabs** to create a room in one tab and join it from another, with no
201
+ network involved. Pick **Over the internet** to go through Trystero, and try it from two devices.
202
+ The host refuses moves longer than three cells: guests cannot cheat, which is the whole point.
203
+
204
+ Pushing to `master` runs `.github/workflows/pages.yml`, which type-checks, tests, builds the demo
205
+ and publishes it to GitHub Pages. One-time setup: **Settings, Pages, Source: GitHub Actions**.
206
+ Internet mode requires HTTPS (Trystero relies on browser crypto that only exists on secure pages),
207
+ so test it from the published site rather than from `http://<LAN-ip>`.
208
+
209
+ ## Scripts
210
+
211
+ ```
212
+ npm test # vitest: memory, BroadcastChannel, fake Trystero, heartbeat, client, Angular
213
+ npm run typecheck
214
+ npm run build # tsup, output in dist/
215
+ npm run demo # vite dev server for demo/
216
+ npm run demo:build # static build in demo-dist/
217
+ ```
218
+
219
+ ## Roadmap
220
+
221
+ - [x] Core, in-memory transport, tests
222
+ - [x] Trystero adapter, BroadcastChannel transport, demo
223
+ - [x] Heartbeat, reconnection, resume after reload
224
+ - [x] TURN fallback (`turnUrl`), verified on a phone over mobile data
225
+ - [x] Client service and Angular signals
226
+ - [x] Published to npm
227
+ - [ ] First production integrations (virtual tabletop maps, dungeon crawler)
228
+ - [ ] Alternative signaling, so peers can find each other without public Nostr relays
229
+
230
+ ## Known limits
231
+
232
+ - Peers still find each other through public signaling relays (Nostr by default). Game data does not go through them, but their availability matters.
233
+ - Without a TURN server, peers behind strict NATs may fail to connect.
234
+ - If the host disappears, the room ends. Resuming from a saved checkpoint is up to your app.
235
+
236
+ ## License
237
+
238
+ MIT
@@ -0,0 +1,42 @@
1
+ import { InjectionToken, Signal, Provider } from '@angular/core';
2
+ import { P as PeerodactylClient, C as ClientState, a as ClientStatus, b as PlayerInfo, c as PeerodactylClientOptions } from './client-DRstnAkE.js';
3
+
4
+ /** The client plus its state as Angular signals. */
5
+ interface PeerodactylSignals<I = unknown, E = unknown, S = unknown> {
6
+ /** Use it to host, join, send intents, listen to `intent` / `event`... */
7
+ readonly client: PeerodactylClient<I, E, S>;
8
+ readonly state: Signal<ClientState<S>>;
9
+ readonly status: Signal<ClientStatus>;
10
+ readonly role: Signal<'host' | 'guest' | null>;
11
+ readonly isHost: Signal<boolean>;
12
+ readonly code: Signal<string | null>;
13
+ readonly selfId: Signal<string | null>;
14
+ readonly players: Signal<readonly PlayerInfo[]>;
15
+ readonly latency: Signal<number | null>;
16
+ readonly snapshot: Signal<S | null>;
17
+ readonly endedReason: Signal<ClientState<S>['endedReason']>;
18
+ }
19
+ /** Where the shared instance lives. Prefer `providePeerodactyl()` + `injectPeerodactyl()`. */
20
+ declare const PEERODACTYL: InjectionToken<PeerodactylSignals<any, any, any>>;
21
+ /**
22
+ * Register peerodactyl once (app config or a route's providers):
23
+ *
24
+ * ```ts
25
+ * bootstrapApplication(App, {
26
+ * providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }, { turnUrl }) })]
27
+ * })
28
+ * ```
29
+ */
30
+ declare function providePeerodactyl(options: PeerodactylClientOptions): Provider[];
31
+ /**
32
+ * Get the shared instance in any component or service:
33
+ *
34
+ * ```ts
35
+ * pd = injectPeerodactyl<Intent, Event, State>()
36
+ * // template: @if (pd.status() === 'reconnecting') { ... } {{ pd.players().length }}
37
+ * // code: await pd.client.hostRoom()
38
+ * ```
39
+ */
40
+ declare function injectPeerodactyl<I = unknown, E = unknown, S = unknown>(): PeerodactylSignals<I, E, S>;
41
+
42
+ export { ClientState, ClientStatus, PEERODACTYL, PeerodactylClient, PeerodactylClientOptions, type PeerodactylSignals, PlayerInfo, injectPeerodactyl, providePeerodactyl };
@@ -0,0 +1,48 @@
1
+ import {
2
+ PeerodactylClient
3
+ } from "./chunk-I6QHF4CQ.js";
4
+
5
+ // src/angular/index.ts
6
+ import {
7
+ DestroyRef,
8
+ InjectionToken,
9
+ computed,
10
+ inject,
11
+ signal
12
+ } from "@angular/core";
13
+ var PEERODACTYL = new InjectionToken("PEERODACTYL");
14
+ function createSignals(options) {
15
+ const client = new PeerodactylClient(options);
16
+ const state = signal(client.state);
17
+ const off = client.subscribe((s) => state.set(s));
18
+ inject(DestroyRef, { optional: true })?.onDestroy(() => {
19
+ off();
20
+ client.leave();
21
+ });
22
+ return {
23
+ client,
24
+ state: state.asReadonly(),
25
+ status: computed(() => state().status),
26
+ role: computed(() => state().role),
27
+ isHost: computed(() => state().role === "host"),
28
+ code: computed(() => state().code),
29
+ selfId: computed(() => state().selfId),
30
+ players: computed(() => state().players),
31
+ latency: computed(() => state().latency),
32
+ snapshot: computed(() => state().snapshot),
33
+ endedReason: computed(() => state().endedReason)
34
+ };
35
+ }
36
+ function providePeerodactyl(options) {
37
+ return [{ provide: PEERODACTYL, useFactory: () => createSignals(options) }];
38
+ }
39
+ function injectPeerodactyl() {
40
+ return inject(PEERODACTYL);
41
+ }
42
+ export {
43
+ PEERODACTYL,
44
+ PeerodactylClient,
45
+ injectPeerodactyl,
46
+ providePeerodactyl
47
+ };
48
+ //# sourceMappingURL=angular.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/angular/index.ts"],"sourcesContent":["import {\n DestroyRef,\n InjectionToken,\n computed,\n inject,\n signal,\n type Provider,\n type Signal\n} from '@angular/core'\nimport {\n PeerodactylClient,\n type ClientState,\n type ClientStatus,\n type PeerodactylClientOptions,\n type PlayerInfo\n} from '../client'\n\nexport type { ClientState, ClientStatus, PeerodactylClientOptions, PlayerInfo }\nexport { PeerodactylClient }\n\n/** The client plus its state as Angular signals. */\nexport interface PeerodactylSignals<I = unknown, E = unknown, S = unknown> {\n /** Use it to host, join, send intents, listen to `intent` / `event`... */\n readonly client: PeerodactylClient<I, E, S>\n readonly state: Signal<ClientState<S>>\n readonly status: Signal<ClientStatus>\n readonly role: Signal<'host' | 'guest' | null>\n readonly isHost: Signal<boolean>\n readonly code: Signal<string | null>\n readonly selfId: Signal<string | null>\n readonly players: Signal<readonly PlayerInfo[]>\n readonly latency: Signal<number | null>\n readonly snapshot: Signal<S | null>\n readonly endedReason: Signal<ClientState<S>['endedReason']>\n}\n\n/** Where the shared instance lives. Prefer `providePeerodactyl()` + `injectPeerodactyl()`. */\nexport const PEERODACTYL = new InjectionToken<PeerodactylSignals<any, any, any>>('PEERODACTYL')\n\nfunction createSignals<I, E, S>(options: PeerodactylClientOptions): PeerodactylSignals<I, E, S> {\n const client = new PeerodactylClient<I, E, S>(options)\n const state = signal<ClientState<S>>(client.state)\n const off = client.subscribe((s) => state.set(s))\n inject(DestroyRef, { optional: true })?.onDestroy(() => {\n off()\n client.leave()\n })\n return {\n client,\n state: state.asReadonly(),\n status: computed(() => state().status),\n role: computed(() => state().role),\n isHost: computed(() => state().role === 'host'),\n code: computed(() => state().code),\n selfId: computed(() => state().selfId),\n players: computed(() => state().players),\n latency: computed(() => state().latency),\n snapshot: computed(() => state().snapshot),\n endedReason: computed(() => state().endedReason)\n }\n}\n\n/**\n * Register peerodactyl once (app config or a route's providers):\n *\n * ```ts\n * bootstrapApplication(App, {\n * providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }, { turnUrl }) })]\n * })\n * ```\n */\nexport function providePeerodactyl(options: PeerodactylClientOptions): Provider[] {\n return [{ provide: PEERODACTYL, useFactory: () => createSignals(options) }]\n}\n\n/**\n * Get the shared instance in any component or service:\n *\n * ```ts\n * pd = injectPeerodactyl<Intent, Event, State>()\n * // template: @if (pd.status() === 'reconnecting') { ... } {{ pd.players().length }}\n * // code: await pd.client.hostRoom()\n * ```\n */\nexport function injectPeerodactyl<I = unknown, E = unknown, S = unknown>(): PeerodactylSignals<\n I,\n E,\n S\n> {\n return inject(PEERODACTYL) as PeerodactylSignals<I, E, S>\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AA6BA,IAAM,cAAc,IAAI,eAAkD,aAAa;AAE9F,SAAS,cAAuB,SAAgE;AAC9F,QAAM,SAAS,IAAI,kBAA2B,OAAO;AACrD,QAAM,QAAQ,OAAuB,OAAO,KAAK;AACjD,QAAM,MAAM,OAAO,UAAU,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAChD,SAAO,YAAY,EAAE,UAAU,KAAK,CAAC,GAAG,UAAU,MAAM;AACtD,QAAI;AACJ,WAAO,MAAM;AAAA,EACf,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA,OAAO,MAAM,WAAW;AAAA,IACxB,QAAQ,SAAS,MAAM,MAAM,EAAE,MAAM;AAAA,IACrC,MAAM,SAAS,MAAM,MAAM,EAAE,IAAI;AAAA,IACjC,QAAQ,SAAS,MAAM,MAAM,EAAE,SAAS,MAAM;AAAA,IAC9C,MAAM,SAAS,MAAM,MAAM,EAAE,IAAI;AAAA,IACjC,QAAQ,SAAS,MAAM,MAAM,EAAE,MAAM;AAAA,IACrC,SAAS,SAAS,MAAM,MAAM,EAAE,OAAO;AAAA,IACvC,SAAS,SAAS,MAAM,MAAM,EAAE,OAAO;AAAA,IACvC,UAAU,SAAS,MAAM,MAAM,EAAE,QAAQ;AAAA,IACzC,aAAa,SAAS,MAAM,MAAM,EAAE,WAAW;AAAA,EACjD;AACF;AAWO,SAAS,mBAAmB,SAA+C;AAChF,SAAO,CAAC,EAAE,SAAS,aAAa,YAAY,MAAM,cAAc,OAAO,EAAE,CAAC;AAC5E;AAWO,SAAS,oBAId;AACA,SAAO,OAAO,WAAW;AAC3B;","names":[]}