castle-web-cli 0.4.237 → 0.4.238

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 (216) hide show
  1. package/dist/bundle.d.ts +24 -0
  2. package/dist/bundle.js +447 -4
  3. package/dist/bundleLatin1.d.ts +6 -0
  4. package/dist/bundleLatin1.js +333 -0
  5. package/dist/castle-host/host.d.ts +10 -1
  6. package/dist/castle-host/host.js +78 -9
  7. package/dist/castleJson.d.ts +2 -0
  8. package/dist/castleJson.js +1 -0
  9. package/dist/deckExports.d.ts +35 -0
  10. package/dist/deckExports.js +365 -0
  11. package/dist/importCheckHook.d.ts +1 -0
  12. package/dist/importCheckHook.js +1 -1
  13. package/dist/index.js +5 -0
  14. package/dist/init.js +2 -1
  15. package/dist/save-deck.js +4 -0
  16. package/kits/base/castle.json +1 -1
  17. package/kits/base/sdk/README.md +47 -0
  18. package/kits/base/sdk/castle.d.ts +3 -1
  19. package/kits/base/sdk/castle.js +1 -0
  20. package/kits/base/sdk/commands.d.ts +25 -1
  21. package/kits/base/sdk/commands.js +29 -1
  22. package/kits/base/sdk/hub.d.ts +17 -0
  23. package/kits/base/sdk/hub.js +33 -9
  24. package/kits/base/sdk/localCache.d.ts +27 -0
  25. package/kits/base/sdk/localCache.js +115 -0
  26. package/kits/base/sdk/localCacheStore.d.ts +15 -0
  27. package/kits/base/sdk/localCacheStore.js +358 -0
  28. package/kits/base/sdk/transport.d.ts +1 -0
  29. package/kits/base/sdk/transport.js +4 -5
  30. package/kits/hub-game/CLAUDE.md +22 -2
  31. package/kits/hub-game/castle.json +4 -1
  32. package/kits/hub-game/code/client/act.js +66 -91
  33. package/kits/hub-game/code/client/actCore.js +134 -0
  34. package/kits/hub-game/code/client/car.js +35 -0
  35. package/kits/hub-game/code/client/chrome.js +207 -381
  36. package/kits/hub-game/code/client/crowdNames.js +2 -2
  37. package/kits/hub-game/code/client/emoteWheel.js +109 -0
  38. package/kits/hub-game/code/client/hats.js +2 -0
  39. package/kits/hub-game/code/client/hookLayer.js +99 -48
  40. package/kits/hub-game/code/client/hostGo.js +77 -0
  41. package/kits/hub-game/code/client/hubControls.js +125 -0
  42. package/kits/hub-game/code/client/hubEntry.js +187 -0
  43. package/kits/hub-game/code/client/hudSurface.js +148 -0
  44. package/kits/hub-game/code/client/hudTree.js +96 -0
  45. package/kits/hub-game/code/client/idle.js +59 -13
  46. package/kits/hub-game/code/client/invites.js +13 -4
  47. package/kits/hub-game/code/client/menuIcons.js +8 -0
  48. package/kits/hub-game/code/client/noTrips.js +38 -0
  49. package/kits/hub-game/code/client/qualityEntry.js +6 -1
  50. package/kits/hub-game/code/client/rehello.js +3 -1
  51. package/kits/hub-game/code/client/riders.js +26 -0
  52. package/kits/hub-game/code/client/role.js +79 -0
  53. package/kits/hub-game/code/client/safeLayout.js +32 -3
  54. package/kits/hub-game/code/client/sound.js +10 -3
  55. package/kits/hub-game/code/client/soundscape.js +2 -2
  56. package/kits/hub-game/code/client/soundscapeAmbience.js +38 -8
  57. package/kits/hub-game/code/client/soundscapeBaked.js +24 -5
  58. package/kits/hub-game/code/client/soundscapeCues.js +2 -1
  59. package/kits/hub-game/code/client/state.js +19 -0
  60. package/kits/hub-game/code/client/stuck.js +2 -1
  61. package/kits/hub-game/code/client/talkSurface.js +178 -0
  62. package/kits/hub-game/code/client/talkTree.js +238 -0
  63. package/kits/hub-game/code/client/tiers.js +8 -5
  64. package/kits/hub-game/code/client/uiDom.js +600 -0
  65. package/kits/hub-game/code/client/uiTree.js +359 -0
  66. package/kits/hub-game/code/client/vehicle.js +154 -0
  67. package/kits/hub-game/code/client/wear.js +27 -5
  68. package/kits/hub-game/code/client/worldLabels.js +3 -2
  69. package/kits/hub-game/code/client/yours.js +10 -3
  70. package/kits/hub-game/code/server/actors.js +4 -3
  71. package/kits/hub-game/code/server/analytics.js +56 -6
  72. package/kits/hub-game/code/server/decor.js +56 -16
  73. package/kits/hub-game/code/server/hub.js +258 -46
  74. package/kits/hub-game/code/server/idle.js +118 -5
  75. package/kits/hub-game/code/server/manifest.js +46 -4
  76. package/kits/hub-game/code/server/npcs.js +4 -2
  77. package/kits/hub-game/code/server/players.js +3 -0
  78. package/kits/hub-game/code/server/role.js +142 -0
  79. package/kits/hub-game/code/server/standing.js +6 -4
  80. package/kits/hub-game/code/server/vehicle.js +126 -0
  81. package/kits/hub-game/code/shared/car.js +52 -0
  82. package/kits/hub-game/code/shared/deckFlags.js +34 -0
  83. package/kits/hub-game/code/shared/deviceClass.js +39 -0
  84. package/kits/hub-game/code/shared/expression.js +9 -0
  85. package/kits/hub-game/code/systems/hub.js +272 -84
  86. package/kits/hub-game/docs/analytics.md +11 -2
  87. package/kits/hub-game/docs/contract.md +352 -14
  88. package/kits/hub-game/docs/vehicle-preset.md +132 -0
  89. package/kits/hub-game/models/hats/baker-cap.pxmodel +89 -0
  90. package/kits/hub-game/models/hats/chef-toque.pxmodel +60 -0
  91. package/kits/hub-game/models/hats/delivery-cap.pxmodel +105 -0
  92. package/kits/hub-game/models/hats/fire-helmet.pxmodel +87 -0
  93. package/kits/hub-game/models/hats/hard-hat.pxmodel +71 -0
  94. package/kits/hub-game/models/hats/nurse-cap.pxmodel +61 -0
  95. package/kits/hub-game/models/hats/police-cap.pxmodel +105 -0
  96. package/kits/hub-game/models/hats/teacher-beret.pxmodel +52 -0
  97. package/kits/hub-game/models/role/square/top-apron.pxmodel +109 -0
  98. package/kits/hub-game/models/role/square/top-cardigan.pxmodel +141 -0
  99. package/kits/hub-game/models/role/square/top-coat.pxmodel +157 -0
  100. package/kits/hub-game/models/role/square/top-scrubs.pxmodel +93 -0
  101. package/kits/hub-game/models/role/square/top-tabard.pxmodel +109 -0
  102. package/kits/hub-game/models/role/square/top-vest.pxmodel +109 -0
  103. package/kits/hub-game/models/role/tool-bag.pxmodel +75 -0
  104. package/kits/hub-game/models/role/tool-bell.pxmodel +71 -0
  105. package/kits/hub-game/models/role/tool-hose.pxmodel +60 -0
  106. package/kits/hub-game/models/role/tool-parcel.pxmodel +61 -0
  107. package/kits/hub-game/models/role/tool-torch.pxmodel +55 -0
  108. package/kits/hub-game/models/role/tool-tray.pxmodel +75 -0
  109. package/kits/hub-game/models/role/top-apron.pxmodel +70 -0
  110. package/kits/hub-game/models/role/top-cardigan.pxmodel +102 -0
  111. package/kits/hub-game/models/role/top-coat.pxmodel +79 -0
  112. package/kits/hub-game/models/role/top-scrubs.pxmodel +54 -0
  113. package/kits/hub-game/models/role/top-tabard.pxmodel +70 -0
  114. package/kits/hub-game/models/role/top-vest.pxmodel +70 -0
  115. package/kits/hub-game/package-lock.json +1 -1
  116. package/kits/hub-game/package.json +1 -1
  117. package/kits/hub-game/scripts/check.mjs +7 -4
  118. package/kits/hub-game/scripts/fixtures/car-vectors.json +279 -0
  119. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +2 -1
  120. package/kits/hub-game/scripts/fixtures/hud-surface.json +670 -0
  121. package/kits/hub-game/scripts/fixtures/talk-surface.json +3930 -0
  122. package/kits/hub-game/scripts/gen-hats.mjs +46 -2
  123. package/kits/hub-game/scripts/gen-role.mjs +80 -0
  124. package/kits/hub-game/scripts/test-act-core.mjs +167 -0
  125. package/kits/hub-game/scripts/test-actions-client.mjs +34 -0
  126. package/kits/hub-game/scripts/test-actors.mjs +48 -0
  127. package/kits/hub-game/scripts/test-analytics.mjs +99 -5
  128. package/kits/hub-game/scripts/test-apply-deck.mjs +122 -0
  129. package/kits/hub-game/scripts/test-back-visibility.mjs +3 -1
  130. package/kits/hub-game/scripts/test-ballot.mjs +2 -0
  131. package/kits/hub-game/scripts/test-car.mjs +43 -0
  132. package/kits/hub-game/scripts/test-decor-client.mjs +2 -1
  133. package/kits/hub-game/scripts/test-decor.mjs +77 -0
  134. package/kits/hub-game/scripts/test-device-class.mjs +83 -0
  135. package/kits/hub-game/scripts/test-emote-wheel.mjs +374 -0
  136. package/kits/hub-game/scripts/test-hats.mjs +5 -4
  137. package/kits/hub-game/scripts/test-host-go.mjs +265 -0
  138. package/kits/hub-game/scripts/test-hub-controls.mjs +108 -0
  139. package/kits/hub-game/scripts/test-hub-entry.mjs +531 -0
  140. package/kits/hub-game/scripts/test-hub-ops.mjs +75 -0
  141. package/kits/hub-game/scripts/test-hud-clear.mjs +12 -2
  142. package/kits/hub-game/scripts/test-hud-rate.mjs +6 -2
  143. package/kits/hub-game/scripts/test-hud-surface.mjs +272 -0
  144. package/kits/hub-game/scripts/test-idle.mjs +347 -1
  145. package/kits/hub-game/scripts/test-interest-cells.mjs +8 -1
  146. package/kits/hub-game/scripts/test-invites-client.mjs +42 -1
  147. package/kits/hub-game/scripts/test-manifest.mjs +30 -0
  148. package/kits/hub-game/scripts/test-no-trips.mjs +42 -0
  149. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  150. package/kits/hub-game/scripts/test-quality.mjs +13 -0
  151. package/kits/hub-game/scripts/test-rehello.mjs +258 -3
  152. package/kits/hub-game/scripts/test-resume-pose-server.mjs +203 -0
  153. package/kits/hub-game/scripts/test-resync.mjs +183 -0
  154. package/kits/hub-game/scripts/test-role-client.mjs +421 -0
  155. package/kits/hub-game/scripts/test-role.mjs +350 -0
  156. package/kits/hub-game/scripts/test-safe-layout.mjs +50 -1
  157. package/kits/hub-game/scripts/test-soundscape.mjs +124 -7
  158. package/kits/hub-game/scripts/test-standing.mjs +15 -1
  159. package/kits/hub-game/scripts/test-talk-surface.mjs +296 -0
  160. package/kits/hub-game/scripts/test-tiers.mjs +13 -0
  161. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +96 -0
  162. package/kits/hub-game/scripts/test-ui-tree.mjs +711 -0
  163. package/kits/hub-game/scripts/test-vehicle-client.mjs +159 -0
  164. package/kits/hub-game/scripts/test-vehicle.mjs +135 -0
  165. package/kits/hub-game/scripts/test-yours.mjs +33 -0
  166. package/kits/hub-game/tools/hubScene/export.mjs +613 -0
  167. package/kits/hub-game/tools/hubScene/hubdata.mjs +921 -0
  168. package/kits/hub-game/tools/hubScene/merge-root.mjs +39 -0
  169. package/kits/hub-game/tools/hubScene/nodeworld.mjs +227 -0
  170. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +798 -0
  171. package/kits/hub-game/tools/hubScene/test/fixture.json +637 -0
  172. package/kits/hub-game/tools/hubScene/test/paint-export.mjs +40 -0
  173. package/kits/hub-game/tools/hubScene/test/upload.test.mjs +655 -0
  174. package/kits/hub-game/tools/hubScene/upload.mjs +636 -0
  175. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +291 -0
  176. package/kits/multiplayer-3d/castle.json +4 -4
  177. package/kits/multiplayer-3d/code/client/resumeGate.js +30 -2
  178. package/kits/multiplayer-3d/code/client/steer.js +3 -1
  179. package/kits/multiplayer-3d/code/systems/multiplayer.js +30 -2
  180. package/kits/multiplayer-3d/package-lock.json +1 -1
  181. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +74 -2
  182. package/kits/physics-3d/CLAUDE.md +1 -1
  183. package/kits/physics-3d/behaviors/Player.jsx +37 -27
  184. package/kits/physics-3d/castle.json +2 -2
  185. package/kits/physics-3d/docs/engine-geometry-memory.md +23 -0
  186. package/kits/physics-3d/engine3d/memoryprofile.js +17 -0
  187. package/kits/physics-3d/engine3d/playerRun.js +6 -1
  188. package/kits/physics-3d/engine3d/pxmodel.js +6 -1
  189. package/kits/physics-3d/engine3d/world3d.js +6 -3
  190. package/kits/physics-3d/package.json +1 -1
  191. package/kits/physics-3d/play/behaviors/Player.js +40 -28
  192. package/kits/physics-3d/scripts/test-memory-profile.mjs +237 -0
  193. package/kits/physics-3d/systems/physics3d.js +5 -2
  194. package/kits/real-time/castle.json +2 -2
  195. package/kits/real-time/code/client/messages.js +5 -0
  196. package/kits/real-time/code/server/session.js +28 -1
  197. package/kits/real-time/package-lock.json +1 -1
  198. package/package.json +5 -4
  199. package/vendor/three/LICENSE +21 -0
  200. package/vendor/three/build/three.core.js +58773 -0
  201. package/vendor/three/build/three.module.js +18251 -0
  202. package/vendor/three/examples/jsm/controls/OrbitControls.js +1860 -0
  203. package/vendor/three/examples/jsm/controls/TransformControls.js +1918 -0
  204. package/vendor/three/examples/jsm/exporters/GLTFExporter.js +3595 -0
  205. package/vendor/three/examples/jsm/geometries/RoundedBoxGeometry.js +216 -0
  206. package/vendor/three/examples/jsm/math/MeshSurfaceSampler.js +315 -0
  207. package/vendor/three/examples/jsm/postprocessing/EffectComposer.js +363 -0
  208. package/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  209. package/vendor/three/examples/jsm/postprocessing/OutputPass.js +139 -0
  210. package/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  211. package/vendor/three/examples/jsm/postprocessing/RenderPass.js +183 -0
  212. package/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  213. package/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  214. package/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  215. package/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1435 -0
  216. package/vendor/three/package.json +134 -0
@@ -60,7 +60,7 @@ function boot(keys = {}, more = {}) {
60
60
  };
61
61
  const engine = {
62
62
  createBody(sim, actor, at) {
63
- return { at: { ...at }, setEnabled() {}, setNextKinematicTranslation() {}, setNextKinematicRotation() {} };
63
+ return { at: { ...at }, translation: () => ({ x: at.x, y: at.y, z: at.z }), rotation: () => ({ x: 0, y: 0, z: 0, w: 1 }), isFixed: () => actor.components.Body?.type !== 'kinematic', setEnabled() {}, setNextKinematicTranslation() {}, setNextKinematicRotation() {} };
64
64
  },
65
65
  removeActor(sim, id) {
66
66
  sim.bodies.delete(id);
@@ -68,7 +68,7 @@ function boot(keys = {}, more = {}) {
68
68
  },
69
69
  };
70
70
  globalThis.__hubTestActors = structuredClone(more.actors ?? actors);
71
- const server = layer(json(keys), hooks, {}, () => true, () => null, null, engine);
71
+ const server = layer(json(keys), hooks, {}, () => true, () => more.ground ?? null, null, engine);
72
72
  const session = {
73
73
  sessionId: 'dev',
74
74
  ...(more.storage ? { storage: { deck: more.storage } } : {}),
@@ -91,7 +91,9 @@ function boot(keys = {}, more = {}) {
91
91
  }
92
92
  }
93
93
  if (!more.owner && Object.hasOwn(more, 'reconnectWindowMs')) { session.hub = { arrival: () => null, readResults: async () => ({ players: {}, boards: {} }), ...(session.hub ?? {}), reconnectWindowMs: more.reconnectWindowMs }; }
94
+ if (more.track && !more.owner) { session.hub = { arrival: () => null, readResults: async () => ({ players: {}, boards: {} }), ...(session.hub ?? {}) }; }
94
95
  if (more.owner) {session.hub = { owner: more.owner, ...(Object.hasOwn(more, 'reconnectWindowMs') ? more.reconnectWindowMs === undefined ? {} : { reconnectWindowMs: more.reconnectWindowMs } : { reconnectWindowMs: 180_000 }), arrival: () => null, readResults: async () => ({ players: {}, boards: {} }), ...(session.hub ?? {}) };}
96
+ if (more.track) { session.hub.track = (id, event) => { more.track.push([id, event]); return true; }; }
95
97
  server.sceneFor(session);
96
98
  server.ready(world);
97
99
  const say = (id, data) => server.message(session, { playerId: id }, data);
@@ -102,7 +104,7 @@ function boot(keys = {}, more = {}) {
102
104
  };
103
105
  // Everyone says hello and is arrived: p2 came through a door with a friend.
104
106
  const pinnedHub = session.hub;
105
- if (more.owner || more.reconnectWindowMs !== undefined) { session.hub = null; }
107
+ if (more.owner || more.reconnectWindowMs !== undefined || more.track) { session.hub = null; }
106
108
  say('p1', { k: 'hub-hello', avatar: 0, party: 1 });
107
109
  say('p2', { k: 'hub-hello', avatar: 3, party: 1, from: 'race', near: '101' });
108
110
  tick(2000);
@@ -1085,6 +1087,77 @@ for (const grace of [1000, 180_000]) {
1085
1087
  }));
1086
1088
  }
1087
1089
 
1090
+ // Terminal analytics: the host resolves a departed player for under a minute,
1091
+ // so a drop still away at 40 s is reported then, once; a quicker return is the
1092
+ // same segment, and a later one reports only its continuation.
1093
+ {
1094
+ const ends = (rows) => rows.filter(([id, e]) => id === 'p2' && (e.kind === 11 || e.kind === 17)).map(([id, e]) => [id, e.kind, e.value, e.result]);
1095
+ for (const [name, keys, more] of [
1096
+ ['House', { houseResume: true, analytics: true, house: { devOwner: 'first' } }, { owner: '101', reconnectWindowMs: undefined }],
1097
+ ['Town', { resumePose: true, analytics: true }, {}],
1098
+ ]) {
1099
+ const kinds = name === 'House' ? [11, 17] : [11];
1100
+ const expect = (value, result) => kinds.map((kind) => ['p2', kind, value, result]);
1101
+ test(`${name} analytics: a drop past the hold ends the visit once, at 40 s`, () => keeping((advance) => {
1102
+ const track = [];
1103
+ const r = boot(keys, { ...more, track, resume() {} });
1104
+ r.tick(1000); r.drop(); r.tick();
1105
+ advance(39_000); r.tick(39_000);
1106
+ assert.deepEqual(ends(track), [], 'nothing before the report deadline');
1107
+ advance(1000); r.tick(1000);
1108
+ const visit = ends(track)[0]?.[2];
1109
+ assert(visit >= 1000 && visit < 2000, `connected time up to the drop (${visit})`);
1110
+ assert.deepEqual(ends(track), expect(visit, 1));
1111
+ advance(300_000); r.tick(300_000);
1112
+ assert.equal(r.leaves.length, 1, 'the hold expired');
1113
+ assert.deepEqual(ends(track), expect(visit, 1), 'expiry adds nothing');
1114
+ }));
1115
+ test(`${name} analytics: a 30 s drop and resume reports nothing until the real leave`, () => keeping((advance) => {
1116
+ const track = [];
1117
+ const r = boot(keys, { ...more, track, resume() {} });
1118
+ r.tick(1000); r.drop(); r.tick();
1119
+ advance(30_000); r.tick(30_000); r.back(); r.say('p2', rehello); r.tick();
1120
+ assert.deepEqual(ends(track), []);
1121
+ r.tick(5000); r.server.shutdown?.(r.session);
1122
+ const rows = ends(track);
1123
+ assert.equal(rows.length, kinds.length, 'one visit, one end');
1124
+ assert.deepEqual(rows.map((row) => row[3]), kinds.map(() => 0));
1125
+ assert(rows[0][2] < 10_000, `time away is not connected time (${rows[0][2]})`);
1126
+ }));
1127
+ test(`${name} analytics: a resume after the report continues the visit`, () => keeping((advance) => {
1128
+ const track = [];
1129
+ const r = boot(keys, { ...more, track, resume() {} });
1130
+ r.tick(1000); r.drop(); r.tick();
1131
+ advance(50_000); r.tick(50_000);
1132
+ r.back(); r.say('p2', rehello); r.tick();
1133
+ r.tick(2000); r.server.shutdown?.(r.session);
1134
+ const rows = ends(track);
1135
+ assert.deepEqual(rows.map((row) => row[3]), [...kinds.map(() => 1), ...kinds.map(() => 2)]);
1136
+ assert.equal(rows.filter((row) => row[1] === 11 && row[3] !== 2).length, 1, 'counted once');
1137
+ }));
1138
+ }
1139
+ }
1140
+
1141
+ // A body real-time keeps after its roster row went must not hold back the report.
1142
+ test('House analytics: a stale body still reports the drop at 40 s', () => keeping((advance) => {
1143
+ const track = [];
1144
+ const r = boot({ houseResume: true, analytics: true, house: { devOwner: 'first' } }, { owner: '101', reconnectWindowMs: undefined, track, resume() {} });
1145
+ r.tick(1000); r.session.players = r.session.players.filter((p) => p.playerId !== 'p2'); r.tick();
1146
+ for (let i = 0; i < 9; i++) { advance(5000); r.tick(5000); }
1147
+ const rows = track.filter(([id, e]) => id === 'p2' && (e.kind === 11 || e.kind === 17));
1148
+ assert.deepEqual(rows.map(([, e]) => e.result), [1, 1]);
1149
+ assert(rows[0][1].value >= 1000 && rows[0][1].value < 2000, `connected time up to the drop (${rows[0][1].value})`);
1150
+ }));
1151
+ test('Town analytics: a body replaced between ticks does not count its time away', () => keeping((advance) => {
1152
+ const track = [];
1153
+ const r = boot({ resumePose: true, analytics: true }, { track, resume() {} });
1154
+ r.tick(1000); r.drop(); r.back(); advance(180_000); r.tick(180_000); r.say('p2', rehello); r.tick(5000);
1155
+ r.server.shutdown?.(r.session);
1156
+ const rows = track.filter(([id, e]) => id === 'p2' && e.kind === 11);
1157
+ assert.equal(rows.length, 1);
1158
+ assert(rows[0][1].value < 10_000, `time away is not connected time (${rows[0][1].value})`);
1159
+ }));
1160
+
1088
1161
  // Trusted Town grace keeps the same visit, even without an author pose marker.
1089
1162
  for (const away of [30_000, 179_000, 180_000]) {
1090
1163
  test(`pinned Town: ${away}ms keeps pose, activity state and first arrival`, () => keeping((advance) => {
@@ -1228,6 +1301,7 @@ for (const viaPlace of [false, true]) {
1228
1301
  assert.deepEqual(toP2(r, from).filter((m) => m.k === 'hub-go'), [
1229
1302
  { k: 'hub-go', door: 'home-1', key: null, place: null, scene: null, title: 'House', party: 1, owner: '101' },
1230
1303
  ]);
1304
+ assert.equal(Object.hasOwn(toP2(r, from).find((m) => m.k === 'hub-go'), 'near'), false, 'a House visit is an ordinary door arrival, with owner and no near');
1231
1305
  }
1232
1306
  r.drop(); r.tick(); r.tick();
1233
1307
  assert.deepEqual(r.leaves, viaPlace ? ['p2'] : []);
@@ -1240,6 +1314,32 @@ for (const viaPlace of [false, true]) {
1240
1314
  });
1241
1315
  }
1242
1316
 
1317
+ test('a lone door arrival onto an authored floor clears an occupied slot; ground and empty slots keep their placement', () => {
1318
+ const arrival = { x: 3, y: 1, z: -4 };
1319
+ const facing = 60 * Math.PI / 180;
1320
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1321
+ for (const [occupied, ground] of [[false, { none: true }], [true, { none: true }], [true, null]]) {
1322
+ const r = boot({ arrival: { actor: 'arrival', spread: 0.65, face: 60 } }, {
1323
+ actors: [...actors, floor, { id: 'arrival', components: { Transform: arrival } }],
1324
+ ground,
1325
+ });
1326
+ r.ctx().placeAt('p1', occupied ? arrival : { x: 20, y: 1, z: 20 });
1327
+ r.drop(); r.tick(); r.back();
1328
+ r.say('p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1329
+ r.tick(2000); r.tick();
1330
+ const guest = r.world.players.get('p2');
1331
+ if (occupied && ground) {
1332
+ const step = 2 * 0.35 + 0.1;
1333
+ assert.ok(Math.abs(guest.at.x - arrival.x - Math.cos(facing) * step) < 1e-9, 'first free slot on the positive side');
1334
+ assert.ok(Math.abs(guest.at.z - arrival.z + Math.sin(facing) * step) < 1e-9, 'stays along the arrival row');
1335
+ assert.ok(Math.hypot(guest.at.x - arrival.x, guest.at.z - arrival.z) >= 0.7, 'no overlapping players');
1336
+ } else {
1337
+ assert.deepEqual([guest.at.x, guest.at.z], [arrival.x, arrival.z], occupied ? 'a ground-backed place keeps the spawn WORLD showed' : 'empty arrival placement is unchanged');
1338
+ }
1339
+ assert.equal(guest.facing, facing, 'keeps the arrival facing');
1340
+ }
1341
+ });
1342
+
1243
1343
  test('town: a sitter who joins a friend at home gets up and goes through the House door', () => {
1244
1344
  const r = boot({ idle: { seats: true }, places: { house: { title: 'House', scene: 'scenes/house.scene' } } }, {
1245
1345
  reconnectWindowMs: 180_000,
@@ -1730,4 +1830,159 @@ test('pose-only transport leave exposes the ordinary live roster before physical
1730
1830
  assert.equal(boot().server.departed, undefined, 'absent mode adds no transport hook');
1731
1831
  });
1732
1832
 
1833
+ // Oct 19 QA: a guest's stored House pose (resumePose) was restored 0.42 m
1834
+ // from the owner, inside the 0.70 m wedge, with no clearance check.
1835
+ {
1836
+ const storage = makePoseStorage();
1837
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1838
+ const arrival = { x: 3, y: 1, z: -4 };
1839
+ const keys = { resumePose: true, arrival: { actor: 'arrival', spread: 0.65, face: 60 } };
1840
+ const more = { actors: [...actors, floor, { id: 'arrival', components: { Transform: arrival } }], ground: { none: true }, storage };
1841
+ const r = boot(keys, more);
1842
+ await flushPose(); r.tick(2000); r.tick();
1843
+ const stored = { x: -2, y: 1, z: 3 };
1844
+ r.ctx().placeAt('p2', stored); r.tick();
1845
+ r.drop(); r.tick(); await flushPose();
1846
+ r.ctx().placeAt('p1', { x: stored.x - 0.38, y: 1, z: stored.z - 0.19 }); r.tick();
1847
+ r.session.players.push({ playerId: 'new-p2', userId: '102', username: 'Bo', isAnonymous: false });
1848
+ r.world.players.set('new-p2', body());
1849
+ r.say('new-p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1850
+ await flushPose(); r.tick(2000); r.tick();
1851
+ const owner = r.world.players.get('p1').at;
1852
+ const guest = r.world.players.get('new-p2').at;
1853
+ assert.ok(Math.hypot(guest.x - owner.x, guest.z - owner.z) >= 0.7, 'a stored pose next to another player steps off');
1854
+ assert.ok(Math.hypot(guest.x - stored.x, guest.z - stored.z) < 3, 'and stays near where it was stored');
1855
+ console.log('ok: a restored pose keeps clear of every player on an authored floor');
1856
+
1857
+ // An empty stored spot is restored exactly, as before.
1858
+ const s2 = makePoseStorage();
1859
+ const q = boot(keys, { ...more, storage: s2 });
1860
+ await flushPose(); q.tick(2000); q.tick();
1861
+ q.ctx().placeAt('p2', stored); q.tick();
1862
+ q.drop(); q.tick(); await flushPose();
1863
+ q.session.players.push({ playerId: 'new-p2', userId: '102', username: 'Bo', isAnonymous: false });
1864
+ q.world.players.set('new-p2', body());
1865
+ q.say('new-p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1866
+ await flushPose(); q.tick(2000); q.tick();
1867
+ assert.deepEqual([q.world.players.get('new-p2').at.x, q.world.players.get('new-p2').at.z], [stored.x, stored.z]);
1868
+ console.log('ok: a clear restored pose is unchanged');
1869
+ }
1870
+
1871
+ test('a retained hold follows a restored pose that stepped off another player', () => {
1872
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1873
+ const r = boot({ arrival: { actor: 'arrival', spread: 0.65, face: 60 } }, {
1874
+ actors: [...actors, floor, { id: 'arrival', components: { Transform: { x: 3, y: 1, z: -4 } } }],
1875
+ ground: { none: true },
1876
+ reconnectWindowMs: 180_000,
1877
+ });
1878
+ const spot = { x: -2, y: 1, z: 3 };
1879
+ r.ctx().placeAt('p2', spot);
1880
+ r.ctx().hold('p2', spot, 0);
1881
+ r.tick(); r.drop(); r.tick();
1882
+ r.ctx().placeAt('p1', { x: spot.x + 0.1, y: 1, z: spot.z });
1883
+ r.back(); r.say('p2', rehello);
1884
+ for (let i = 0; i < 5; i++) {r.tick();}
1885
+ const owner = r.world.players.get('p1').at;
1886
+ const back = r.world.players.get('p2').at;
1887
+ assert.ok(Math.hypot(back.x - owner.x, back.z - owner.z) >= 0.7, 'the hold does not drag them back onto the occupied spot');
1888
+ });
1889
+
1890
+ test('a lone arrival on a narrow authored floor steps off along the floor when the row runs off it', () => {
1891
+ const corridor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 20, height: 0.14, depth: 0.8 } } };
1892
+ const arrival = { x: 0, y: 1, z: 0 };
1893
+ const r = boot({ arrival: { actor: 'arrival', spread: 0.65, face: 90 } }, {
1894
+ actors: [...actors, corridor, { id: 'arrival', components: { Transform: arrival } }],
1895
+ ground: { none: true },
1896
+ });
1897
+ r.ctx().placeAt('p1', arrival);
1898
+ r.drop(); r.tick(); r.back();
1899
+ r.say('p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1900
+ r.tick(2000); r.tick();
1901
+ const guest = r.world.players.get('p2').at;
1902
+ assert.ok(Math.hypot(guest.x - arrival.x, guest.z - arrival.z) >= 0.7, 'clear of the player on the arrival');
1903
+ assert.ok(Math.abs(guest.z) <= 0.4, 'still on the corridor');
1904
+ });
1905
+
1906
+ // #1189's Sol R1 on the production House: spotClear read only scene actors,
1907
+ // so a stepped-off restore landed in placed furniture (a spawned copy).
1908
+ {
1909
+ const storage = makePoseStorage();
1910
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1911
+ const table = { id: 'table', components: { Solid: {}, Body: { type: 'kinematic' }, Transform: { x: 30, y: 0.35, z: 30 }, Shape: { kind: 'box', width: 1, height: 0.7, depth: 1 } } };
1912
+ const r = boot({ resumePose: true, arrival: { actor: 'arrival', spread: 0.65, face: 60 } }, {
1913
+ actors: [...actors, floor, table, { id: 'arrival', components: { Transform: { x: -8, y: 1, z: -8 } } }], ground: { none: true }, storage,
1914
+ });
1915
+ await flushPose(); r.tick(2000); r.tick();
1916
+ const copy = r.ctx().spawn('table', { x: 2.5, y: 0.35, z: 2 });
1917
+ assert.ok(copy, 'the table copy spawned');
1918
+ const stored = { x: 1.4, y: 0.85, z: 2 };
1919
+ r.ctx().placeAt('p2', stored, 0); r.tick();
1920
+ r.drop(); r.tick(); await flushPose();
1921
+ r.ctx().placeAt('p1', { x: 1.5, y: 0.85, z: 2 }); r.tick();
1922
+ r.session.players.push({ playerId: 'new-p2', userId: '102', username: 'Bo', isAnonymous: false });
1923
+ r.world.players.set('new-p2', body());
1924
+ r.say('new-p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1925
+ await flushPose(); r.tick(2000); r.tick();
1926
+ const guest = r.world.players.get('new-p2').at;
1927
+ const owner = r.world.players.get('p1').at;
1928
+ assert.ok(Math.hypot(guest.x - owner.x, guest.z - owner.z) >= 0.7, 'clear of the player');
1929
+ assert.ok(!(Math.abs(guest.x - 2.5) <= 0.5 + 0.35 && Math.abs(guest.z - 2) <= 0.5 + 0.35), `not inside the placed table (at ${guest.x.toFixed(2)}, ${guest.z.toFixed(2)})`);
1930
+ console.log('ok: a stepped-off restore keeps clear of placed furniture (a spawned copy)');
1931
+ }
1932
+
1933
+ test('a lone arrival stepping off an occupied slot keeps clear of placed furniture', () => {
1934
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1935
+ const table = { id: 'table', components: { Solid: {}, Body: { type: 'kinematic' }, Transform: { x: 30, y: 0.35, z: 30 }, Shape: { kind: 'box', width: 1, height: 0.7, depth: 1 } } };
1936
+ const arrival = { x: 1.4, y: 1, z: 2 };
1937
+ const r = boot({ arrival: { actor: 'arrival', spread: 0.65, face: 0 } }, {
1938
+ actors: [...actors, floor, table, { id: 'arrival', components: { Transform: arrival } }], ground: { none: true },
1939
+ });
1940
+ assert.ok(r.ctx().spawn('table', { x: 2.5, y: 0.35, z: 2 }), 'the table copy spawned');
1941
+ r.ctx().placeAt('p1', arrival);
1942
+ r.drop(); r.tick(); r.back();
1943
+ r.say('p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1944
+ r.tick(2000); r.tick();
1945
+ const guest = r.world.players.get('p2').at;
1946
+ assert.ok(Math.hypot(guest.x - arrival.x, guest.z - arrival.z) >= 0.7, 'clear of the player on the arrival');
1947
+ assert.ok(!(Math.abs(guest.x - 2.5) <= 0.85 && Math.abs(guest.z - 2) <= 0.85), `not inside the placed table (at ${guest.x.toFixed(2)}, ${guest.z.toFixed(2)})`);
1948
+ });
1949
+
1950
+ // Oct 19 QA: a House front-door leave (hub.end) kept its durable pose on the
1951
+ // door; the rejoin within 10 minutes was restored there and ended at once.
1952
+ {
1953
+ const storage = makePoseStorage();
1954
+ const floor = { id: 'floor', components: { Solid: {}, Transform: { x: 0, y: -0.07, z: 0 }, Shape: { kind: 'box', width: 40, height: 0.14, depth: 40 } } };
1955
+ const arrival = { x: 3, y: 1, z: -4 };
1956
+ const r = boot({ resumePose: true, arrival: { actor: 'arrival', spread: 0.65, face: 60 } }, {
1957
+ actors: [...actors, floor, { id: 'arrival', components: { Transform: arrival } }], ground: { none: true }, storage,
1958
+ });
1959
+ await flushPose(); r.tick(2000); r.tick();
1960
+ const door = { x: -3.5, y: 1, z: 2.3 };
1961
+ r.ctx().placeAt('p2', door); r.tick();
1962
+ r.ctx().end(['p2']);
1963
+ r.tick(); r.drop(); r.tick(); await flushPose();
1964
+ assert.equal([...storage.rows.keys()].filter((k) => k.includes('"102"')).length, 0, 'an ended visit stores no pose');
1965
+ r.session.players.push({ playerId: 'new-p2', userId: '102', username: 'Bo', isAnonymous: false });
1966
+ r.world.players.set('new-p2', body());
1967
+ r.say('new-p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1968
+ await flushPose(); r.tick(2000); r.tick();
1969
+ const back = r.world.players.get('new-p2').at;
1970
+ assert.ok(Math.hypot(back.x - door.x, back.z - door.z) > 1, `the rejoin is not put back on the door (at ${back.x.toFixed(2)}, ${back.z.toFixed(2)})`);
1971
+ console.log('ok: a front-door leave (hub.end) keeps no pose for a rejoin within 10 minutes');
1972
+
1973
+ // A plain drop (no end) still restores where they stood.
1974
+ const s2 = makePoseStorage();
1975
+ const q = boot({ resumePose: true, arrival: { actor: 'arrival', spread: 0.65, face: 60 } }, {
1976
+ actors: [...actors, floor, { id: 'arrival', components: { Transform: arrival } }], ground: { none: true }, storage: s2,
1977
+ });
1978
+ await flushPose(); q.tick(2000); q.tick();
1979
+ q.ctx().placeAt('p2', door); q.tick(); q.drop(); q.tick(); await flushPose();
1980
+ q.session.players.push({ playerId: 'new-p2', userId: '102', username: 'Bo', isAnonymous: false });
1981
+ q.world.players.set('new-p2', body());
1982
+ q.say('new-p2', { k: 'hub-hello', avatar: 1, from: 'home-1', party: 1 });
1983
+ await flushPose(); q.tick(2000); q.tick();
1984
+ assert.deepEqual([q.world.players.get('new-p2').at.x, q.world.players.get('new-p2').at.z], [door.x, door.z], 'a drop without an end still restores');
1985
+ console.log('ok: a drop without an end still restores its pose');
1986
+ }
1987
+
1733
1988
  console.log(`rehello: ${passed} tests passed`);
@@ -0,0 +1,203 @@
1
+ // Real transport -> SDK wrapper -> real-time -> Rapier -> hub: a durable
2
+ // resumePose taken by a fresh socket of the same account, with a client that
3
+ // reports like the browser does (from where its own copy of the scene stands,
4
+ // taking only a clamped self row as a correction).
5
+ import assert from 'node:assert/strict';
6
+ import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { WebSocket } from 'ws';
10
+ import { startDevSessionServer } from '../../../cli/dist/devSessionServer.js';
11
+
12
+ const root = fileURLToPath(new URL('../../../', import.meta.url));
13
+ const scratch = path.join(root, '.castle');
14
+ await mkdir(scratch, { recursive: true });
15
+ const dir = await mkdtemp(path.join(scratch, 'resume-pose-'));
16
+ const logs = [];
17
+ const sockets = [];
18
+ let server;
19
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
20
+ const spawn = { x: 0, y: 1, z: 0 };
21
+ const cold = { x: 6, y: 1, z: 8 };
22
+ const sameLayer = process.argv[2] === 'same-layer';
23
+ try {
24
+ await mkdir(path.join(dir, 'imports'), { recursive: true });
25
+ for (const kit of ['base', 'hub-game', 'real-time', 'multiplayer-3d', 'physics-3d', 'physics-2d']) {
26
+ await cp(path.join(root, 'kits', kit), path.join(dir, 'imports', `castle.${kit}`), {
27
+ recursive: true,
28
+ filter: source => !['node_modules', 'imports', '.castle'].includes(path.basename(source)),
29
+ });
30
+ }
31
+ await symlink(path.join(root, 'kits/hub-game/node_modules'), path.join(dir, 'node_modules'));
32
+ await mkdir(path.join(dir, 'code/server'), { recursive: true });
33
+ await mkdir(path.join(dir, 'scenes'), { recursive: true });
34
+ await writeFile(path.join(dir, 'package.json'), JSON.stringify({ type: 'module', private: true }));
35
+ await writeFile(path.join(dir, 'castle.json'), JSON.stringify({
36
+ hub: { contract: 1, title: 'Resume pose boundary', resumePose: true },
37
+ server: { main: 'code/server/main.js', tickRate: 20, maxPlayers: 8 },
38
+ }));
39
+ await writeFile(path.join(dir, 'scenes/main.scene'), JSON.stringify({ actors: [
40
+ { id: 'player', components: { Player: {}, Transform: { ...spawn } } },
41
+ ] }));
42
+ // Local serve refuses storage to an unsaved deck: the session sees a
43
+ // revision-checked store kept in a file, so it outlives one session process.
44
+ await writeFile(path.join(dir, 'code/server/poseStorage.js'), `
45
+ import fs from 'node:fs';
46
+ const file = ${JSON.stringify(path.join(dir, 'pose-rows.json'))};
47
+ const load = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { rows: {}, revisions: {} }; } };
48
+ export function poseStorage() {
49
+ return {
50
+ async snapshot({ prefix }) {
51
+ const { rows, revisions } = load();
52
+ return { access: 'test-access', targets: [{ revision: revisions[prefix] ?? null,
53
+ rows: Object.fromEntries(Object.entries(rows).filter(([key]) => key.startsWith(prefix))) }] };
54
+ },
55
+ async transaction({ changes }) {
56
+ const state = load();
57
+ const { prefix, expectedRevision, replace } = changes[0];
58
+ if ((state.revisions[prefix] ?? null) !== expectedRevision) throw new Error('SAVE_CONFLICT');
59
+ for (const key of Object.keys(state.rows)) if (key.startsWith(prefix)) delete state.rows[key];
60
+ Object.assign(state.rows, structuredClone(replace));
61
+ const revision = process.pid + ':' + Date.now() + ':' + Math.random();
62
+ state.revisions[prefix] = revision;
63
+ fs.writeFileSync(file, JSON.stringify(state));
64
+ return { revisions: [{ revision }] };
65
+ },
66
+ async list({ prefix, limit }) {
67
+ const entries = Object.entries(load().rows).filter(([key]) => key.startsWith(prefix)).slice(0, limit);
68
+ return { entries: entries.map(([key, value]) => ({ key, value })), cursor: null };
69
+ },
70
+ };
71
+ }
72
+ `);
73
+ await writeFile(path.join(dir, 'code/server/main.js'), `
74
+ import callbacks from '@imports/castle.hub-game/code/server/index.js';
75
+ import { poseStorage } from './poseStorage.js';
76
+ const deck = poseStorage();
77
+ const seen = new WeakMap();
78
+ const wrap = (session) => {
79
+ if (!session || typeof session !== 'object') return session;
80
+ if (!seen.has(session)) {
81
+ seen.set(session, new Proxy(session, { get(target, key) {
82
+ if (key === 'storage') return { ...target.storage, deck };
83
+ const value = Reflect.get(target, key);
84
+ return typeof value === 'function' ? value.bind(target) : value;
85
+ } }));
86
+ }
87
+ return seen.get(session);
88
+ };
89
+ export default Object.fromEntries(Object.entries(callbacks).map(([key, value]) =>
90
+ [key, typeof value === 'function' ? (session, ...rest) => value(wrap(session), ...rest) : value]));
91
+ `);
92
+ await writeFile(path.join(dir, 'code/server/game.js'), `
93
+ export default {
94
+ message(h, p, d) {
95
+ if (d?.test === 'move') h.placeAt(p.playerId, ${JSON.stringify(cold)}, 40);
96
+ if (d?.test) h.send(p.playerId, { test: d.test, pose: h.sim.players.get(p.playerId)?.at });
97
+ },
98
+ };
99
+ `);
100
+ server = await startDevSessionServer({ projectDir: dir, log: (level, message) => logs.push(`${level}: ${message}`) });
101
+ let base = `ws://127.0.0.1:${server.port}/__castle/mp`;
102
+ const user = { userId: '102', username: 'Bo', isAnonymous: false };
103
+
104
+ // First visit: arrive, get moved, stand there as the browser would, leave.
105
+ const a = await connect(`${base}?nonce=${server.mintNonce(user)}`);
106
+ await a.wait(f => f.t === 'hello');
107
+ a.send({ k: 'hub-hello', avatar: 0, party: 1 });
108
+ a.local = { ...spawn };
109
+ a.reporting = true;
110
+ await a.wait(f => f.t === 'm' && f.d?.k === 'hub-arrived');
111
+ await sleep(300);
112
+ await query(a, 'move');
113
+ a.local = { ...cold };
114
+ await sleep(600);
115
+ const before = (await query(a, 'state')).pose;
116
+ assert.ok(Math.hypot(before.x - cold.x, before.z - cold.z) < 0.3, `first visit stands at the moved spot ${JSON.stringify(before)}`);
117
+ a.socket.close();
118
+ await new Promise(resolve => a.socket.once('close', resolve));
119
+ // The session process ends the visit on its own tick: wait for the row it
120
+ // writes, not a fixed time, before either a restart or a fresh socket.
121
+ const rowsFile = path.join(dir, 'pose-rows.json');
122
+ const rows = async () => { try { return JSON.parse(await readFile(rowsFile, 'utf8')).rows; } catch { return {}; } };
123
+ for (const until = Date.now() + 10000; !Object.keys(await rows()).length && Date.now() < until;) await sleep(50);
124
+ const stored = await rows();
125
+ assert.equal(Object.keys(stored).length, 1, `one durable row ${JSON.stringify(stored)}`);
126
+ if (sameLayer) {
127
+ // The layer goes on: the return is a fresh page of the same account,
128
+ // a new player id beside whatever the layer kept of the first.
129
+ server.defaultSession.nextGuest = () => user;
130
+ } else {
131
+ // The layer empties and shuts down; the return opens a new one (a cold layer).
132
+ await server.shutdown();
133
+ server = await startDevSessionServer({ projectDir: dir, log: (level, message) => logs.push(`${level}: ${message}`) });
134
+ base = `ws://127.0.0.1:${server.port}/__castle/mp`;
135
+ }
136
+
137
+ // A fresh socket of the same account: a new player id, a body at spawn.
138
+ const b = await connect(`${base}?nonce=${server.mintNonce(user)}`);
139
+ await b.wait(f => f.t === 'hello');
140
+ b.local = { ...spawn };
141
+ b.reporting = true;
142
+ b.send({ k: 'hub-hello', avatar: 0, party: 1 });
143
+ await b.wait(f => f.t === 'm' && f.d?.k === 'hub-arrived');
144
+ await sleep(5000);
145
+ const after = (await query(b, 'state')).pose;
146
+ const off = Math.hypot(after.x - before.x, after.z - before.z);
147
+ assert.ok(off < 1, `fresh socket keeps the durable pose: server body ${JSON.stringify(after)}, client ${JSON.stringify(b.local)}, ${off.toFixed(2)} m off`);
148
+ assert.ok(Math.hypot(b.local.x - before.x, b.local.z - before.z) < 1, `client was put there too ${JSON.stringify(b.local)}`);
149
+ console.log(`test-resume-pose-server ${sameLayer ? 'same layer' : 'cold layer'}: a fresh socket keeps its durable pose against browser-like reports`);
150
+ } catch (error) {
151
+ console.error(logs.join('\n'));
152
+ throw error;
153
+ } finally {
154
+ for (const socket of sockets) socket.terminate();
155
+ await server?.shutdown();
156
+ await rm(dir, { recursive: true, force: true });
157
+ }
158
+ async function query(client, test, extra = {}) {
159
+ client.send({ test, ...extra });
160
+ return (await client.wait(f => f.t === 'm' && f.d?.test === test)).d;
161
+ }
162
+ async function connect(url) {
163
+ const socket = new WebSocket(url);
164
+ sockets.push(socket);
165
+ const frames = [];
166
+ const client = {
167
+ socket,
168
+ selfId: null,
169
+ local: null,
170
+ reporting: false,
171
+ send: d => socket.send(JSON.stringify({ t: 'm', d })),
172
+ async wait(predicate) {
173
+ const deadline = Date.now() + 10000;
174
+ while (Date.now() < deadline) {
175
+ const index = frames.findIndex(predicate);
176
+ if (index >= 0) return frames.splice(index, 1)[0];
177
+ await sleep(20);
178
+ }
179
+ throw Error('multiplayer frame timed out');
180
+ },
181
+ };
182
+ // The browser's multiplayer system: the starting WORLD places the body, a
183
+ // clamped self row corrects it, nothing else moves it; it reports at 20 Hz.
184
+ socket.on('message', (data, binary) => {
185
+ if (binary) return;
186
+ const frame = JSON.parse(data);
187
+ if (frame.t === 'hello') client.selfId = frame.playerId;
188
+ for (const d of frame.t === 'm' ? [].concat(frame.d?.batch ?? frame.d) : []) {
189
+ for (const [id, x, y, z, , clamped] of d?.ps ?? []) {
190
+ if (id === client.selfId && client.local && ((d.k === 'w' && !d.again) || clamped)) client.local = { x, y, z };
191
+ }
192
+ }
193
+ frames.push(frame);
194
+ });
195
+ const timer = setInterval(() => {
196
+ if (client.reporting && client.local && socket.readyState === 1) {
197
+ client.send({ k: 'i', p: [client.local.x, client.local.y, client.local.z, 0], c: [], r: [], o: [] });
198
+ }
199
+ }, 50);
200
+ socket.on('close', () => clearInterval(timer));
201
+ await new Promise((resolve, reject) => { socket.once('open', resolve); socket.once('error', reject); });
202
+ return client;
203
+ }