@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.cjs CHANGED
@@ -34,7 +34,7 @@ __export(server_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(server_exports);
36
36
  var import_logtape = require("@logtape/logtape");
37
- var import_core2 = require("@super-line/core");
37
+ var import_core3 = require("@super-line/core");
38
38
 
39
39
  // src/bytes.ts
40
40
  function encodedBytes(encoded) {
@@ -53,8 +53,23 @@ function encodedBytes(encoded) {
53
53
  }
54
54
 
55
55
  // src/index.ts
56
+ var z2 = __toESM(require("zod"), 1);
57
+ var import_core2 = require("@super-line/core");
58
+
59
+ // src/schema.ts
56
60
  var z = __toESM(require("zod"), 1);
57
61
  var import_core = require("@super-line/core");
62
+ var isJson = (value) => {
63
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
64
+ if (typeof value === "number") return Number.isFinite(value);
65
+ if (Array.isArray(value)) return value.every(isJson);
66
+ if (typeof value !== "object") return false;
67
+ const proto = Object.getPrototypeOf(value);
68
+ if (proto !== Object.prototype && proto !== null) return false;
69
+ return Object.values(value).every(isJson);
70
+ };
71
+
72
+ // src/index.ts
58
73
  var CommandRejected = class extends Error {
59
74
  code;
60
75
  reason;
@@ -66,16 +81,126 @@ var CommandRejected = class extends Error {
66
81
  }
67
82
  };
68
83
  var WORLDS_COLLECTION = "mpWorlds";
69
- var worldId = z.string().min(1).max(128);
70
- var player = z.string().min(1).max(256);
71
- var tick = z.number().int().min(0);
72
- var rowSchema = z.strictObject({
84
+ var worldId = z2.string().min(1).max(128);
85
+ var player = z2.string().min(1).max(256);
86
+ var tick = z2.number().int().min(0);
87
+ var rowSchema = z2.strictObject({
73
88
  id: worldId,
74
- state: z.unknown(),
89
+ state: z2.unknown(),
75
90
  tick,
76
- seats: z.array(z.strictObject({ player, profile: z.unknown() })),
77
- updatedAt: z.number()
91
+ seats: z2.array(z2.strictObject({ player, profile: z2.unknown() })),
92
+ updatedAt: z2.number()
78
93
  });
94
+ var element = z2.lazy(
95
+ () => z2.union([patchSchema, z2.tuple([z2.unknown()]), z2.tuple([z2.record(z2.string(), element), z2.number().int().min(0)])])
96
+ );
97
+ var patchSchema = z2.record(z2.string(), z2.union([element, z2.literal(0)]));
98
+
99
+ // src/patch.ts
100
+ function diff(prev, next) {
101
+ if (isPlainObject(prev) && isPlainObject(next)) return diffObjects(prev, next);
102
+ return jsonEqual(prev, next) ? void 0 : null;
103
+ }
104
+ function applyPatch(base, patch) {
105
+ const out = isPlainObject(base) ? { ...base } : {};
106
+ for (const key of Object.keys(patch)) {
107
+ if (key === "__proto__") continue;
108
+ const change = patch[key];
109
+ if (change === 0) delete out[key];
110
+ else if (Array.isArray(change)) out[key] = change.length === 2 ? applyArrayPatch(own(out, key), change) : change[0];
111
+ else if (change) out[key] = applyPatch(own(out, key), change);
112
+ }
113
+ return out;
114
+ }
115
+ var INDEX = /^(0|[1-9][0-9]*)$/;
116
+ function applyArrayPatch(base, [changes, length]) {
117
+ const out = Array.isArray(base) ? base.slice(0, length) : [];
118
+ for (const key of Object.keys(changes)) {
119
+ const index = Number(key);
120
+ if (!INDEX.test(key) || index >= length) continue;
121
+ const change = changes[key];
122
+ if (Array.isArray(change)) out[index] = change.length === 2 ? applyArrayPatch(out[index], change) : change[0];
123
+ else out[index] = applyPatch(out[index], change);
124
+ }
125
+ for (let index = out.length; index < length; index++) out[index] = null;
126
+ for (let index = 0; index < length; index++) if (!(index in out)) out[index] = null;
127
+ return out;
128
+ }
129
+ function diffArrays(prev, next) {
130
+ const changes = {};
131
+ let changed = 0;
132
+ let replaced = 0;
133
+ const shared = Math.min(prev.length, next.length);
134
+ for (let index = 0; index < shared; index++) {
135
+ const from = prev[index];
136
+ const to = next[index] === void 0 ? null : next[index];
137
+ if (isPlainObject(from) && isPlainObject(to)) {
138
+ const inner = diffObjects(from, to);
139
+ if (!inner) continue;
140
+ changes[index] = inner;
141
+ if (Object.keys(inner).length * 2 > Object.keys(to).length) replaced += 1;
142
+ } else if (Array.isArray(from) && Array.isArray(to)) {
143
+ const inner = diffArrays(from, to);
144
+ if (inner === void 0) continue;
145
+ if (inner === null) replaced += 1;
146
+ changes[index] = inner ?? [to];
147
+ } else if (jsonEqual(from, to)) {
148
+ continue;
149
+ } else {
150
+ changes[index] = [to];
151
+ replaced += 1;
152
+ }
153
+ changed += 1;
154
+ if (replaced * 2 > next.length) return null;
155
+ }
156
+ replaced += next.length - shared;
157
+ if (replaced * 2 > next.length) return null;
158
+ for (let index = shared; index < next.length; index++) {
159
+ changes[index] = [next[index] === void 0 ? null : next[index]];
160
+ changed += 1;
161
+ }
162
+ if (changed === 0 && prev.length === next.length) return void 0;
163
+ return [changes, next.length];
164
+ }
165
+ function diffObjects(prev, next) {
166
+ let patch;
167
+ for (const key of Object.keys(next)) {
168
+ const to = next[key];
169
+ if (to === void 0) continue;
170
+ const from = own(prev, key);
171
+ if (isPlainObject(from) && isPlainObject(to)) {
172
+ const inner = diffObjects(from, to);
173
+ if (inner) (patch ??= {})[key] = inner;
174
+ } else if (Array.isArray(from) && Array.isArray(to)) {
175
+ const inner = diffArrays(from, to);
176
+ if (inner !== void 0) (patch ??= {})[key] = inner ?? [to];
177
+ } else if (from === void 0 || !jsonEqual(from, to)) {
178
+ (patch ??= {})[key] = [to];
179
+ }
180
+ }
181
+ for (const key of Object.keys(prev)) {
182
+ if (prev[key] !== void 0 && own(next, key) === void 0) (patch ??= {})[key] = 0;
183
+ }
184
+ return patch;
185
+ }
186
+ function own(object, key) {
187
+ return Object.prototype.hasOwnProperty.call(object, key) ? object[key] : void 0;
188
+ }
189
+ function jsonEqual(a, b) {
190
+ if (a === b) return true;
191
+ if (Array.isArray(a)) {
192
+ if (!Array.isArray(b) || a.length !== b.length) return false;
193
+ for (let i = 0; i < a.length; i++) {
194
+ if (!jsonEqual(a[i], b[i])) return false;
195
+ }
196
+ return true;
197
+ }
198
+ if (isPlainObject(a) && isPlainObject(b)) return diffObjects(a, b) === void 0;
199
+ return false;
200
+ }
201
+ function isPlainObject(value) {
202
+ return typeof value === "object" && value !== null && !Array.isArray(value);
203
+ }
79
204
 
80
205
  // src/server.ts
81
206
  var log = (0, import_logtape.getLogger)(["super-line", "plugin-multiplayer", "server"]);
@@ -87,6 +212,8 @@ function multiplayer(opts) {
87
212
  const game = opts.world;
88
213
  const worlds = /* @__PURE__ */ new Map();
89
214
  const loading = /* @__PURE__ */ new Map();
215
+ const seeding = /* @__PURE__ */ new Map();
216
+ const patches = opts.frames === "patch";
90
217
  let sl;
91
218
  let disposed = false;
92
219
  let rebuilt = Promise.resolve();
@@ -132,7 +259,13 @@ function multiplayer(opts) {
132
259
  if (w.meter) r.stats = statsOf(w, w.meter);
133
260
  return r;
134
261
  };
135
- const frameOf = (w) => ({ world: w.id, ...reading(w), acks: { ...w.acks }, state: w.state });
262
+ const frameOf = (w, state = w.state) => ({
263
+ world: w.id,
264
+ ...reading(w),
265
+ acks: { ...w.acks },
266
+ ...patches ? { n: w.n } : {},
267
+ state
268
+ });
136
269
  const seatsOf = (w) => [...w.seats].map(([player2, { profile }]) => ({ player: player2, profile }));
137
270
  const worldContext = (w, outbox) => ({
138
271
  tick: w.tick,
@@ -156,8 +289,20 @@ function multiplayer(opts) {
156
289
  }
157
290
  }
158
291
  };
159
- const sendFrame = (w) => {
160
- const frame = frameOf(w);
292
+ const sendFrame = (w, whole = false) => {
293
+ let frame;
294
+ if (!patches) frame = frameOf(w);
295
+ else {
296
+ w.n++;
297
+ const patch = whole ? null : diff(w.base, w.state);
298
+ if (patch !== null) {
299
+ if (patch) w.base = applyPatch(w.base, structuredClone(patch));
300
+ frame = { world: w.id, ...reading(w), acks: { ...w.acks }, n: w.n, patch: patch ?? {} };
301
+ } else {
302
+ w.base = structuredClone(w.state);
303
+ frame = frameOf(w, w.base);
304
+ }
305
+ }
161
306
  context().room(roomOf(w.id)).broadcast("mp.state", frame);
162
307
  if (!w.meter) return;
163
308
  w.meter.frameBytes = encodedBytes(context().serializer.encode({ t: "evt", e: "mp.state", d: frame }));
@@ -222,12 +367,13 @@ function multiplayer(opts) {
222
367
  const due = Math.floor((now - c.at) / period + 1e-6) - (w.tick - c.tick);
223
368
  const before = w.tick;
224
369
  for (let i = 0; i < Math.min(due, MAX_CATCH_UP); i++) runTick(w);
225
- if (due > MAX_CATCH_UP) {
370
+ const fresh = due > MAX_CATCH_UP;
371
+ if (fresh) {
226
372
  Object.assign(c, { at: now, tick: w.tick, epoch: newEpoch() });
227
373
  if (w.meter) w.meter.ticksDropped += due - MAX_CATCH_UP;
228
374
  }
229
375
  if (w.meter) closeWindow(w.meter, now);
230
- if (crossed(before, w.tick, sendRate)) sendFrame(w);
376
+ if (crossed(before, w.tick, sendRate) || fresh && patches) sendFrame(w, fresh);
231
377
  if (crossed(before, w.tick, 1e3 / saveEveryMs)) void save(w);
232
378
  arm(w, c);
233
379
  };
@@ -243,21 +389,18 @@ function multiplayer(opts) {
243
389
  w.clock = void 0;
244
390
  sendFrame(w);
245
391
  };
246
- const joined = (w, player2) => ({
247
- seat: player2,
248
- tickRate,
249
- sendRate,
250
- maxPlayers: game.maxPlayers,
251
- frame: frameOf(w)
252
- });
392
+ const joined = (w, player2) => {
393
+ if (patches) sendFrame(w);
394
+ return { seat: player2, tickRate, sendRate, maxPlayers: game.maxPlayers, frame: frameOf(w, patches ? w.base : w.state) };
395
+ };
253
396
  const profileOf = (verdict) => {
254
397
  if (verdict === true) return void 0;
255
398
  if (!game.profile) return verdict.profile;
256
399
  try {
257
- return (0, import_core2.validateSync)(game.profile, verdict.profile);
400
+ return (0, import_core3.validateSync)(game.profile, verdict.profile);
258
401
  } catch (error) {
259
402
  log.error("authorize returned a profile that fails the world profile schema: {error}", { error });
260
- throw new import_core2.SuperLineError("INTERNAL", "Invalid profile from authorize");
403
+ throw new import_core3.SuperLineError("INTERNAL", "Invalid profile from authorize");
261
404
  }
262
405
  };
263
406
  const away = (w, player2, seat) => {
@@ -267,10 +410,10 @@ function multiplayer(opts) {
267
410
  const fromRow = (row) => {
268
411
  let state;
269
412
  try {
270
- state = (0, import_core2.validateSync)(game.state, row.state);
413
+ state = (0, import_core3.validateSync)(game.state, row.state);
271
414
  } catch (error) {
272
415
  log.error("World {world} has a saved state that fails the state schema: {error}", { world: row.id, error });
273
- throw new import_core2.SuperLineError("STATE_INVALID", `The saved state of world '${row.id}' no longer fits the world's schema`);
416
+ throw new import_core3.SuperLineError("STATE_INVALID", `The saved state of world '${row.id}' no longer fits the world's schema`);
274
417
  }
275
418
  const w = {
276
419
  id: row.id,
@@ -280,7 +423,8 @@ function multiplayer(opts) {
280
423
  acks: {},
281
424
  persisted: true,
282
425
  updatedAt: row.updatedAt,
283
- meter: newMeter()
426
+ meter: newMeter(),
427
+ n: 0
284
428
  };
285
429
  for (const { player: player2, profile } of row.seats) {
286
430
  const seat = { profile };
@@ -324,11 +468,11 @@ function multiplayer(opts) {
324
468
  const w = worlds.get(id);
325
469
  const player2 = conn.principal ?? conn.id;
326
470
  const seat = w?.seats.get(player2);
327
- if (!w || !seat || seat.conn !== conn) throw new import_core2.SuperLineError("NOT_SEATED", `Not seated in world '${id}'`);
471
+ if (!w || !seat || seat.conn !== conn) throw new import_core3.SuperLineError("NOT_SEATED", `Not seated in world '${id}'`);
328
472
  return { w, player: player2, seat };
329
473
  }
330
474
  function assertRoom(w) {
331
- if (w && w.seats.size >= game.maxPlayers) throw new import_core2.SuperLineError("WORLD_FULL", "Every seat in this world is held");
475
+ if (w && w.seats.size >= game.maxPlayers) throw new import_core3.SuperLineError("WORLD_FULL", "Every seat in this world is held");
332
476
  }
333
477
  async function bind(w, player2, seat, conn) {
334
478
  const room = context().room(roomOf(w.id));
@@ -345,9 +489,46 @@ function multiplayer(opts) {
345
489
  async function joinAgain(w, player2, seat, conn) {
346
490
  if (seat.conn === conn) return joined(w, player2);
347
491
  await bind(w, player2, seat, conn);
348
- if (!tickRate) sendFrame(w);
492
+ if (!tickRate && !patches) sendFrame(w);
349
493
  return joined(w, player2);
350
494
  }
495
+ async function seed(id) {
496
+ if (!opts.initialState) return game.initialState();
497
+ const state = await opts.initialState(id);
498
+ try {
499
+ if (!isJson(state)) throw new TypeError("not plain JSON");
500
+ return (0, import_core3.validateSync)(game.state, state);
501
+ } catch (error) {
502
+ log.error("initialState returned a state for world {world} that is not valid: {error}", { world: id, error });
503
+ throw new import_core3.SuperLineError("STATE_INVALID", `initialState returned an invalid state for world '${id}'`);
504
+ }
505
+ }
506
+ function create(id) {
507
+ let pending = seeding.get(id);
508
+ if (!pending) {
509
+ pending = seed(id).then((state) => {
510
+ let w = worlds.get(id);
511
+ if (!w)
512
+ worlds.set(
513
+ id,
514
+ w = {
515
+ id,
516
+ state,
517
+ tick: 0,
518
+ seats: /* @__PURE__ */ new Map(),
519
+ acks: {},
520
+ persisted: false,
521
+ updatedAt: 0,
522
+ meter: newMeter(),
523
+ n: 0
524
+ }
525
+ );
526
+ return w;
527
+ }).finally(() => seeding.delete(id));
528
+ seeding.set(id, pending);
529
+ }
530
+ return pending;
531
+ }
351
532
  async function rebuild(ctx) {
352
533
  await ctx.ready;
353
534
  for (const name of ctx.local.rooms) {
@@ -372,7 +553,7 @@ function multiplayer(opts) {
372
553
  await bind(w, player2, seat, conn);
373
554
  bound = true;
374
555
  }
375
- if (w && bound) sendFrame(w);
556
+ if (w && bound) sendFrame(w, true);
376
557
  }
377
558
  }
378
559
  const dropConn = (conn) => {
@@ -394,31 +575,17 @@ function multiplayer(opts) {
394
575
  mpJoin: async ({ world: id }, ctx, conn) => {
395
576
  await rebuilt;
396
577
  if (opts.onlyWorld !== null && id !== opts.onlyWorld)
397
- throw new import_core2.SuperLineError("WRONG_WORLD", `This server hosts only world '${opts.onlyWorld}'`);
578
+ throw new import_core3.SuperLineError("WRONG_WORLD", `This server hosts only world '${opts.onlyWorld}'`);
398
579
  const player2 = conn.principal ?? conn.id;
399
580
  const loaded = await load(id);
400
581
  const held = loaded?.seats.get(player2);
401
582
  if (loaded && held) return await joinAgain(loaded, player2, held, conn);
402
583
  assertRoom(loaded);
403
584
  const verdict = opts.authorize ? await opts.authorize({ joiner: context().describe(conn), player: player2, world: id, exists: loaded !== void 0, ctx }) : false;
404
- if (!verdict) throw new import_core2.SuperLineError("FORBIDDEN", "Join denied");
405
- if (!conn.raw.writable) throw new import_core2.SuperLineError("DISCONNECTED", "The connection closed during authorize");
585
+ if (!verdict) throw new import_core3.SuperLineError("FORBIDDEN", "Join denied");
406
586
  const profile = profileOf(verdict);
407
- let w = worlds.get(id);
408
- if (!w)
409
- worlds.set(
410
- id,
411
- w = {
412
- id,
413
- state: game.initialState(),
414
- tick: 0,
415
- seats: /* @__PURE__ */ new Map(),
416
- acks: {},
417
- persisted: false,
418
- updatedAt: 0,
419
- meter: newMeter()
420
- }
421
- );
587
+ const w = worlds.get(id) ?? await create(id);
588
+ if (!conn.raw.writable) throw new import_core3.SuperLineError("DISCONNECTED", "The connection closed while joining");
422
589
  const raced = w.seats.get(player2);
423
590
  if (raced) return await joinAgain(w, player2, raced, conn);
424
591
  assertRoom(w);
@@ -543,6 +710,29 @@ function multiplayer(opts) {
543
710
  const row = await rows().read(id);
544
711
  if (row) await rows().delete(id);
545
712
  return w !== void 0 || row !== void 0;
713
+ },
714
+ async run(id, fn) {
715
+ await rebuilt;
716
+ const w = await load(id);
717
+ if (!w) return false;
718
+ const outbox = [];
719
+ const copy = structuredClone(w.state);
720
+ fn(copy, worldContext(w, outbox));
721
+ w.state = copy;
722
+ if (!w.clock) sendFrame(w);
723
+ flush(w, outbox);
724
+ if (!w.clock) await save(w);
725
+ return true;
726
+ },
727
+ async removeSeat(id, player2, o) {
728
+ await rebuilt;
729
+ const w = await load(id);
730
+ const seat = w?.seats.get(player2);
731
+ if (!w || !seat) return false;
732
+ if (seat.conn)
733
+ context().toConn(seat.conn.id).emit("mp.closed", { world: id, reason: "removed", ...o?.reason !== void 0 ? { detail: o.reason } : {} });
734
+ await vacate(w, player2, seat);
735
+ return true;
546
736
  }
547
737
  }
548
738
  };
package/dist/server.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ConnDescriptor } from '@super-line/core';
2
2
  import { SuperLinePlugin } from '@super-line/server';
3
- import { PlayerId, AnyWorld, ProfileOf, MultiplayerSurface, WorldServerStats, StateOf } from './index.cjs';
3
+ import { PlayerId, AnyWorld, ProfileOf, MultiplayerSurface, WorldServerStats, WorldContext, StateOf, MessageOf } from './index.cjs';
4
4
 
5
5
  type Awaitable<T> = T | Promise<T>;
6
6
  interface AuthorizeArgs<Ctx> {
@@ -28,6 +28,17 @@ interface MultiplayerServerOptions<W extends AnyWorld, Ctx> {
28
28
  * `mpClock` response and in `worlds.get` / `worlds.list`. Default `false`: nothing is measured.
29
29
  */
30
30
  stats?: boolean;
31
+ /**
32
+ * `'patch'` sends each state frame as a `StatePatch` of what changed since the previous one; a join, a rejoin and
33
+ * a resync still get the whole state. Default `'whole'`: every frame carries the whole state.
34
+ */
35
+ frames?: 'whole' | 'patch';
36
+ /**
37
+ * The state a new world starts from, given its id. Runs only when a join creates the world (no row, not in memory);
38
+ * its result must be plain JSON that fits the state schema, else the join fails and no world is made. Default:
39
+ * the world's own `initialState()`.
40
+ */
41
+ initialState?: (world: string) => Awaitable<StateOf<W>>;
31
42
  }
32
43
  interface WorldInfo<State> {
33
44
  id: string;
@@ -44,16 +55,29 @@ interface WorldInfo<State> {
44
55
  stats?: WorldServerStats;
45
56
  }
46
57
  type WorldSummary = Omit<WorldInfo<unknown>, 'state'>;
47
- interface MultiplayerWorlds<State> {
58
+ interface MultiplayerWorlds<State, Msg = never> {
48
59
  /** The live in-memory world, else its saved row. */
49
60
  get(id: string): Promise<WorldInfo<State> | undefined>;
50
61
  list(): Promise<WorldSummary[]>;
51
62
  /** End a world: its row is deleted and every seated connection gets `mp.closed { reason: 'deleted' }`. */
52
63
  delete(id: string): Promise<boolean>;
64
+ /**
65
+ * Change a world from the server, as a command with no sender: `fn` runs on a copy, so a throw (or `reject()`)
66
+ * leaves the state untouched and rethrows; then the world is saved and framed and its messages sent. Loads the
67
+ * world from its row if it is not live; resolves `false` when it does not exist.
68
+ */
69
+ run(id: string, fn: (state: State, ctx: WorldContext<Msg>) => void): Promise<boolean>;
70
+ /**
71
+ * End a seat now, held or away: `onLeave` runs and others hear `left`. Its connection gets
72
+ * `mp.closed { reason: 'removed', detail: opts.reason }` and stays open. Resolves `false` for an unknown world or seat.
73
+ */
74
+ removeSeat(id: string, player: PlayerId, opts?: {
75
+ reason?: string;
76
+ }): Promise<boolean>;
53
77
  }
54
78
  interface MultiplayerServer<W extends AnyWorld> {
55
79
  plugin: SuperLinePlugin<MultiplayerSurface<W>>;
56
- worlds: MultiplayerWorlds<StateOf<W>>;
80
+ worlds: MultiplayerWorlds<StateOf<W>, MessageOf<W>>;
57
81
  }
58
82
  declare function multiplayer<W extends AnyWorld, Ctx = unknown>(opts: MultiplayerServerOptions<W, Ctx>): MultiplayerServer<W>;
59
83
 
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ConnDescriptor } from '@super-line/core';
2
2
  import { SuperLinePlugin } from '@super-line/server';
3
- import { PlayerId, AnyWorld, ProfileOf, MultiplayerSurface, WorldServerStats, StateOf } from './index.js';
3
+ import { PlayerId, AnyWorld, ProfileOf, MultiplayerSurface, WorldServerStats, WorldContext, StateOf, MessageOf } from './index.js';
4
4
 
5
5
  type Awaitable<T> = T | Promise<T>;
6
6
  interface AuthorizeArgs<Ctx> {
@@ -28,6 +28,17 @@ interface MultiplayerServerOptions<W extends AnyWorld, Ctx> {
28
28
  * `mpClock` response and in `worlds.get` / `worlds.list`. Default `false`: nothing is measured.
29
29
  */
30
30
  stats?: boolean;
31
+ /**
32
+ * `'patch'` sends each state frame as a `StatePatch` of what changed since the previous one; a join, a rejoin and
33
+ * a resync still get the whole state. Default `'whole'`: every frame carries the whole state.
34
+ */
35
+ frames?: 'whole' | 'patch';
36
+ /**
37
+ * The state a new world starts from, given its id. Runs only when a join creates the world (no row, not in memory);
38
+ * its result must be plain JSON that fits the state schema, else the join fails and no world is made. Default:
39
+ * the world's own `initialState()`.
40
+ */
41
+ initialState?: (world: string) => Awaitable<StateOf<W>>;
31
42
  }
32
43
  interface WorldInfo<State> {
33
44
  id: string;
@@ -44,16 +55,29 @@ interface WorldInfo<State> {
44
55
  stats?: WorldServerStats;
45
56
  }
46
57
  type WorldSummary = Omit<WorldInfo<unknown>, 'state'>;
47
- interface MultiplayerWorlds<State> {
58
+ interface MultiplayerWorlds<State, Msg = never> {
48
59
  /** The live in-memory world, else its saved row. */
49
60
  get(id: string): Promise<WorldInfo<State> | undefined>;
50
61
  list(): Promise<WorldSummary[]>;
51
62
  /** End a world: its row is deleted and every seated connection gets `mp.closed { reason: 'deleted' }`. */
52
63
  delete(id: string): Promise<boolean>;
64
+ /**
65
+ * Change a world from the server, as a command with no sender: `fn` runs on a copy, so a throw (or `reject()`)
66
+ * leaves the state untouched and rethrows; then the world is saved and framed and its messages sent. Loads the
67
+ * world from its row if it is not live; resolves `false` when it does not exist.
68
+ */
69
+ run(id: string, fn: (state: State, ctx: WorldContext<Msg>) => void): Promise<boolean>;
70
+ /**
71
+ * End a seat now, held or away: `onLeave` runs and others hear `left`. Its connection gets
72
+ * `mp.closed { reason: 'removed', detail: opts.reason }` and stays open. Resolves `false` for an unknown world or seat.
73
+ */
74
+ removeSeat(id: string, player: PlayerId, opts?: {
75
+ reason?: string;
76
+ }): Promise<boolean>;
53
77
  }
54
78
  interface MultiplayerServer<W extends AnyWorld> {
55
79
  plugin: SuperLinePlugin<MultiplayerSurface<W>>;
56
- worlds: MultiplayerWorlds<StateOf<W>>;
80
+ worlds: MultiplayerWorlds<StateOf<W>, MessageOf<W>>;
57
81
  }
58
82
  declare function multiplayer<W extends AnyWorld, Ctx = unknown>(opts: MultiplayerServerOptions<W, Ctx>): MultiplayerServer<W>;
59
83