@super-line/plugin-multiplayer 0.1.0 → 0.2.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/dist/server.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import {
2
+ applyPatch,
3
+ diff,
2
4
  encodedBytes
3
- } from "./chunk-AUQT3TTM.js";
5
+ } from "./chunk-GRDMIVAD.js";
4
6
  import {
5
7
  CommandRejected,
6
- WORLDS_COLLECTION
7
- } from "./chunk-QG5AWEMR.js";
8
+ WORLDS_COLLECTION,
9
+ isJson
10
+ } from "./chunk-SR5BFY5T.js";
8
11
 
9
12
  // src/server.ts
10
13
  import { getLogger } from "@logtape/logtape";
@@ -18,6 +21,8 @@ function multiplayer(opts) {
18
21
  const game = opts.world;
19
22
  const worlds = /* @__PURE__ */ new Map();
20
23
  const loading = /* @__PURE__ */ new Map();
24
+ const seeding = /* @__PURE__ */ new Map();
25
+ const patches = opts.frames === "patch";
21
26
  let sl;
22
27
  let disposed = false;
23
28
  let rebuilt = Promise.resolve();
@@ -63,7 +68,13 @@ function multiplayer(opts) {
63
68
  if (w.meter) r.stats = statsOf(w, w.meter);
64
69
  return r;
65
70
  };
66
- const frameOf = (w) => ({ world: w.id, ...reading(w), acks: { ...w.acks }, state: w.state });
71
+ const frameOf = (w, state = w.state) => ({
72
+ world: w.id,
73
+ ...reading(w),
74
+ acks: { ...w.acks },
75
+ ...patches ? { n: w.n } : {},
76
+ state
77
+ });
67
78
  const seatsOf = (w) => [...w.seats].map(([player, { profile }]) => ({ player, profile }));
68
79
  const worldContext = (w, outbox) => ({
69
80
  tick: w.tick,
@@ -87,8 +98,20 @@ function multiplayer(opts) {
87
98
  }
88
99
  }
89
100
  };
90
- const sendFrame = (w) => {
91
- const frame = frameOf(w);
101
+ const sendFrame = (w, whole = false) => {
102
+ let frame;
103
+ if (!patches) frame = frameOf(w);
104
+ else {
105
+ w.n++;
106
+ const patch = whole ? null : diff(w.base, w.state);
107
+ if (patch !== null) {
108
+ if (patch) w.base = applyPatch(w.base, structuredClone(patch));
109
+ frame = { world: w.id, ...reading(w), acks: { ...w.acks }, n: w.n, patch: patch ?? {} };
110
+ } else {
111
+ w.base = structuredClone(w.state);
112
+ frame = frameOf(w, w.base);
113
+ }
114
+ }
92
115
  context().room(roomOf(w.id)).broadcast("mp.state", frame);
93
116
  if (!w.meter) return;
94
117
  w.meter.frameBytes = encodedBytes(context().serializer.encode({ t: "evt", e: "mp.state", d: frame }));
@@ -153,12 +176,13 @@ function multiplayer(opts) {
153
176
  const due = Math.floor((now - c.at) / period + 1e-6) - (w.tick - c.tick);
154
177
  const before = w.tick;
155
178
  for (let i = 0; i < Math.min(due, MAX_CATCH_UP); i++) runTick(w);
156
- if (due > MAX_CATCH_UP) {
179
+ const fresh = due > MAX_CATCH_UP;
180
+ if (fresh) {
157
181
  Object.assign(c, { at: now, tick: w.tick, epoch: newEpoch() });
158
182
  if (w.meter) w.meter.ticksDropped += due - MAX_CATCH_UP;
159
183
  }
160
184
  if (w.meter) closeWindow(w.meter, now);
161
- if (crossed(before, w.tick, sendRate)) sendFrame(w);
185
+ if (crossed(before, w.tick, sendRate) || fresh && patches) sendFrame(w, fresh);
162
186
  if (crossed(before, w.tick, 1e3 / saveEveryMs)) void save(w);
163
187
  arm(w, c);
164
188
  };
@@ -174,13 +198,10 @@ function multiplayer(opts) {
174
198
  w.clock = void 0;
175
199
  sendFrame(w);
176
200
  };
177
- const joined = (w, player) => ({
178
- seat: player,
179
- tickRate,
180
- sendRate,
181
- maxPlayers: game.maxPlayers,
182
- frame: frameOf(w)
183
- });
201
+ const joined = (w, player) => {
202
+ if (patches) sendFrame(w);
203
+ return { seat: player, tickRate, sendRate, maxPlayers: game.maxPlayers, frame: frameOf(w, patches ? w.base : w.state) };
204
+ };
184
205
  const profileOf = (verdict) => {
185
206
  if (verdict === true) return void 0;
186
207
  if (!game.profile) return verdict.profile;
@@ -211,7 +232,8 @@ function multiplayer(opts) {
211
232
  acks: {},
212
233
  persisted: true,
213
234
  updatedAt: row.updatedAt,
214
- meter: newMeter()
235
+ meter: newMeter(),
236
+ n: 0
215
237
  };
216
238
  for (const { player, profile } of row.seats) {
217
239
  const seat = { profile };
@@ -276,9 +298,46 @@ function multiplayer(opts) {
276
298
  async function joinAgain(w, player, seat, conn) {
277
299
  if (seat.conn === conn) return joined(w, player);
278
300
  await bind(w, player, seat, conn);
279
- if (!tickRate) sendFrame(w);
301
+ if (!tickRate && !patches) sendFrame(w);
280
302
  return joined(w, player);
281
303
  }
304
+ async function seed(id) {
305
+ if (!opts.initialState) return game.initialState();
306
+ const state = await opts.initialState(id);
307
+ try {
308
+ if (!isJson(state)) throw new TypeError("not plain JSON");
309
+ return validateSync(game.state, state);
310
+ } catch (error) {
311
+ log.error("initialState returned a state for world {world} that is not valid: {error}", { world: id, error });
312
+ throw new SuperLineError("STATE_INVALID", `initialState returned an invalid state for world '${id}'`);
313
+ }
314
+ }
315
+ function create(id) {
316
+ let pending = seeding.get(id);
317
+ if (!pending) {
318
+ pending = seed(id).then((state) => {
319
+ let w = worlds.get(id);
320
+ if (!w)
321
+ worlds.set(
322
+ id,
323
+ w = {
324
+ id,
325
+ state,
326
+ tick: 0,
327
+ seats: /* @__PURE__ */ new Map(),
328
+ acks: {},
329
+ persisted: false,
330
+ updatedAt: 0,
331
+ meter: newMeter(),
332
+ n: 0
333
+ }
334
+ );
335
+ return w;
336
+ }).finally(() => seeding.delete(id));
337
+ seeding.set(id, pending);
338
+ }
339
+ return pending;
340
+ }
282
341
  async function rebuild(ctx) {
283
342
  await ctx.ready;
284
343
  for (const name of ctx.local.rooms) {
@@ -303,7 +362,7 @@ function multiplayer(opts) {
303
362
  await bind(w, player, seat, conn);
304
363
  bound = true;
305
364
  }
306
- if (w && bound) sendFrame(w);
365
+ if (w && bound) sendFrame(w, true);
307
366
  }
308
367
  }
309
368
  const dropConn = (conn) => {
@@ -333,23 +392,9 @@ function multiplayer(opts) {
333
392
  assertRoom(loaded);
334
393
  const verdict = opts.authorize ? await opts.authorize({ joiner: context().describe(conn), player, world: id, exists: loaded !== void 0, ctx }) : false;
335
394
  if (!verdict) throw new SuperLineError("FORBIDDEN", "Join denied");
336
- if (!conn.raw.writable) throw new SuperLineError("DISCONNECTED", "The connection closed during authorize");
337
395
  const profile = profileOf(verdict);
338
- let w = worlds.get(id);
339
- if (!w)
340
- worlds.set(
341
- id,
342
- w = {
343
- id,
344
- state: game.initialState(),
345
- tick: 0,
346
- seats: /* @__PURE__ */ new Map(),
347
- acks: {},
348
- persisted: false,
349
- updatedAt: 0,
350
- meter: newMeter()
351
- }
352
- );
396
+ const w = worlds.get(id) ?? await create(id);
397
+ if (!conn.raw.writable) throw new SuperLineError("DISCONNECTED", "The connection closed while joining");
353
398
  const raced = w.seats.get(player);
354
399
  if (raced) return await joinAgain(w, player, raced, conn);
355
400
  assertRoom(w);
@@ -474,6 +519,29 @@ function multiplayer(opts) {
474
519
  const row = await rows().read(id);
475
520
  if (row) await rows().delete(id);
476
521
  return w !== void 0 || row !== void 0;
522
+ },
523
+ async run(id, fn) {
524
+ await rebuilt;
525
+ const w = await load(id);
526
+ if (!w) return false;
527
+ const outbox = [];
528
+ const copy = structuredClone(w.state);
529
+ fn(copy, worldContext(w, outbox));
530
+ w.state = copy;
531
+ if (!w.clock) sendFrame(w);
532
+ flush(w, outbox);
533
+ if (!w.clock) await save(w);
534
+ return true;
535
+ },
536
+ async removeSeat(id, player, o) {
537
+ await rebuilt;
538
+ const w = await load(id);
539
+ const seat = w?.seats.get(player);
540
+ if (!w || !seat) return false;
541
+ if (seat.conn)
542
+ context().toConn(seat.conn.id).emit("mp.closed", { world: id, reason: "removed", ...o?.reason !== void 0 ? { detail: o.reason } : {} });
543
+ await vacate(w, player, seat);
544
+ return true;
477
545
  }
478
546
  }
479
547
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@super-line/plugin-multiplayer",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Server-run game worlds for super-line — the server owns one JSON state per world and sends it to every seated player. A paired plugin (contract · server · client).",
6
6
  "keywords": [
@@ -89,8 +89,8 @@
89
89
  "@super-line/collections-memory": "0.3.0",
90
90
  "@super-line/collections-sqlite": "0.5.2",
91
91
  "@super-line/server": "^0.25.0",
92
- "@super-line/core": "^0.24.0",
93
- "@super-line/transport-loopback": "0.7.0"
92
+ "@super-line/transport-loopback": "0.7.0",
93
+ "@super-line/core": "^0.24.0"
94
94
  },
95
95
  "scripts": {
96
96
  "build": "tsup"
@@ -1,19 +0,0 @@
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
- };