castle-web-cli 0.4.243 → 0.4.245

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.
Files changed (41) hide show
  1. package/dist/api.d.ts +1 -0
  2. package/dist/api.js +13 -0
  3. package/dist/contentOriginTiming.d.ts +13 -0
  4. package/dist/contentOriginTiming.js +15 -0
  5. package/dist/imports.js +28 -6
  6. package/dist/index.js +54 -5
  7. package/dist/init.js +1 -1
  8. package/dist/projectState.d.ts +33 -0
  9. package/dist/projectState.js +97 -0
  10. package/dist/serve.d.ts +18 -0
  11. package/dist/serve.js +103 -2
  12. package/dist/serveSecurity.d.ts +105 -3
  13. package/dist/serveSecurity.js +500 -39
  14. package/dist/shell/assets/{index-DulbYIJm.js → index-Bec6LpAv.js} +87 -87
  15. package/dist/shell/index.html +1 -1
  16. package/kits/base/castle.json +1 -1
  17. package/kits/base/sdk/runtime.js +57 -0
  18. package/kits/hub-game/code/client/chrome.js +9 -2
  19. package/kits/hub-game/code/client/hookLayer.js +8 -0
  20. package/kits/hub-game/code/client/padCues.js +2 -0
  21. package/kits/hub-game/code/client/padReadability.js +6 -1
  22. package/kits/hub-game/code/client/signals.js +126 -0
  23. package/kits/hub-game/code/client/state.js +4 -0
  24. package/kits/hub-game/code/server/friendBests.js +8 -2
  25. package/kits/hub-game/code/server/hub.js +31 -4
  26. package/kits/hub-game/code/server/npcs.js +4 -0
  27. package/kits/hub-game/code/server/party.js +3 -0
  28. package/kits/hub-game/code/server/resumePose.js +30 -9
  29. package/kits/hub-game/code/server/signals.js +124 -0
  30. package/kits/hub-game/code/server/writerLease.js +161 -17
  31. package/kits/hub-game/code/systems/hub.js +21 -2
  32. package/kits/hub-game/docs/contract.md +92 -11
  33. package/kits/hub-game/package.json +1 -1
  34. package/kits/hub-game/scripts/test-menu-client.mjs +7 -6
  35. package/kits/hub-game/scripts/test-menu-footer-dom.mjs +94 -0
  36. package/kits/hub-game/scripts/test-pad-cues.mjs +6 -3
  37. package/kits/hub-game/scripts/test-resume-pose.mjs +85 -0
  38. package/kits/hub-game/scripts/test-signals.mjs +412 -0
  39. package/kits/hub-game/scripts/test-writer-lease-server.mjs +108 -4
  40. package/kits/hub-game/scripts/test-writer-lease.mjs +385 -1
  41. package/package.json +2 -2
@@ -0,0 +1,412 @@
1
+ // v1.221: first-input signals cross the real client helper / layer message
2
+ // boundary (contract §4 `signal`, §12 "First-input signals").
3
+ import assert from 'node:assert/strict';
4
+ import { register } from 'node:module';
5
+
6
+ register(`data:text/javascript,${encodeURIComponent(`
7
+ export async function resolve(specifier, context, next) {
8
+ if (specifier === '@imports/castle.multiplayer-3d/code/server/sceneBodies.js') return { url: 'data:text/javascript,export const readScene = () => globalThis.__hubTestActors;', shortCircuit: true };
9
+ if (context.parentURL?.includes('/kits/base/sdk/') && specifier.startsWith('.') && !specifier.endsWith('.js')) return next(specifier + '.js', context);
10
+ return next(specifier, context);
11
+ }
12
+ `)}`);
13
+ const { layer } = await import('../code/server/hub.js');
14
+ const Manifest = await import('../code/server/manifest.js');
15
+ const { makeSignals, signalReplay, walking, WINDOW_MS } = await import('../code/client/signals.js');
16
+ const { collectPadCues } = await import('../code/client/padCues.js');
17
+ const { makePadReadability } = await import('../code/client/padReadability.js');
18
+
19
+ const actors = [
20
+ { id: 'player', components: { Player: {}, Transform: { x: 0, y: 1, z: 0 } } },
21
+ { id: 'door-gems', components: { HubDoor: { id: 'gems', to: 'deck:gems', title: 'Gem Rush' }, Transform: { x: 0, y: 1.4, z: -28 } } },
22
+ { id: 'pad-gems', components: { HubPad: { door: 'gems', radius: 2 }, Transform: { x: 0, y: 0, z: -24 } } },
23
+ { id: 'rowan', components: { HubNpc: { name: 'Rowan' }, Transform: { x: 1, y: 1, z: 0 } } },
24
+ ];
25
+ const players = [
26
+ { playerId: 'p1', userId: '101', username: 'Ada', isAnonymous: false },
27
+ { playerId: 'p2', userId: '102', username: 'Bo', isAnonymous: false },
28
+ ];
29
+ const json = (keys = {}) => ({ server: { maxPlayers: 8 }, hub: { contract: 1, title: 'Town', ...keys } });
30
+ const npcBody = { translation: () => ({ x: 1, y: 1, z: 0 }), setNextKinematicTranslation() {}, setNextKinematicRotation() {} };
31
+ const realNow = Date.now;
32
+ let clock = 1_800_000_000_000;
33
+ Date.now = () => clock;
34
+ function boot(options = {}) {
35
+ const sent = [], heard = [], messages = [], order = [];
36
+ let hub;
37
+ const hooks = {
38
+ ready(ctx) { hub = ctx; },
39
+ message(ctx, player, data) { messages.push([player.playerId, data]); },
40
+ ...(options.hook === null ? {} : { signal: options.hook ?? ((ctx, id, signal) => { heard.push([id, signal]); order.push(`signal:${signal.kind}`); }) }),
41
+ };
42
+ globalThis.__hubTestActors = structuredClone(actors);
43
+ const server = layer(json(options.keys ?? {}), hooks, {}, () => true, () => null, null, { createBody: () => ({ setEnabled() {}, setNextKinematicTranslation() {}, setNextKinematicRotation() {} }), removeActor() {} });
44
+ const session = { sessionId: 'dev', players: [...players], hub: null, send(id, msg) { sent.push([id, structuredClone(msg)]); order.push(`send:${msg.k}`); }, broadcast(msg) { sent.push(['all', structuredClone(msg)]); } };
45
+ const world = { timeMs: 0, scenePath: 'scenes/main.scene', objects: new Map(), bodies: new Map([['rowan', npcBody]]), players: new Map(players.map((p) => [p.playerId, { at: { x: 0, y: 1, z: 0 }, facing: 0, body: { setTranslation() {} } }])) };
46
+ server.sceneFor(session);
47
+ server.ready(world);
48
+ const say = (id, data) => server.message(session, { playerId: id }, data);
49
+ if (options.hello !== false) {
50
+ for (const id of ['p1', 'p2']) {say(id, { k: 'hub-hello', avatar: 0, party: 2 });}
51
+ server.place(world);
52
+ }
53
+ const tick = (ms = 50) => { world.timeMs += ms; server.place(world); server.step(world, []); };
54
+ const arrivedMsg = (id) => sent.filter(([to, m]) => to === id && m.k === 'hub-arrived').at(-1)?.[1];
55
+ // The arrival number this player's client holds now (hub-arrived or a replay).
56
+ const armed = (id) => {
57
+ const m = sent.filter(([to, msg]) => to === id && (msg.k === 'hub-arrived' || msg.k === 'hub-signals')).at(-1)?.[1];
58
+ return m?.k === 'hub-signals' ? m.n : m?.signals;
59
+ };
60
+ const sig = (id, kind, more = {}) => say(id, { k: 'hub-signal', kind, a: armed(id), ...more });
61
+ return { server, session, world, hub, sent, heard, messages, order, say, tick, arrivedMsg, armed, sig };
62
+ }
63
+ const kinds = (heard) => heard.map(([id, s]) => `${id}:${s.kind}${s.door ? `:${s.door}` : ''}${s.npc ? `:${s.npc}` : ''}`);
64
+
65
+ // No manifest key: `signals` stays unknown to the manifest, and a place
66
+ // without the hook sends `hub-arrived` exactly as before.
67
+ assert.ok(Manifest.readManifest(json({ signals: true })).errors.length > 0);
68
+ {
69
+ const on = boot(), off = boot({ hook: null });
70
+ assert.ok(Number.isSafeInteger(on.arrivedMsg('p1').signals));
71
+ assert.notEqual(on.arrivedMsg('p1').signals, on.arrivedMsg('p2').signals);
72
+ assert.deepEqual(off.arrivedMsg('p1'), { k: 'hub-arrived', facing: 0 });
73
+ assert.deepEqual(off.sent.filter(([, m]) => m.k !== 'hub-arrived'), on.sent.filter(([, m]) => m.k !== 'hub-arrived'));
74
+ }
75
+
76
+ // Each client kind at most once per arrival, from a present sender only.
77
+ {
78
+ const r = boot();
79
+ for (let i = 0; i < 3; i++) {
80
+ r.sig('p1', 'move');
81
+ r.sig('p1', 'jump');
82
+ r.sig('p1', 'prompt', { door: 'gems' });
83
+ }
84
+ r.sig('p2', 'jump');
85
+ assert.deepEqual(kinds(r.heard), ['p1:move', 'p1:jump', 'p1:prompt:gems', 'p2:jump']);
86
+ assert.ok(Object.isFrozen(r.heard[0][1]));
87
+ const before = r.heard.length;
88
+ // Kit-only kinds, unknown kinds, a named other player and strangers do nothing.
89
+ for (const data of [{ kind: 'run' }, { kind: 'talk', npc: 'rowan' }, { kind: 'press', door: 'gems' }, { kind: 'pad', door: 'gems' }, { kind: ['move'] }, { kind: null }, {}]) {
90
+ r.say('p2', { k: 'hub-signal', a: r.armed('p2'), ...data });
91
+ }
92
+ r.sig('stranger', 'move');
93
+ r.say('p2', new Proxy({ k: 'hub-signal' }, { get(t, key) { if (key === 'kind') {throw Error('accessor');} return t[key]; } }));
94
+ assert.equal(r.heard.length, before);
95
+ // A bad payload spends its kind: no second try, no door scan.
96
+ r.sig('p2', 'move', { text: 'PRIVATE' }); r.sig('p2', 'move');
97
+ r.sig('p2', 'prompt', { door: 'nope' }); r.sig('p2', 'prompt', { door: 'gems' });
98
+ assert.equal(r.heard.length, before);
99
+ // [2] A rehello, an avatar change or a retained resume is not an arrival.
100
+ r.say('p1', { k: 'hub-hello', avatar: 1, again: true }); r.tick();
101
+ r.say('p1', { k: 'hub-hello', avatar: 0 }); r.tick();
102
+ r.say('p1', { k: 'hub-hello', avatar: 0, resume: true }); r.tick();
103
+ for (const kind of ['move', 'jump']) {r.sig('p1', kind);}
104
+ r.sig('p1', 'prompt', { door: 'gems' });
105
+ assert.equal(r.heard.length, before);
106
+ assert.equal(r.messages.length, 0, 'the kit consumes hub-signal');
107
+ }
108
+
109
+ // [2] The once check comes before any door lookup: repeats never scan doors.
110
+ {
111
+ const r = boot();
112
+ let scans = 0;
113
+ r.sig('p1', 'prompt', { door: 'gems' });
114
+ const fake = new Proxy({ k: 'hub-signal', kind: 'prompt', a: r.armed('p1'), door: 'gems' }, { get(target, key) { if (key === 'door') {scans++;} return target[key]; } });
115
+ for (let i = 0; i < 50; i++) {r.say('p1', fake);}
116
+ assert.equal(scans, 0);
117
+ assert.equal(r.heard.length, 1);
118
+ }
119
+
120
+ // Only within 120 s of the arrival; a new arrival starts again.
121
+ {
122
+ const r = boot();
123
+ clock += WINDOW_MS - 1;
124
+ r.sig('p1', 'move');
125
+ clock += 1;
126
+ r.sig('p1', 'jump');
127
+ r.sig('p2', 'move');
128
+ assert.deepEqual(kinds(r.heard), ['p1:move']);
129
+ // Leaving and arriving again is a new arrival with a new number.
130
+ const was = r.arrivedMsg('p1').signals;
131
+ const body = r.world.players.get('p1');
132
+ r.session.players = r.session.players.filter((p) => p.playerId !== 'p1');
133
+ r.world.players.delete('p1');
134
+ r.tick();
135
+ r.session.players = [...players];
136
+ r.world.players.set('p1', body);
137
+ r.say('p1', { k: 'hub-hello', avatar: 0, party: 1 }); r.tick(); r.tick(500);
138
+ const now = r.arrivedMsg('p1')?.signals;
139
+ assert.ok(Number.isSafeInteger(now) && now !== was, 'a fresh arrival is numbered again');
140
+ r.sig('p1', 'jump');
141
+ assert.deepEqual(kinds(r.heard), ['p1:move', 'p1:jump']);
142
+ }
143
+
144
+ // [round 2] A signal armed with an earlier arrival's number is dropped before
145
+ // it spends anything; the current arrival's own is taken.
146
+ {
147
+ const r = boot();
148
+ const old = r.armed('p1');
149
+ const body = r.world.players.get('p1');
150
+ r.session.players = r.session.players.filter((p) => p.playerId !== 'p1');
151
+ r.world.players.delete('p1');
152
+ r.tick();
153
+ r.session.players = [...players];
154
+ r.world.players.set('p1', body);
155
+ r.say('p1', { k: 'hub-hello', avatar: 0, party: 1 }); r.tick(); r.tick(500);
156
+ const now = r.armed('p1');
157
+ assert.notEqual(now, old);
158
+ r.say('p1', { k: 'hub-signal', kind: 'jump', a: old }); // in flight from the old record
159
+ r.say('p1', { k: 'hub-signal', kind: 'jump' }); // no number at all
160
+ r.say('p1', { k: 'hub-signal', kind: 'jump', a: String(now) });
161
+ assert.equal(r.heard.length, 0);
162
+ r.say('p1', { k: 'hub-signal', kind: 'jump', a: now });
163
+ assert.deepEqual(kinds(r.heard), ['p1:jump']);
164
+ }
165
+
166
+ // [round 2] A reloaded page on a retained body is told the same arrival, what
167
+ // is left of its window and what was spent; it says only what is left, and
168
+ // neither the window nor the allowance starts again.
169
+ {
170
+ const r = boot();
171
+ const n = r.armed('p1');
172
+ r.sig('p1', 'move');
173
+ clock += 30_000;
174
+ r.say('p1', { k: 'hub-hello', avatar: 0, party: 1 }); r.tick(); // a reload: a fresh page, same body
175
+ const replay = r.sent.filter(([to, m]) => to === 'p1' && m.k === 'hub-signals').at(-1)?.[1];
176
+ assert.deepEqual(replay, { k: 'hub-signals', n, left: WINDOW_MS - 30_000, sent: ['move'] });
177
+ assert.equal(r.arrivedMsg('p1').signals, n, 'no new arrival');
178
+ // The reloaded client, armed from the replay.
179
+ const page = makeSignals();
180
+ const arrival = signalReplay(replay, 5000);
181
+ assert.deepEqual(arrival, { n, at: 5000 - 30_000, sent: ['move'] });
182
+ page.frame({ send: (data) => r.say('p1', data) }, arrival, 5000, { keys: new Set(['KeyW', 'Space']), stick: null, prompt: null });
183
+ assert.deepEqual(kinds(r.heard), ['p1:move', 'p1:jump'], 'only what was left');
184
+ // A resume hello replays too, with the spent kinds; the window is not renewed.
185
+ clock += 89_999;
186
+ r.say('p1', { k: 'hub-hello', avatar: 0, resume: true }); r.tick();
187
+ const again = r.sent.filter(([to, m]) => to === 'p1' && m.k === 'hub-signals').at(-1)[1];
188
+ assert.deepEqual(again, { k: 'hub-signals', n, left: 1, sent: ['move', 'jump'] });
189
+ clock += 1;
190
+ r.sig('p1', 'prompt', { door: 'gems' });
191
+ assert.equal(r.heard.length, 2, 'the window ends when it always would');
192
+ // Past the window, or with everything spent, nothing is replayed.
193
+ const count = r.sent.filter(([, m]) => m.k === 'hub-signals').length;
194
+ r.say('p1', { k: 'hub-hello', avatar: 0, resume: true }); r.tick();
195
+ r.say('p2', { k: 'hub-hello', avatar: 0, resume: true }); r.tick();
196
+ assert.equal(r.sent.filter(([, m]) => m.k === 'hub-signals').length, count);
197
+ const full = boot();
198
+ for (const kind of ['move', 'jump']) {full.sig('p1', kind);}
199
+ full.sig('p1', 'prompt', { door: 'gems' });
200
+ full.say('p1', { k: 'hub-hello', avatar: 0, resume: true }); full.tick();
201
+ assert.equal(full.sent.some(([, m]) => m.k === 'hub-signals'), false);
202
+ // An avatar change is not a reload.
203
+ const avatar = boot();
204
+ avatar.say('p1', { k: 'hub-hello', avatar: 1, again: true }); avatar.tick();
205
+ assert.equal(avatar.sent.some(([, m]) => m.k === 'hub-signals'), false);
206
+ // Malformed replays arm nothing.
207
+ for (const bad of [null, {}, { n: 1, left: 0, sent: [] }, { n: 1, left: WINDOW_MS + 1, sent: [] }, { n: '1', left: 5, sent: [] }, { n: 1, left: 5 }]) {
208
+ assert.equal(signalReplay(bad, 0), null);
209
+ }
210
+ assert.deepEqual(signalReplay({ n: 1, left: 5, sent: ['jump', 'talk', 7] }, 0).sent, ['jump']);
211
+ }
212
+
213
+ // Before arrival nothing is heard.
214
+ {
215
+ const r = boot({ hello: false });
216
+ r.sig('p1', 'move');
217
+ r.say('p1', { k: 'hub-hello', avatar: 0, party: 1 });
218
+ r.sig('p1', 'move');
219
+ assert.equal(r.heard.length, 0);
220
+ r.tick();
221
+ r.sig('p1', 'move');
222
+ assert.deepEqual(kinds(r.heard), ['p1:move']);
223
+ }
224
+
225
+ // press after the jump's own work, from a door jump and a party Go / Go-yes;
226
+ // pad when newly counted; talk when a conversation opens.
227
+ {
228
+ const r = boot();
229
+ r.say('p1', { k: 'hub-door-jump', door: 'gems' });
230
+ assert.deepEqual(r.order.slice(-2), ['send:hub-jumped', 'signal:press'], 'the hook runs after the jump');
231
+ r.say('p1', { k: 'hub-door-jump', door: 'gems' }); // within a second: refused, so silent
232
+ r.say('p2', { k: 'hub-door-jump', door: 'nope' });
233
+ r.hub.pad('gems', ['p1']);
234
+ r.hub.pad('gems', ['p1', 'p2', 'ghost', 7]);
235
+ r.hub.pad('gems', ['p2']);
236
+ r.hub.pad('gems', ['p1', 'p2']);
237
+ r.say('p2', { k: 'hub-npc-open', npc: 'rowan' });
238
+ r.say('p2', { k: 'hub-npc-open', npc: 'nobody' });
239
+ assert.deepEqual(kinds(r.heard), ['p1:press:gems', 'p1:pad:gems', 'p2:pad:gems', 'p1:pad:gems', 'p2:talk:rowan']);
240
+ }
241
+ {
242
+ const r = boot();
243
+ const party = (id, data) => r.say(id, { k: 'hub-party', ...data });
244
+ party('p1', { op: 'invite', player: 'p2' }); r.tick();
245
+ party('p2', { op: 'accept', from: 'p1' }); r.tick();
246
+ party('p1', { op: 'go', door: 'gems' }); r.tick();
247
+ const proposal = r.sent.filter(([to, m]) => to === 'p2' && m.k === 'hub-party').at(-1)[1].proposal;
248
+ party('p2', { op: 'go-yes', id: proposal.id });
249
+ assert.deepEqual(kinds(r.heard), ['p1:press:gems', 'p2:press:gems']);
250
+ }
251
+
252
+ // A throwing or rejecting hook is logged once and never reaches the kit.
253
+ {
254
+ const warns = [];
255
+ const warn = console.warn;
256
+ console.warn = (line) => warns.push(String(line));
257
+ try {
258
+ const r = boot({ hook() { throw Error('PRIVATE'); } });
259
+ assert.doesNotThrow(() => r.sig('p1', 'move'));
260
+ assert.doesNotThrow(() => r.say('p1', { k: 'hub-door-jump', door: 'gems' }));
261
+ assert.doesNotThrow(() => r.hub.pad('gems', ['p1']));
262
+ assert.doesNotThrow(() => r.say('p2', { k: 'hub-npc-open', npc: 'rowan' }));
263
+ assert.ok(r.sent.some(([id, msg]) => id === 'p2' && msg.k === 'hub-npc' && msg.open === true), 'the conversation still opens');
264
+ assert.ok(r.sent.some(([id, msg]) => id === 'p1' && msg.k === 'hub-jumped'), 'the jump still happens');
265
+ const rejecting = boot({ hook: () => Promise.reject(Error('PRIVATE')) });
266
+ rejecting.sig('p1', 'jump');
267
+ await new Promise((resolve) => setTimeout(resolve, 0));
268
+ assert.equal(warns.filter((line) => line.includes('signal hook failed')).length, 2, 'once per place');
269
+ assert.ok(warns.every((line) => !line.includes('PRIVATE')));
270
+ } finally {
271
+ console.warn = warn;
272
+ }
273
+ }
274
+
275
+ // Without the hook: nothing is kept or called, and hub-signal is an unknown message.
276
+ {
277
+ const off = boot({ hook: null });
278
+ off.sig('p1', 'move');
279
+ off.say('p1', { k: 'hub-door-jump', door: 'gems' });
280
+ off.hub.pad('gems', ['p1']);
281
+ off.say('p2', { k: 'hub-npc-open', npc: 'rowan' });
282
+ assert.deepEqual(off.messages.map(([id, m]) => [id, m.k, m.kind]), [['p1', 'hub-signal', 'move']]);
283
+ assert.equal(off.sent.some(([, m]) => m.k === 'hub-signals'), false);
284
+ }
285
+
286
+ // The client helper.
287
+ {
288
+ assert.equal(walking(new Set(['KeyW']), null), true);
289
+ assert.equal(walking(new Set(['Space']), null), false);
290
+ assert.equal(walking(null, { active: true, x: 0.1, y: 0.1 }), false);
291
+ assert.equal(walking(null, { active: true, x: 0, y: -0.2 }), true);
292
+ assert.equal(walking(null, { active: false, x: 0, y: -1 }), false);
293
+
294
+ const out = [];
295
+ let state = 'connected', statusReads = 0;
296
+ const net = { send: (data) => out.push(data), status: () => { statusReads++; return { state }; } };
297
+ const keys = new Set();
298
+ let pending = false;
299
+ const stick = { active: false, x: 0, y: 0, consumeJump() { const had = pending; pending = false; return had; } };
300
+ const original = stick.consumeJump;
301
+ const s = makeSignals();
302
+ let t = 1000;
303
+ let arrival = { n: 1, at: t };
304
+ const frame = (o = {}) => s.frame(o.net ?? net, Object.hasOwn(o, 'arrival') ? o.arrival : arrival, o.now ?? t, { keys, stick, prompt: null, ...o });
305
+ // (b) No arrival number (no hook): nothing wrapped, nothing sent.
306
+ keys.add('KeyW');
307
+ frame({ arrival: null, prompt: 'gems' });
308
+ assert.equal(stick.consumeJump, original);
309
+ assert.equal(out.length, 0);
310
+ // [3] With the socket down nothing is marked sent; it goes once it is up.
311
+ state = 'reconnecting'; frame();
312
+ assert.equal(out.length, 0);
313
+ state = 'connected'; frame(); frame();
314
+ assert.deepEqual(out, [{ k: 'hub-signal', kind: 'move', a: 1 }]);
315
+ // A tap the Player behavior takes is a jump, once.
316
+ pending = true;
317
+ assert.equal(stick.consumeJump(), true, 'the wrapper hands the tap on');
318
+ frame(); keys.add('Space'); frame();
319
+ assert.deepEqual(out.slice(1), [{ k: 'hub-signal', kind: 'jump', a: 1 }]);
320
+ // (a) The first door prompt only, once; nothing is collected after it.
321
+ assert.equal(s.wantsPrompt(arrival), true);
322
+ frame({ prompt: 'gems' }); frame({ prompt: 'race' }); frame({ prompt: 'gems' });
323
+ assert.deepEqual(out.slice(2), [{ k: 'hub-signal', kind: 'prompt', a: 1, door: 'gems' }]);
324
+ assert.equal(s.wantsPrompt(arrival), false);
325
+ // (a) All three sent: a frame costs nothing, not even a status read.
326
+ const reads = statusReads;
327
+ for (let i = 0; i < 100; i++) {frame({ prompt: 'gems' });}
328
+ assert.equal(statusReads, reads);
329
+ assert.equal(out.length, 3);
330
+ // [3] A reconnect that is not an arrival (same record) says nothing again;
331
+ // only a new arrival number does.
332
+ frame({ arrival });
333
+ assert.equal(out.length, 3);
334
+ arrival = { n: 2, at: t };
335
+ keys.clear();
336
+ frame();
337
+ assert.equal(out.length, 3, 'nothing pressed yet for the new arrival');
338
+ keys.add('ArrowUp'); frame();
339
+ assert.deepEqual(out.at(-1), { k: 'hub-signal', kind: 'move', a: 2 });
340
+ // (a) Past 120 s nothing is said, and the check goes quiet.
341
+ keys.add('Space');
342
+ frame({ now: t + WINDOW_MS });
343
+ assert.equal(out.length, 4);
344
+ const quiet = statusReads;
345
+ frame({ now: t + WINDOW_MS + 5, prompt: 'gems' });
346
+ assert.equal(statusReads, quiet);
347
+ assert.equal(out.length, 4);
348
+ // Nothing to say: no status read either.
349
+ const s4 = makeSignals();
350
+ let reads4 = 0;
351
+ const net4 = { send() { throw Error('nothing to send'); }, status: () => { reads4++; return { state: 'connected' }; } };
352
+ for (let i = 0; i < 10; i++) {s4.frame(net4, { n: 9, at: t }, t, { keys: new Set(), stick: null, prompt: null });}
353
+ assert.equal(reads4, 0);
354
+ // Another wrapper over ours (Act's) is wrapped again: its own presses count.
355
+ const s2 = makeSignals();
356
+ const acted = { active: false, x: 0, y: 0, consumeJump: () => false };
357
+ const out2 = [];
358
+ const net2 = { send: (data) => out2.push(data) };
359
+ const a2 = { n: 3, at: t };
360
+ s2.frame(net2, a2, t, { keys: new Set(), stick: acted, prompt: null });
361
+ let actJump = false;
362
+ const inner = acted.consumeJump;
363
+ acted.consumeJump = () => { const own = actJump; actJump = false; return inner() || own; };
364
+ s2.frame(net2, a2, t, { keys: new Set(), stick: acted, prompt: null });
365
+ actJump = true; acted.consumeJump();
366
+ s2.frame(net2, a2, t, { keys: new Set(), stick: acted, prompt: null });
367
+ assert.deepEqual(out2, [{ k: 'hub-signal', kind: 'jump', a: 3 }]);
368
+ // Keys typed into a text field are words, not a walk or a jump.
369
+ const field = { closest: (sel) => sel.includes('input') ? field : null };
370
+ const typingDoc = { activeElement: field };
371
+ const s3 = makeSignals(typingDoc);
372
+ const out3 = [];
373
+ const net3 = { send: (data) => out3.push(data) };
374
+ const a3 = { n: 4, at: t };
375
+ s3.frame(net3, a3, t, { keys: new Set(['KeyW', 'Space']), stick: null, prompt: null });
376
+ assert.deepEqual(out3, []);
377
+ typingDoc.activeElement = null;
378
+ s3.frame(net3, a3, t, { keys: new Set(['KeyW', 'Space']), stick: null, prompt: null });
379
+ assert.deepEqual(out3, [{ k: 'hub-signal', kind: 'move', a: 4 }, { k: 'hub-signal', kind: 'jump', a: 4 }]);
380
+ // The client's messages are the server's: a real layer hears them.
381
+ const r = boot();
382
+ const toLayer = makeSignals();
383
+ const layerNet = { send: (data) => r.say('p1', data) };
384
+ toLayer.frame(layerNet, { n: r.arrivedMsg('p1').signals, at: t }, t, { keys: new Set(['ArrowUp', 'Space']), stick: null, prompt: 'gems' });
385
+ assert.deepEqual(kinds(r.heard), ['p1:move', 'p1:jump', 'p1:prompt:gems']);
386
+ }
387
+
388
+ // A door pad's caption names its door; an explicit cue names none.
389
+ {
390
+ const cues = collectPadCues([
391
+ { id: 'door-gems', components: { HubDoor: { id: 'gems', title: 'Gem Rush' } } },
392
+ { id: 'pad-gems', components: { HubPad: { door: 'gems', radius: 2 }, Transform: { x: 0, z: 0 } } },
393
+ { id: 'cue', components: { HubPadCue: { radius: 1, title: 'Quick' }, Transform: { x: 10, z: 0 } } },
394
+ ]);
395
+ assert.deepEqual(cues.map((cue) => cue.doorId), ['gems', undefined]);
396
+ // The door counts only when chrome says it drew the caption visibly.
397
+ let shows = true;
398
+ const readable = makePadReadability({ hubPadContext: true }, { chrome: { setPadContext: (item) => Boolean(item) && shows, clearPadContext() {} } });
399
+ const actorsNow = [
400
+ { id: 'door-gems', components: { HubDoor: { id: 'gems', title: 'Gem Rush' } } },
401
+ { id: 'pad-gems', components: { HubPad: { door: 'gems', radius: 2 }, Transform: { x: 0, z: 0 } } },
402
+ ];
403
+ assert.equal(readable.frame(actorsNow, new Set(), { x: 0, z: 2.5 }, false), 'gems');
404
+ assert.equal(readable.frame(actorsNow, new Set(), { x: 0, z: 2.5 }, true), null, 'not while traveling');
405
+ assert.equal(readable.frame(actorsNow, new Set(), { x: 0, z: 2.5 }, false, true), null, 'not while the caption is blocked');
406
+ assert.equal(readable.frame(actorsNow, new Set(), { x: 0, z: 30 }, false), null);
407
+ shows = false;
408
+ assert.equal(readable.frame(actorsNow, new Set(), { x: 0, z: 2.5 }, false), null, 'a caption chrome hid or could not place is not a prompt');
409
+ }
410
+
411
+ Date.now = realNow;
412
+ console.log('signals: ok');
@@ -47,7 +47,10 @@ function connect(s, id, transport = true) {
47
47
  if (transport) s.server.transportJoin?.(s.session, player(id));
48
48
  }
49
49
 
50
- async function retainedReplacement(name, hub, liveElsewhere, entryPath) {
50
+ // knownLost false: the place never learned of the other claim before the
51
+ // player came back alone (no write failed here), so the fresh arrival finds
52
+ // it out by revalidating, and reclaims without the notice.
53
+ async function retainedReplacement(name, hub, liveElsewhere, entryPath, knownLost = true) {
51
54
  const events = [], state = new Map(), pending = [], loads = [], leaves = [], arrivalState = [];
52
55
  const a = boot(`${name}-old`, true, '101', false, { hub, hooks: {
53
56
  arrive(ctx, group) {
@@ -71,7 +74,7 @@ async function retainedReplacement(name, hub, liveElsewhere, entryPath) {
71
74
  assert.ok(state.has('101'), 'the old visits own authored state');
72
75
  const b = boot(`${name}-other`);
73
76
  await b.ctx.saves.deck('101').set({ progress: 42 });
74
- await assert.rejects(a.ctx.saves.fence('101'), { code: 'CAULDRON_STORAGE_WRITER_LOST' });
77
+ if (knownLost) await assert.rejects(a.ctx.saves.fence('101'), { code: 'CAULDRON_STORAGE_WRITER_LOST' });
75
78
  drop(a, 'p1'); drop(a, 'p2'); a.tick();
76
79
  assert.ok(!events.some(e => e.startsWith('leave:')), 'both dropped visits are retained');
77
80
  if (!liveElsewhere) await b.server.shutdown();
@@ -83,8 +86,12 @@ async function retainedReplacement(name, hub, liveElsewhere, entryPath) {
83
86
  if (entryPath === 'tick') a.tick();
84
87
  a.hello('fresh'); await flush(); a.tick(2000); a.tick(300);
85
88
  await Promise.all(pending);
86
- assert.deepEqual(events, ['leave:p1', 'leave:p2', 'claim', 'arrive:fresh'], `${entryPath}: cleanup and reopening precede arrival`);
87
- assert.deepEqual(leaves, [['p1', true], ['p2', true]], 'leave hooks ran under the old lost lease');
89
+ if (knownLost) {
90
+ assert.deepEqual(events, ['leave:p1', 'leave:p2', 'claim', 'arrive:fresh'], `${entryPath}: cleanup and reopening precede arrival`);
91
+ } else {
92
+ assert.deepEqual(events.filter(e => e !== 'arrive:fresh'), ['leave:p1', 'leave:p2', 'claim'], `${entryPath}: cleanup precedes the revalidated claim`);
93
+ }
94
+ assert.deepEqual(leaves, [['p1', knownLost], ['p2', knownLost]], 'leave hooks ran under the old lease');
88
95
  assert.deepEqual(arrivalState.at(-1), ['fresh', false], 'leave cleared authored per-account state before arrival');
89
96
  assert.deepEqual(loads.at(-1), ['fresh', 42], 'fresh arrival loads the other instance\'s saves');
90
97
  assert.equal(a.calls.claim.length, 2);
@@ -150,6 +157,96 @@ async function replacementProgress(name, hub, entryPath) {
150
157
  assert.equal(a.ctx.saves.lost('101'), false);
151
158
  await a.server.shutdown();
152
159
  }
160
+ // A fenced Town must not move the durable resume pose revision: its end and
161
+ // a same-playerId resume's take go through the writer lease.
162
+ async function poseFenced() {
163
+ const rows = new Map(), revisions = new Map(), sent = [];
164
+ const deck = (name) => {
165
+ const raw = fixture.root(`${name}-pose-deck`).storage.deck;
166
+ return { ...raw,
167
+ async snapshot({ prefix }) {
168
+ return { access: 'x', targets: [{ revision: revisions.get(prefix) ?? null,
169
+ rows: Object.fromEntries([...rows].filter(([k]) => k.startsWith(prefix))) }] };
170
+ },
171
+ async transaction({ changes }) {
172
+ const { prefix, expectedRevision, replace } = changes[0];
173
+ sent.push([name, prefix]);
174
+ if ((revisions.get(prefix) ?? null) !== expectedRevision) throw Object.assign(Error('conflict'), { code: 'SAVE_CONFLICT' });
175
+ for (const k of [...rows.keys()]) if (k.startsWith(prefix)) rows.delete(k);
176
+ for (const [k, v] of Object.entries(replace)) rows.set(k, v);
177
+ const revision = `r${sent.length}`;
178
+ revisions.set(prefix, revision);
179
+ return { revisions: [{ revision }] };
180
+ } };
181
+ };
182
+ const a = boot('pose-old', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a') } });
183
+ await flush(); a.tick(2000); a.tick(300); await flush();
184
+ assert.ok(sent.some(([n]) => n === 'a'), 'arrival takes the pose lease');
185
+ const other = boot('pose-other', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('b') } });
186
+ await flush(); other.tick(2000); other.tick(300); await flush();
187
+ await assert.rejects(a.ctx.saves.fence('101'), { code: 'CAULDRON_STORAGE_WRITER_LOST' });
188
+ const before = sent.filter(([n]) => n === 'a').length;
189
+ drop(a, 'p1'); a.tick(); await flush();
190
+ connect(a, 'p1'); a.hello('p1', { resume: true }); a.tick(); await flush();
191
+ assert.equal(sent.filter(([n]) => n === 'a').length, before, 'a fenced Town sends no pose transaction');
192
+ await a.server.shutdown(); await flush();
193
+ assert.equal(sent.filter(([n]) => n === 'a').length, before, 'nor at shutdown');
194
+ await other.server.shutdown();
195
+ assert.ok(sent.filter(([n]) => n === 'b').length > 1, 'the current writer still saves its pose');
196
+ }
197
+
198
+ // A lone quick return (a new player id before any tick saw the old socket
199
+ // go): the held visits end their pose under their claim, and the arrival's
200
+ // take, made while the claim revalidates, follows it (or its replacement).
201
+ async function poseQuickReturn(taken) {
202
+ const rows = new Map(), revisions = new Map(), results = [];
203
+ const deck = (name) => {
204
+ const raw = fixture.root(`${name}-quick-deck`).storage.deck;
205
+ return { ...raw,
206
+ async snapshot({ prefix }) {
207
+ return { access: 'x', targets: [{ revision: revisions.get(prefix) ?? null,
208
+ rows: Object.fromEntries([...rows].filter(([k]) => k.startsWith(prefix))) }] };
209
+ },
210
+ async transaction({ changes }) {
211
+ const { prefix, expectedRevision, replace } = changes[0];
212
+ const ok = (revisions.get(prefix) ?? null) === expectedRevision;
213
+ results.push([name, Object.keys(replace).length ? 'end' : 'take', ok]);
214
+ if (!ok) throw Object.assign(Error('conflict'), { code: 'SAVE_CONFLICT' });
215
+ for (const k of [...rows.keys()]) if (k.startsWith(prefix)) rows.delete(k);
216
+ for (const [k, v] of Object.entries(replace)) rows.set(k, v);
217
+ const revision = `r${results.length}`;
218
+ revisions.set(prefix, revision);
219
+ return { revisions: [{ revision }] };
220
+ } };
221
+ };
222
+ const a = boot(`quick-${taken}`, true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a') } });
223
+ for (let i = 0; i < 3; i++) { await flush(); await new Promise(r => setImmediate(r)); a.tick(2000); a.tick(300); }
224
+ if (taken) {
225
+ const other = boot(`quick-${taken}-other`);
226
+ await other.ctx.saves.ready('101');
227
+ await other.server.shutdown();
228
+ }
229
+ results.length = 0;
230
+ drop(a, 'p1'); drop(a, 'p2');
231
+ connect(a, 'fresh'); a.hello('fresh');
232
+ for (let i = 0; i < 4; i++) { await flush(); await new Promise(r => setImmediate(r)); }
233
+ a.tick(2000); a.tick(300);
234
+ for (let i = 0; i < 4; i++) { await flush(); await new Promise(r => setImmediate(r)); }
235
+ const ends = results.filter(([, kind]) => kind === 'end');
236
+ if (taken) {
237
+ assert.equal(ends.length, 0, 'the held visits\' pose ends were refused by their taken claim');
238
+ } else {
239
+ // Two visits of one account: only the later take's revision can end it.
240
+ assert.ok(ends.some(([, , ok]) => ok), 'the held pose was ended before it was forgotten');
241
+ }
242
+ assert.ok(results.some(([, kind, ok]) => kind === 'take' && ok), 'the arrival took the pose lease');
243
+ assert.equal(a.ctx.saves.lost('101'), false);
244
+ results.length = 0;
245
+ drop(a, 'fresh'); a.tick(); await flush(); await new Promise(r => setImmediate(r));
246
+ assert.deepEqual(results.filter(([, kind]) => kind === 'end').map(([, , ok]) => ok), [true], 'the arrival can save its pose on departure');
247
+ await a.server.shutdown();
248
+ }
249
+
153
250
  const a = boot('a'), b = boot('b'), disabled = boot('off', false);
154
251
  const guest = boot('guest', true, 'dev-guest-1', true), anonymous = boot('anon', true, '102', true);
155
252
  try {
@@ -189,6 +286,11 @@ try {
189
286
  assert.equal(a.ctx.saves.lost('101'), false);
190
287
  assert.ok(!a.sent.some(([to, msg]) => to === 'p1' && msg.k === 'hub-hud' && msg.hud?.text === NOTICE), 'a fresh visit is not warned');
191
288
  console.log('writer lease hub: opt-in, visits, persistent HUD, reconnect and transport rejoin passed');
289
+ await poseFenced();
290
+ await poseQuickReturn(false);
291
+ await poseQuickReturn(true);
292
+ console.log('writer lease hub: a quick lone return keeps the held pose and the arrival keeps its pose lease');
293
+ console.log('writer lease hub: a fenced Town leaves the durable resume pose to the current writer');
192
294
 
193
295
  for (const [mode, hub] of [['pose', { resumePose: true }], ['keep', { resume: { keep: true }, result: { score: { unit: 's', better: 'lower' } } }]]) {
194
296
  for (const liveElsewhere of [false, true]) {
@@ -196,6 +298,8 @@ try {
196
298
  const name = `${mode}-${liveElsewhere ? 'C' : 'D'}-${path}`;
197
299
  await retainedReplacement(name, hub, liveElsewhere, path);
198
300
  console.log(`writer lease hub: ${name} held visits forgotten, claim reopened, arrival reload and saves passed`);
301
+ await retainedReplacement(`${name}-unknown`, hub, liveElsewhere, path, false);
302
+ console.log(`writer lease hub: ${name} lone return to a claim taken elsewhere revalidates and saves without the notice`);
199
303
  }
200
304
  }
201
305
  for (const path of ['hello', 'transport', 'tick']) {