@super-line/plugin-multiplayer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ Generated from conventional commits by [git-cliff](https://git-cliff.org) —
4
+ run `pnpm changelog` rather than editing by hand.
5
+
6
+ ## [plugin-multiplayer-v0.1.0] — 2026-11-29
7
+
8
+ ### Features
9
+
10
+ - **plugin-multiplayer:** Publishable manifest, license, README corrections ([3091b97])
11
+ - **plugin-multiplayer:** Client and server stats, lazy correction ([60e4384])
12
+ - **plugin-multiplayer:** Server-run game worlds ([739d7da])
13
+
14
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mert
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,335 @@
1
- # Temporary Holding Version
1
+ # @super-line/plugin-multiplayer
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
+ Server-run game worlds for super-line. A **world** is one JSON state that only the game's own functions change
4
+ (join, leave, command, tick). The server runs them, ticks the world on a fixed clock and sends the whole state to
5
+ every seated player. Clients predict their own player and draw everyone else smoothly a moment behind. The same
6
+ code runs in one Node process, which hosts many worlds, and on Cloudflare, with one Durable Object per world.
7
+
8
+ ```bash
9
+ pnpm add @super-line/plugin-multiplayer
10
+ ```
11
+
12
+ Guides: [run a game world](https://super-line.dogar.biz/how-to/plugin-multiplayer) ·
13
+ [game worlds on Cloudflare](https://super-line.dogar.biz/how-to/multiplayer-on-cloudflare) ·
14
+ [measure and tune](https://super-line.dogar.biz/how-to/multiplayer-measure-and-tune) ·
15
+ [tutorial](https://super-line.dogar.biz/tutorials/build-a-multiplayer-game) ·
16
+ [how it works](https://super-line.dogar.biz/concepts/server-ticked-worlds).
17
+
18
+ > **0.x.** The API may change between minor versions.
19
+
20
+ ## The game
21
+
22
+ A game is a plain object of functions over its state. The schemas are any Standard Schema with a synchronous
23
+ validator; zod is used below.
24
+
25
+ ```ts
26
+ // world.ts: imported by the server and the browser
27
+ import * as z from 'zod'
28
+ import { defineWorld } from '@super-line/plugin-multiplayer'
29
+
30
+ const player = z.object({ name: z.string(), x: z.number(), y: z.number(), ix: z.number(), iy: z.number() })
31
+
32
+ export const arena = defineWorld({
33
+ state: z.object({ players: z.record(z.string(), player) }),
34
+ command: z.object({ x: z.number().min(-1).max(1), y: z.number().min(-1).max(1) }),
35
+ profile: z.object({ name: z.string().max(64) }),
36
+ tickRate: 30, // ticks a second; leave it out and the world only reacts to commands
37
+ sendRate: 10, // frames a second, at most tickRate; default min(10, tickRate)
38
+ maxPlayers: 10,
39
+
40
+ initialState: () => ({ players: {} }),
41
+ onJoin(s, { player: id, profile }) {
42
+ s.players[id] = { name: profile.name, x: 3, y: 3, ix: 0, iy: 0 }
43
+ },
44
+ onLeave(s, { player: id }) {
45
+ delete s.players[id]
46
+ },
47
+ onCommand(s, input, { player: id }) {
48
+ const me = s.players[id]
49
+ if (me) Object.assign(me, { ix: input.x, iy: input.y })
50
+ },
51
+ onTick(s, { dt }) {
52
+ for (const p of Object.values(s.players)) {
53
+ p.x += p.ix * 7 * dt
54
+ p.y += p.iy * 7 * dt
55
+ }
56
+ },
57
+
58
+ // What the client draws: an entity per id, and how to blend two of them.
59
+ entity: (s, id): { x: number; y: number } | undefined => {
60
+ const p = s.players[id]
61
+ return p && { x: p.x, y: p.y }
62
+ },
63
+ lerp: (a, b, t) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
64
+ })
65
+ ```
66
+
67
+ - Functions change the state **in place**. Call `reject(code, reason?)` inside `onCommand` to refuse a command:
68
+ the state goes back to what it was before the command, and the sender gets
69
+ `{ applied: false, code, reason }`. If `onCommand` throws anything else, the result is `{ applied: false, code: 'INTERNAL' }`
70
+ and the error is logged. A throw in `onTick` is logged and the loop goes on.
71
+ - Every function gets one context: `tick`, `now`, `players`, `predicting`, and `send(player, message)` /
72
+ `broadcast(message)` for the optional `message` schema. Join, leave and command add `player` and `profile`;
73
+ tick adds `dt` (always `1 / tickRate` seconds). Messages are sent only after the function returns, and are
74
+ dropped if the command is rejected.
75
+ - The browser runs `onCommand` and `predict ?? onTick` to predict its own moves. Keep them free of anything only
76
+ the server knows: while predicting, `ctx.players` is just your own seat, `ctx.profile` is `undefined`, and
77
+ `send`/`broadcast` do nothing. Pass a separate `predict` when the tick does work the client cannot repeat.
78
+ - `defineWorld` throws a `TypeError` for a `maxPlayers` that is not positive, a `tickRate` outside `(0, 60]`, a
79
+ `sendRate` above `tickRate`, and an `initialState()` that is not plain JSON.
80
+ - A player id is the seat's principal (below). It is a key in the state, so every player sees it. Entity ids
81
+ share the space with player ids: name a non-player entity something no principal can be (`'ball'` next to
82
+ UUIDs).
83
+
84
+ ## Wiring
85
+
86
+ ```ts
87
+ // contract.ts
88
+ import { defineContract } from '@super-line/core'
89
+ import { multiplayerContract } from '@super-line/plugin-multiplayer'
90
+ import { arena } from './world.js'
91
+
92
+ export const arenaContract = multiplayerContract(arena)
93
+ export const contract = defineContract({ roles: { user: {} }, plugins: [arenaContract] })
94
+ ```
95
+
96
+ ```ts
97
+ // server.ts: one Node process, any number of worlds
98
+ import { createServer } from 'node:http'
99
+ import { createSuperLineServer } from '@super-line/server'
100
+ import { webSocketServerTransport } from '@super-line/transport-websocket'
101
+ import { memoryCollections } from '@super-line/collections-memory'
102
+ import { multiplayer } from '@super-line/plugin-multiplayer/server'
103
+
104
+ const mp = multiplayer({
105
+ world: arena,
106
+ onlyWorld: null, // host any world id
107
+ authorize: ({ player }) => ({ profile: { name: player } }), // who may take a seat; return false to refuse
108
+ })
109
+
110
+ const server = createServer()
111
+ createSuperLineServer(contract, {
112
+ transports: [webSocketServerTransport({ server })],
113
+ collections: memoryCollections(), // required: each world is saved as a row
114
+ authenticate: () => ({ role: 'user', ctx: {} }),
115
+ plugins: [mp.plugin],
116
+ })
117
+ server.listen(8080)
118
+ ```
119
+
120
+ ```ts
121
+ // browser
122
+ import { multiplayerClient } from '@super-line/plugin-multiplayer/client'
123
+
124
+ const mp = multiplayerClient(client, arenaContract) // one wrapper per connected super-line client
125
+ const world = await mp.join('lobby')
126
+
127
+ function onRenderFrame(input: { x: number; y: number }) {
128
+ void world.send(input) // at most one command goes out per tick
129
+ const me = world.at(world.seat) // your own character, predicted
130
+ for (const id of Object.keys(world.state.players)) {
131
+ if (id !== world.seat) draw(id, world.at(id)) // everyone else, interpolated
132
+ }
133
+ draw(world.seat, me)
134
+ }
135
+
136
+ world.on('closed', ({ reason }) => showNotice(reason))
137
+ ```
138
+
139
+ The server kit's options:
140
+
141
+ | Option | Meaning |
142
+ | --- | --- |
143
+ | `world` | the game from `defineWorld` |
144
+ | `onlyWorld` | `string \| null`, required. A string is the one world id this server hosts; any other id gets `WRONG_WORLD` before `authorize` runs. `null` hosts any id. |
145
+ | `authorize` | required. `({ joiner, player, world, exists, ctx }) => false \| true \| { profile }`, may be async. Deny-by-default: `false` or a missing hook refuses the join with `FORBIDDEN`; a throw fails the join with that error if it is a `SuperLineError`, otherwise with `INTERNAL`. When the world has a `profile` schema, return `{ profile }`; it is validated and reaches the game as `ctx.profile`. `exists` is whether the world has been created. |
146
+ | `seatGraceMs` | how long a dropped player's seat is held, default 30 000; `0` leaves at once |
147
+ | `saveEveryMs` | how often a ticking world saves, default 5 000 |
148
+ | `stats` | measure each world, default `false`. See [Stats](#stats). |
149
+
150
+ The kit also has `worlds.get(id)`, `worlds.list()` and `worlds.delete(id)`. Deleting is the only way a world ends:
151
+ the row goes, and every seated client gets `closed` with `deleted`.
152
+
153
+ ### The world handle
154
+
155
+ `world.state` and `world.tick` are the latest server state. `world.predicted` is that state with your unconfirmed
156
+ commands re-applied and the tick run forward. `world.at(id)` is the entity to draw now: your own from the
157
+ prediction, glided over one tick so a correction bends instead of jumping, and everyone else's from a buffer of
158
+ recent states, a little in the past. At 30 ticks and 10 sends a second that is about 133 ms plus the network delay
159
+ behind. `world.serverTick()` is the estimated server tick. Events: `frame`, `message`, `seat`
160
+ (`joined | left | dropped | resumed`), `rejected` and `closed`.
161
+
162
+ `send(command)` resolves `{ applied: true, tick }` or `{ applied: false, code, reason? }`. In a ticking world a
163
+ newer `send` before the next tick resolves the waiting one with `SUPERSEDED`. It rejects with `DISCONNECTED` while
164
+ the connection is down: a command is never queued across a reconnect. A command counts as confirmed when a
165
+ state frame shows the server handled it, not when its response arrives, because the two can arrive in either
166
+ order.
167
+
168
+ While seated in a ticking world the client sends a clock request every 5 s (`clockEveryMs`). It feeds
169
+ `serverTick()` and, on Cloudflare, is a real message to the world's object. A world with no tick is never pinged.
170
+
171
+ ## Stats
172
+
173
+ Both halves measure what the plugin does, for a profiling overlay or a load run.
174
+
175
+ **Client.** `world.stats()` returns plain numbers and is cheap enough to call every render frame: the counters
176
+ and rolling values are kept where frames, commands and clock replies already arrive, and a frame arriving computes
177
+ nothing for stats. Two numbers are worked out on the first `stats()` read after a frame, and only then: the frame
178
+ size, which re-encodes the latest frame as JSON, and `correction`, which needs the prediction from the new frame.
179
+ That is the prediction the next render reads anyway (`world.at(world.seat)` or `world.predicted`), so a page that
180
+ draws its own player pays nothing extra; a client that never predicts, such as a headless bot, never pays for it.
181
+
182
+ | Field | Unit | Meaning |
183
+ | --- | --- | --- |
184
+ | `rttMs` | ms | smoothed round trip of the join and clock requests; undefined until one returns |
185
+ | `clockErrorMs` | ms | how far clock readings land from the client's estimate of the server clock, smoothed |
186
+ | `renderDelayTicks`, `renderDelayMs` | ticks, ms | how far behind the server clock other entities are drawn |
187
+ | `latenessMs`, `jitterMs` | ms | how late frames arrive against the clock, and how much that varies |
188
+ | `predictionLeadTicks` | ticks | how far ahead of the latest frame the prediction runs |
189
+ | `framesPerSecond` | per second | state frames received over about the last second |
190
+ | `frameBytes` | bytes | the latest frame's size on the wire with the default JSON serializer |
191
+ | `msSinceFrame` | ms | time since the latest frame arrived |
192
+ | `pendingCommands` | count | sent and not yet shown in a frame, rejected or failed |
193
+ | `commandsSent`, `commandsApplied`, `commandsRejected`, `commandsSuperseded` | count | since the handle opened |
194
+ | `correction` | state units | how far the latest frame moved your predicted entity: the straight-line distance over the numeric fields `entity` returns, between the last prediction made from the previous frame and the first made from the new one. It keeps its last value when nothing predicted between two frames, and is undefined without `entity` or before a comparison |
195
+ | `server` | | the server's numbers from the latest clock reply, or undefined |
196
+
197
+ **Server.** With `multiplayer({ ..., stats: true })` each world records the numbers below. They ride in every
198
+ clock reply, so a client sees them as `world.stats().server`, and the kit returns them as `stats` from
199
+ `worlds.get` and `worlds.list` for a live world. With `stats` off nothing is measured and the clock reply carries
200
+ only `tick`, `ms` and `epoch`. The type is `WorldServerStats`.
201
+
202
+ | Field | Unit | Meaning |
203
+ | --- | --- | --- |
204
+ | `tickMsLast` | ms | the latest tick: `onTick` and sending the messages it queued, not the frame |
205
+ | `tickMsMean`, `tickMsMax` | ms | over the last completed one-second window |
206
+ | `ticksPerSecond` | per second | ticks run in that window |
207
+ | `ticksDropped` | ticks | catch-up ticks skipped because the loop fell more than 5 behind, since the world loaded |
208
+ | `frameBytes` | bytes | the latest state frame, encoded once more with the server's serializer, as it goes on the wire |
209
+ | `framesSent` | count | state frames sent since the world loaded |
210
+ | `seated`, `away` | count | seats held by a connection, and seats held for a dropped player |
211
+ | `saveMs` | ms | the latest save |
212
+
213
+ Measuring a frame costs one extra encode per send, which is why `stats` is off by default. Durations use
214
+ `performance.now()`. On deployed Cloudflare Workers, `performance.now()` and `Date.now()` only advance after I/O,
215
+ so a tick that does no I/O reads `0` there; `wrangler dev` advances them normally. Use Cloudflare's CPU profiling
216
+ for production tick cost. A save writes to the object's SQLite, and may read `0` for the same reason.
217
+
218
+ To refresh the server's numbers about once a second, ping faster:
219
+ `multiplayerClient(client, arenaContract, { clockEveryMs: 1000 })`. `WorldStats` and `WorldServerStats` are both
220
+ exported from `/client`.
221
+
222
+ ## Seats
223
+
224
+ A seat belongs to the connection's principal, which is the server's `identify(conn)` and falls back to the
225
+ connection id.
226
+
227
+ - **A drop** puts the seat away for `seatGraceMs`. The character stays in the world, others get `seat` with
228
+ `dropped`, and the game hears `onLeave` only when the grace runs out. An away seat still counts toward
229
+ `maxPlayers` and keeps the world ticking.
230
+ - **A reconnect** within the grace resumes the seat without `authorize` or `onJoin`. The wrapper re-joins on its
231
+ own after a reconnect.
232
+ - **The newest connection wins.** The same principal joining from a second connection takes the seat. The first
233
+ gets `closed` with `replaced`, and its socket stays open. Its handle is closed for good: to play there again,
234
+ build a new wrapper and join.
235
+ - **Without `identify`**, every connection is its own principal, so a reconnect is a new player and the old
236
+ seat expires after the grace.
237
+
238
+ ## Saving
239
+
240
+ Each world is one row in the server-only collection `mpWorlds`, which the contract fragment declares: the state,
241
+ the tick and the seats with their profiles. Clients get `FORBIDDEN` on it. The row is written on join, on leave
242
+ and grace expiry, every `saveEveryMs` while ticking, and after every applied command in a world with no tick. A crash or restart can lose up to one save interval of a ticking world.
243
+
244
+ On the first join after a restart the world loads from its row with every seat away. A row whose state no longer
245
+ fits the state schema fails the join with `STATE_INVALID` until the host fixes or deletes it.
246
+
247
+ A server with no `collections` backend refuses to start. A row is capped at 2 MB on Durable Object SQLite. A save
248
+ over a backend's limit is logged on every attempt, and the world keeps running from memory.
249
+
250
+ ## On Cloudflare
251
+
252
+ Run one Durable Object per world, reached by the world's name, and set `onlyWorld` to that name so one socket can
253
+ only ever reach its own world. Route only the socket path to the object, because every request wakes it:
254
+
255
+ ```ts
256
+ // worker.ts
257
+ import { cloudflareCollections } from '@super-line/collections-cloudflare'
258
+ import { createDurableNode, routeToNode } from '@super-line/transport-cloudflare'
259
+
260
+ export class WorldNode extends createDurableNode((ctx, _env: Env, base) => {
261
+ const name = ctx.id.name
262
+ if (name === undefined) throw new Error('WorldNode must be reached by name')
263
+ const collections = cloudflareCollections(ctx.storage, contract.collections)
264
+ const mp = multiplayer({ world: arena, onlyWorld: name, authorize: () => ({ profile: { name: 'guest' } }) })
265
+ return createSuperLineServer(contract, {
266
+ ...base,
267
+ collections,
268
+ authenticate: () => ({ role: 'user', ctx: {} }),
269
+ plugins: [mp.plugin],
270
+ })
271
+ }) {}
272
+
273
+ export default {
274
+ fetch: (request, env) => {
275
+ const url = new URL(request.url)
276
+ const world = url.searchParams.get('world')
277
+ if (url.pathname !== '/ws' || !world) return new Response('Not found', { status: 404 })
278
+ return routeToNode(request, env.WORLDS, { name: () => world })
279
+ },
280
+ } satisfies ExportedHandler<Env>
281
+ ```
282
+
283
+ A world with no tick can hibernate between commands, once no dropped player's seat is still inside its grace
284
+ period (that timer keeps the object awake). When an object wakes, the plugin reloads each world from its
285
+ row and gives the surviving connections their seats back without `onJoin`. The clock restarts from the saved
286
+ tick, so a ticking world loses what happened since its last save, and everyone gets one fresh frame. A connection with nothing saved to go back to gets `closed` with `lost`.
287
+ `ctx.id.name` is set on a wake caused by a WebSocket message, so the host does not need to store the name.
288
+
289
+ ## With plugin-auth
290
+
291
+ The plugin works with any `identify`. With plugin-auth the principal is the user id, so a seat follows the account
292
+ across reloads and tabs. A common `authorize` admits only signed-in users and hands the game their name:
293
+
294
+ ```ts
295
+ const authKit = auth({ contract, collections, defaultRoles: ['user'] })
296
+ const mp = multiplayer({
297
+ world: arena,
298
+ onlyWorld: name,
299
+ authorize: async ({ joiner }) => {
300
+ if (!joiner.userId) return false
301
+ const user = await authKit.users.get(joiner.userId)
302
+ return user && !user.deletedAt ? { profile: { name: user.displayName } } : false
303
+ },
304
+ })
305
+ createSuperLineServer(contract, {
306
+ ...base,
307
+ collections,
308
+ authenticate: authKit.authenticate,
309
+ identify: authKit.identify,
310
+ plugins: [authKit.plugin, mp.plugin],
311
+ })
312
+ ```
313
+
314
+ Put `authContract()` beside the game's fragment in `defineContract({ plugins })`. A plugin-auth sign-in or
315
+ sign-out replaces the super-line client, so build a new `multiplayerClient` on each new client. Leave the world
316
+ before signing out if the character should disappear at once instead of after the grace. If plugin-auth runs
317
+ inside each world's Durable Object, accounts belong to that world.
318
+
319
+ ## Limits and what is not in this version
320
+
321
+ - Every player gets the whole state, the same for everyone, at the send rate. There are no deltas and no private
322
+ per-player views. That suits tens of players, not hundreds.
323
+ - A world lives on one node. In a Node cluster, every player of a world must reach the same process.
324
+ - Commands are not exactly-once across a reconnect: one sent while disconnected fails.
325
+ - One row per world, capped by the backend, with no splitting.
326
+ - No physics engine (collision is the game's code), and no matchmaking, lockstep, spectators or lag compensation.
327
+ - TypeScript client only. There is no written wire protocol yet.
328
+ - The client imports no rendering engine: the game decides what an entity is and how to blend one.
329
+
330
+ See [`examples/game-arena`](../../examples/game-arena): a PlayCanvas arena on Cloudflare with plugin-auth.
331
+
332
+ ## Third-party code
333
+
334
+ The client's clock, prediction and interpolation are ported from [Tickflare](https://github.com/Giamme/tickflare)
335
+ (MIT). The files and the license are listed in [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,35 @@
1
+ # Third-party notices
2
+
3
+ ## Tickflare
4
+
5
+ Parts of this package are ported from [Tickflare](https://github.com/Giamme/tickflare) (commit `2dc0fa0`):
6
+
7
+ | File in this package | Ported from |
8
+ | --- | --- |
9
+ | `src/client/clock.ts` | `src/client/clock.ts` (`ServerClock`) |
10
+ | `src/client/predict.ts` | `src/client/predict.ts` (`Predictor`) |
11
+ | `src/client/buffered.ts` | `src/client/buffered.ts` (`BufferedInterpolator`) and `src/client/interpolate.ts` (`Interpolator`, as `Glide`) |
12
+
13
+ ```
14
+ MIT License
15
+
16
+ Copyright (c) 2026 Giamme
17
+
18
+ Permission is hereby granted, free of charge, to any person obtaining a copy
19
+ of this software and associated documentation files (the "Software"), to deal
20
+ in the Software without restriction, including without limitation the rights
21
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
+ copies of the Software, and to permit persons to whom the Software is
23
+ furnished to do so, subject to the following conditions:
24
+
25
+ The above copyright notice and this permission notice shall be included in all
26
+ copies or substantial portions of the Software.
27
+
28
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34
+ SOFTWARE.
35
+ ```
@@ -0,0 +1,19 @@
1
+ // src/bytes.ts
2
+ function encodedBytes(encoded) {
3
+ if (typeof encoded !== "string") return encoded.byteLength;
4
+ let bytes = 0;
5
+ for (let i = 0; i < encoded.length; i++) {
6
+ const c = encoded.charCodeAt(i);
7
+ if (c < 128) bytes += 1;
8
+ else if (c < 2048) bytes += 2;
9
+ else if (c >= 55296 && c < 56320 && i + 1 < encoded.length) {
10
+ bytes += 4;
11
+ i++;
12
+ } else bytes += 3;
13
+ }
14
+ return bytes;
15
+ }
16
+
17
+ export {
18
+ encodedBytes
19
+ };
@@ -0,0 +1,148 @@
1
+ // src/index.ts
2
+ import * as z2 from "zod";
3
+ import { defineContractPlugin } from "@super-line/core";
4
+
5
+ // src/schema.ts
6
+ import * as z from "zod";
7
+ import { jsonSchemaOf } from "@super-line/core";
8
+ var hostSchema = (schema) => {
9
+ const shape = jsonSchemaOf(schema) ?? {};
10
+ return z.unknown().transform((value, ctx) => {
11
+ const result = schema["~standard"].validate(value);
12
+ if (result instanceof Promise) {
13
+ throw new TypeError(
14
+ "plugin-multiplayer: async Standard Schema validators are not supported (validation runs synchronously inside the envelope schema)"
15
+ );
16
+ }
17
+ if (result.issues) {
18
+ for (const issue of result.issues) {
19
+ const path = (issue.path ?? []).map((seg) => typeof seg === "object" && seg !== null ? seg.key : seg).filter((seg) => typeof seg !== "symbol");
20
+ ctx.addIssue({ code: "custom", message: issue.message, path });
21
+ }
22
+ return z.NEVER;
23
+ }
24
+ return result.value;
25
+ }).meta(shape);
26
+ };
27
+
28
+ // src/index.ts
29
+ var CommandRejected = class extends Error {
30
+ code;
31
+ reason;
32
+ constructor(code, reason) {
33
+ super(reason ?? code);
34
+ this.name = "CommandRejected";
35
+ this.code = code;
36
+ if (reason !== void 0) this.reason = reason;
37
+ }
38
+ };
39
+ function reject(code, reason) {
40
+ throw new CommandRejected(code, reason);
41
+ }
42
+ var isJson = (value) => {
43
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
44
+ if (typeof value === "number") return Number.isFinite(value);
45
+ if (Array.isArray(value)) return value.every(isJson);
46
+ if (typeof value !== "object") return false;
47
+ const proto = Object.getPrototypeOf(value);
48
+ if (proto !== Object.prototype && proto !== null) return false;
49
+ return Object.values(value).every(isJson);
50
+ };
51
+ function defineWorld(world) {
52
+ const { maxPlayers, tickRate, sendRate } = world;
53
+ if (!Number.isFinite(maxPlayers) || maxPlayers <= 0) throw new TypeError("maxPlayers must be a positive number");
54
+ if (tickRate !== void 0 && !(tickRate > 0 && tickRate <= 60))
55
+ throw new TypeError("tickRate must be greater than 0 and at most 60");
56
+ if (tickRate !== void 0 && sendRate !== void 0 && !(sendRate > 0 && sendRate <= tickRate))
57
+ throw new TypeError("sendRate must be positive and at most tickRate");
58
+ if (!isJson(world.initialState())) throw new TypeError("initialState() must return plain JSON");
59
+ return world;
60
+ }
61
+ var WORLDS_COLLECTION = "mpWorlds";
62
+ var worldId = z2.string().min(1).max(128);
63
+ var player = z2.string().min(1).max(256);
64
+ var tick = z2.number().int().min(0);
65
+ var rowSchema = z2.strictObject({
66
+ id: worldId,
67
+ state: z2.unknown(),
68
+ tick,
69
+ seats: z2.array(z2.strictObject({ player, profile: z2.unknown() })),
70
+ updatedAt: z2.number()
71
+ });
72
+ var surfaceOf = (world) => {
73
+ const frame = z2.strictObject({
74
+ world: worldId,
75
+ tick,
76
+ ms: z2.number().int().min(0).optional(),
77
+ epoch: z2.string().max(64).optional(),
78
+ acks: z2.record(player, z2.number().int().min(0)),
79
+ state: hostSchema(world.state)
80
+ });
81
+ const rate = z2.number().min(0);
82
+ const n = z2.number().min(0);
83
+ const stats = z2.strictObject({
84
+ tickMsLast: n,
85
+ tickMsMean: n,
86
+ tickMsMax: n,
87
+ ticksPerSecond: n,
88
+ ticksDropped: n,
89
+ frameBytes: n,
90
+ framesSent: n,
91
+ seated: n,
92
+ away: n,
93
+ saveMs: n
94
+ });
95
+ return {
96
+ clientToServer: {
97
+ mpJoin: {
98
+ input: z2.strictObject({ world: worldId }),
99
+ output: z2.strictObject({ seat: player, tickRate: rate, sendRate: rate, maxPlayers: z2.number(), frame })
100
+ },
101
+ mpLeave: { input: z2.strictObject({ world: worldId }), output: z2.strictObject({}) },
102
+ mpCommand: {
103
+ input: z2.strictObject({
104
+ world: worldId,
105
+ seq: z2.number().int().positive().max(Number.MAX_SAFE_INTEGER),
106
+ command: hostSchema(world.command)
107
+ }),
108
+ output: z2.union([
109
+ z2.strictObject({ applied: z2.literal(true), tick }),
110
+ z2.strictObject({ applied: z2.literal(false), code: z2.string(), reason: z2.string().optional() })
111
+ ])
112
+ },
113
+ mpClock: {
114
+ input: z2.strictObject({ world: worldId }),
115
+ output: z2.strictObject({ tick, ms: z2.number().optional(), epoch: z2.string().optional(), stats: stats.optional() })
116
+ }
117
+ },
118
+ serverToClient: {
119
+ "mp.state": { payload: frame },
120
+ "mp.message": {
121
+ payload: z2.strictObject({ world: worldId, message: world.message ? hostSchema(world.message) : z2.never() })
122
+ },
123
+ "mp.seat": {
124
+ payload: z2.strictObject({
125
+ world: worldId,
126
+ player,
127
+ change: z2.enum(["joined", "left", "dropped", "resumed"])
128
+ })
129
+ },
130
+ "mp.closed": { payload: z2.strictObject({ world: worldId, reason: z2.enum(["deleted", "replaced", "lost"]) }) }
131
+ }
132
+ };
133
+ };
134
+ function multiplayerContract(world) {
135
+ const fragment = {
136
+ shared: surfaceOf(world),
137
+ collections: { [WORLDS_COLLECTION]: { schema: rowSchema, key: "id" } }
138
+ };
139
+ return Object.assign(defineContractPlugin("multiplayer", fragment), { world });
140
+ }
141
+
142
+ export {
143
+ CommandRejected,
144
+ reject,
145
+ defineWorld,
146
+ WORLDS_COLLECTION,
147
+ multiplayerContract
148
+ };