castle-web-cli 0.4.229 → 0.4.231

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 (259) hide show
  1. package/dist/agent-prompts.d.ts +2 -0
  2. package/dist/agent-prompts.js +16 -8
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +21 -21
  5. package/dist/api.d.ts +28 -2
  6. package/dist/api.js +74 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +860 -3
  9. package/dist/castleJson.d.ts +44 -0
  10. package/dist/castleJson.js +131 -0
  11. package/dist/check.js +27 -1
  12. package/dist/contentPack.d.ts +49 -0
  13. package/dist/contentPack.js +273 -0
  14. package/dist/devExperiments.d.ts +21 -0
  15. package/dist/devExperiments.js +139 -0
  16. package/dist/devHub.d.ts +55 -0
  17. package/dist/devHub.js +187 -0
  18. package/dist/devSaveStorage.d.ts +36 -0
  19. package/dist/devSaveStorage.js +469 -0
  20. package/dist/devSessionChild.js +25 -13
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +237 -46
  23. package/dist/devSessionStorage.d.ts +9 -0
  24. package/dist/devSessionStorage.js +66 -1
  25. package/dist/experimentAssignment.d.ts +15 -0
  26. package/dist/experimentAssignment.js +41 -0
  27. package/dist/importCheckHook.d.ts +40 -0
  28. package/dist/importCheckHook.js +171 -0
  29. package/dist/importRegression.d.ts +15 -0
  30. package/dist/importRegression.js +100 -0
  31. package/dist/importTrust.d.ts +2 -0
  32. package/dist/importTrust.js +27 -0
  33. package/dist/importUpdateHook.d.ts +18 -0
  34. package/dist/importUpdateHook.js +31 -8
  35. package/dist/importUpdateHookRunner.js +19 -7
  36. package/dist/imports.d.ts +16 -0
  37. package/dist/imports.js +141 -31
  38. package/dist/index.js +3 -1
  39. package/dist/init.d.ts +3 -0
  40. package/dist/init.js +126 -9
  41. package/dist/install.js +4 -1
  42. package/dist/localPaths.js +4 -0
  43. package/dist/login.js +2 -2
  44. package/dist/platformDoc.js +3 -8
  45. package/dist/playPagePolicy.js +3 -1
  46. package/dist/remix.js +5 -0
  47. package/dist/routerTaskReport.d.ts +28 -0
  48. package/dist/routerTaskReport.js +56 -0
  49. package/dist/save-deck.d.ts +18 -0
  50. package/dist/save-deck.js +142 -6
  51. package/dist/serve.d.ts +8 -0
  52. package/dist/serve.js +99 -14
  53. package/dist/serverBundle.d.ts +1 -1
  54. package/dist/serverBundle.js +5 -1
  55. package/dist/webSourceSync.d.ts +2 -0
  56. package/dist/webSourceSync.js +2 -0
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +406 -53
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +9 -0
  64. package/kits/base/sdk/castle.js +5 -0
  65. package/kits/base/sdk/commands.d.ts +223 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +45 -1
  73. package/kits/base/sdk/multiplayer.js +158 -8
  74. package/kits/base/sdk/save.d.ts +197 -0
  75. package/kits/base/sdk/save.js +525 -0
  76. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  77. package/kits/base/sdk/saveCoordinator.js +252 -0
  78. package/kits/base/sdk/server/hub.d.ts +169 -0
  79. package/kits/base/sdk/server/hub.js +125 -0
  80. package/kits/base/sdk/server/platformHandle.d.ts +42 -1
  81. package/kits/base/sdk/server/storage.d.ts +58 -4
  82. package/kits/base/sdk/server/storage.js +25 -5
  83. package/kits/base/sdk/server/wrapper.d.ts +36 -2
  84. package/kits/base/sdk/server/wrapper.js +92 -11
  85. package/kits/base/sdk/store.d.ts +3 -2
  86. package/kits/base/sdk/store.js +5 -0
  87. package/kits/base/sdk/transport.d.ts +2 -1
  88. package/kits/base/sdk/transport.js +13 -1
  89. package/kits/hub-game/.prettierrc +5 -0
  90. package/kits/hub-game/CLAUDE.md +149 -0
  91. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  92. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  93. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  94. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  95. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  96. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  97. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  98. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  99. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  100. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  101. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  102. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  103. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  104. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  105. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  106. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  107. package/kits/hub-game/castle.json +96 -0
  108. package/kits/hub-game/code/client/attention.js +133 -0
  109. package/kits/hub-game/code/client/avatar.js +288 -0
  110. package/kits/hub-game/code/client/cabinets.js +90 -0
  111. package/kits/hub-game/code/client/chat.js +135 -0
  112. package/kits/hub-game/code/client/chrome.js +1035 -0
  113. package/kits/hub-game/code/client/doorFrame.js +15 -0
  114. package/kits/hub-game/code/client/firstJoin.js +14 -0
  115. package/kits/hub-game/code/client/grab.js +376 -0
  116. package/kits/hub-game/code/client/hookLayer.js +236 -0
  117. package/kits/hub-game/code/client/idle.js +326 -0
  118. package/kits/hub-game/code/client/keys.js +48 -0
  119. package/kits/hub-game/code/client/pack.js +232 -0
  120. package/kits/hub-game/code/client/packFormat.js +397 -0
  121. package/kits/hub-game/code/client/say.js +127 -0
  122. package/kits/hub-game/code/client/sha256.js +80 -0
  123. package/kits/hub-game/code/client/sound.js +147 -0
  124. package/kits/hub-game/code/client/state.js +143 -0
  125. package/kits/hub-game/code/client/talk.js +233 -0
  126. package/kits/hub-game/code/client/tiers.js +480 -0
  127. package/kits/hub-game/code/client/together.js +440 -0
  128. package/kits/hub-game/code/client/wear.js +149 -0
  129. package/kits/hub-game/code/server/actors.js +627 -0
  130. package/kits/hub-game/code/server/blocks.js +103 -0
  131. package/kits/hub-game/code/server/cabinets.js +309 -0
  132. package/kits/hub-game/code/server/game.js +137 -0
  133. package/kits/hub-game/code/server/grab.js +248 -0
  134. package/kits/hub-game/code/server/history.js +96 -0
  135. package/kits/hub-game/code/server/hub.js +1998 -0
  136. package/kits/hub-game/code/server/idle.js +412 -0
  137. package/kits/hub-game/code/server/index.js +64 -0
  138. package/kits/hub-game/code/server/labels.js +59 -0
  139. package/kits/hub-game/code/server/manifest.js +554 -0
  140. package/kits/hub-game/code/server/npcs.js +733 -0
  141. package/kits/hub-game/code/server/party.js +439 -0
  142. package/kits/hub-game/code/server/place.js +43 -0
  143. package/kits/hub-game/code/server/say.js +83 -0
  144. package/kits/hub-game/code/server/wear.js +142 -0
  145. package/kits/hub-game/code/systems/hub.js +2347 -0
  146. package/kits/hub-game/docs/content-pack.md +151 -0
  147. package/kits/hub-game/docs/contract.md +1209 -0
  148. package/kits/hub-game/docs/style.md +137 -0
  149. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  150. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  151. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  152. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  153. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  154. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  155. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  156. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  157. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  158. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  159. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  160. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  161. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  162. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  163. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  164. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  165. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  166. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  167. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  168. package/kits/hub-game/eslint.config.js +20 -0
  169. package/kits/hub-game/fonts.generated.js +9 -0
  170. package/kits/hub-game/index.html +22 -0
  171. package/kits/hub-game/main.jsx +6 -0
  172. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  174. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  175. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  176. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  177. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  178. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  179. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  180. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  181. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  182. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  183. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  184. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  185. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  186. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  187. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  188. package/kits/hub-game/package-lock.json +365 -0
  189. package/kits/hub-game/package.json +32 -0
  190. package/kits/hub-game/scenes/main.scene +318 -0
  191. package/kits/hub-game/scripts/check.mjs +339 -0
  192. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  193. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  194. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  195. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  196. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  197. package/kits/hub-game/scripts/pack.mjs +192 -0
  198. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  199. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  200. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  201. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  202. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  203. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  204. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  205. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  206. package/kits/hub-game/scripts/test-door.mjs +56 -0
  207. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  208. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  209. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  210. package/kits/hub-game/scripts/test-hub-trip.mjs +1518 -0
  211. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  212. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  213. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  214. package/kits/hub-game/scripts/test-manifest.mjs +270 -0
  215. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  216. package/kits/hub-game/scripts/test-npcs.mjs +724 -0
  217. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  218. package/kits/hub-game/scripts/test-party.mjs +369 -0
  219. package/kits/hub-game/scripts/test-say.mjs +149 -0
  220. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  221. package/kits/hub-game/scripts/test-together.mjs +215 -0
  222. package/kits/hub-game/theme.style +3 -0
  223. package/kits/multiplayer-3d/castle.json +5 -5
  224. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  225. package/kits/multiplayer-3d/code/server/players.js +4 -1
  226. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  227. package/kits/multiplayer-3d/code/server/world.js +20 -7
  228. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  229. package/kits/physics-2d/CLAUDE.md +2 -0
  230. package/kits/physics-2d/castle.json +2 -2
  231. package/kits/physics-2d/engine/art.js +13 -0
  232. package/kits/physics-2d/engine/assets.js +4 -2
  233. package/kits/physics-2d/engine/scene.js +117 -5
  234. package/kits/physics-2d/package.json +1 -1
  235. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  236. package/kits/physics-3d/CLAUDE.md +285 -1
  237. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  238. package/kits/physics-3d/castle.json +3 -3
  239. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -5
  240. package/kits/physics-3d/engine3d/actornode.js +253 -0
  241. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  242. package/kits/physics-3d/engine3d/materials.js +29 -1
  243. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  244. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  245. package/kits/physics-3d/engine3d/world3d.js +527 -5
  246. package/kits/physics-3d/package.json +1 -1
  247. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  248. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  249. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  250. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  251. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  252. package/kits/physics-3d/systems/physics3d.js +187 -5
  253. package/kits/real-time/castle.json +2 -2
  254. package/kits/real-time/code/client/connection.js +77 -7
  255. package/kits/real-time/code/client/gameHooks.js +63 -3
  256. package/kits/real-time/code/client/messages.js +7 -0
  257. package/kits/real-time/code/server/gameHooks.js +24 -0
  258. package/kits/real-time/code/server/session.js +390 -22
  259. package/package.json +2 -2
@@ -8,9 +8,11 @@ import { fileURLToPath } from 'url';
8
8
  import { WebSocketServer, WebSocket } from 'ws';
9
9
  import { readCastleJson, resolveServerConfig } from './castleJson.js';
10
10
  import { OutboundFrameMeter } from './devSessionFrameBudget.js';
11
- import { runDevStorageOperation } from './devSessionStorage.js';
11
+ import { SAVE_VERBS } from './devSaveStorage.js';
12
+ import { runDevSave, runDevStorageOperation } from './devSessionStorage.js';
12
13
  import { rawDataToString } from './rawData.js';
13
14
  import { bundleServerModule } from './serverBundle.js';
15
+ import { devDeckCastleJsons, devDeckSessionKey } from './contentPack.js';
14
16
  const PROTOCOL_VERSION = 1;
15
17
  const MAX_CLIENT_FRAME_BYTES = 16 * 1024;
16
18
  // Mirrors the host-agent's server-to-client broadcast cap.
@@ -22,8 +24,15 @@ const NONCE_TTL_MS = 60_000;
22
24
  const INVALID_RECONNECT_CLOSE_CODE = 4003;
23
25
  const CHILD_READY_TIMEOUT_MS = 15_000;
24
26
  const CHILD_STOP_GRACE_MS = 2_000;
27
+ // A named session nobody is connected to is stopped after this long, the way the
28
+ // platform tears down an empty session; its next join starts it fresh.
29
+ const NAMED_SESSION_IDLE_MS = 60_000;
30
+ const DEFAULT_SESSION_ID = 'dev';
31
+ export function devSessionIdFor(key) {
32
+ return key === null ? DEFAULT_SESSION_ID : `${DEFAULT_SESSION_ID}:${key}`;
33
+ }
25
34
  export async function startDevSessionServer(opts) {
26
- const server = new DevSessionServerImpl(opts.projectDir, opts.log);
35
+ const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS);
27
36
  try {
28
37
  await server.start();
29
38
  return server;
@@ -33,6 +42,112 @@ export async function startDevSessionServer(opts) {
33
42
  throw error;
34
43
  }
35
44
  }
45
+ /**
46
+ * Owns the one port `/__castle/mp` is proxied to, and hands each upgrade to the
47
+ * session that minted its nonce, owns its reconnect token, or spawned the child
48
+ * presenting its boot token. The default session ('dev') always runs; a named
49
+ * key's session runs while anyone is in it.
50
+ */
51
+ class DevSessionRouter {
52
+ projectDir;
53
+ log;
54
+ idleMs;
55
+ sessionId = DEFAULT_SESSION_ID;
56
+ port = 0;
57
+ server = http.createServer((_req, res) => res.writeHead(404).end());
58
+ defaultSession;
59
+ named = new Map();
60
+ closed = false;
61
+ constructor(projectDir, log, idleMs) {
62
+ this.projectDir = projectDir;
63
+ this.log = log;
64
+ this.idleMs = idleMs;
65
+ this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { });
66
+ this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
67
+ }
68
+ async start() {
69
+ await new Promise((resolve, reject) => {
70
+ this.server.once('error', reject);
71
+ this.server.listen(0, '127.0.0.1', () => {
72
+ this.server.off('error', reject);
73
+ const address = this.server.address();
74
+ if (!address || typeof address === 'string')
75
+ reject(new Error('dev session server has no port'));
76
+ else {
77
+ this.port = address.port;
78
+ resolve();
79
+ }
80
+ });
81
+ });
82
+ await this.defaultSession.start();
83
+ }
84
+ mintNonce(author, key = null, experimentVariants) {
85
+ return this.sessionFor(key).mintNonce(author, experimentVariants);
86
+ }
87
+ sessionIdFor(key) {
88
+ return devSessionIdFor(key);
89
+ }
90
+ handleFilesChanged(message) {
91
+ for (const session of this.sessions())
92
+ session.handleFilesChanged(message);
93
+ }
94
+ async shutdown() {
95
+ if (this.closed)
96
+ return;
97
+ this.closed = true;
98
+ const sessions = this.sessions();
99
+ this.named.clear();
100
+ await Promise.all(sessions.map((session) => session.shutdown()));
101
+ await closeHttpServer(this.server);
102
+ }
103
+ shutdownNow() {
104
+ this.closed = true;
105
+ for (const session of this.sessions())
106
+ session.shutdownNow();
107
+ this.named.clear();
108
+ this.server.close();
109
+ }
110
+ sessions() {
111
+ return [this.defaultSession, ...this.named.values()];
112
+ }
113
+ sessionFor(key) {
114
+ if (key === null || this.closed)
115
+ return this.defaultSession;
116
+ const existing = this.named.get(key);
117
+ if (existing)
118
+ return existing;
119
+ // `deck:<name>/<key>` runs another local deck's server, one this deck lists
120
+ // in `devDecks` (contentPack.ts): a door to a separately built deck.
121
+ const other = devDeckSessionKey(this.projectDir, key);
122
+ const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs);
123
+ this.named.set(key, session);
124
+ session.start().catch((error) => {
125
+ this.log('error', `(${key}) start failed: ${error instanceof Error ? error.message : String(error)}`);
126
+ this.stopIdle(key, session);
127
+ });
128
+ return session;
129
+ }
130
+ stopIdle(key, session) {
131
+ if (this.named.get(key) !== session)
132
+ return;
133
+ this.named.delete(key);
134
+ void session.shutdown();
135
+ }
136
+ handleUpgrade(request, socket, head) {
137
+ let url;
138
+ try {
139
+ url = new URL(request.url ?? '/', 'ws://127.0.0.1');
140
+ }
141
+ catch {
142
+ rejectUpgrade(socket, 400);
143
+ return;
144
+ }
145
+ // A credential nobody owns falls to the default session, which rejects it
146
+ // exactly as a single-session serve always has.
147
+ const owner = this.sessions().find((session) => session.ownsUpgrade(url));
148
+ (owner ?? this.defaultSession).handleUpgrade(request, socket, head, url);
149
+ }
150
+ }
36
151
  function serverDirOf(entry) {
37
152
  const slash = entry.lastIndexOf('/');
38
153
  return slash < 0 ? '' : entry.slice(0, slash + 1);
@@ -58,12 +173,16 @@ export function serverRestartNeeded(changes, opts) {
58
173
  const IMPORTED_SERVER_PATH = /^(imports|forks)\/[^/]+\/(code\/)?server\//;
59
174
  // The runtime frames that cost the session a frame of its outbound budget.
60
175
  const OUTBOUND_FRAME_TYPES = new Set(['sendTo', 'sendBinary', 'broadcast', 'broadcastBinary']);
61
- class DevSessionServerImpl {
176
+ // One running session: its players, roster, reconnect tokens, frame meter and
177
+ // runtime child. The router owns the listener and hands it its upgrades.
178
+ class DevSessionImpl {
62
179
  projectDir;
63
180
  log;
64
- sessionId = 'dev';
65
- port = 0;
66
- server = http.createServer((_req, res) => res.writeHead(404).end());
181
+ key;
182
+ port;
183
+ onIdle;
184
+ idleMs;
185
+ sessionId;
67
186
  clientWss = new WebSocketServer({
68
187
  noServer: true,
69
188
  maxPayload: MAX_CLIENT_FRAME_BYTES,
@@ -95,34 +214,54 @@ class DevSessionServerImpl {
95
214
  // Everything beside the entry restarts the server too, wherever it lives.
96
215
  serverDir;
97
216
  serverSettings;
98
- constructor(projectDir, log) {
217
+ // The first boot, which a join that raced it waits on rather than bouncing.
218
+ starting = null;
219
+ idleTimer = null;
220
+ /**
221
+ * `key` null is the default session, which never idles out. A named one calls
222
+ * `onIdle` once it has had nobody connected for `idleMs`.
223
+ */
224
+ constructor(projectDir, log, key, port, onIdle, idleMs = NAMED_SESSION_IDLE_MS) {
99
225
  this.projectDir = projectDir;
100
226
  this.log = log;
227
+ this.key = key;
228
+ this.port = port;
229
+ this.onIdle = onIdle;
230
+ this.idleMs = idleMs;
231
+ this.sessionId = devSessionIdFor(key);
101
232
  this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
102
233
  this.serverDir = serverDirOf(this.serverEntry);
103
234
  this.serverSettings = JSON.stringify(readCastleJson(projectDir)?.server ?? null);
104
- this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
105
235
  }
106
- async start() {
107
- await new Promise((resolve, reject) => {
108
- this.server.once('error', reject);
109
- this.server.listen(0, '127.0.0.1', () => {
110
- this.server.off('error', reject);
111
- const address = this.server.address();
112
- if (!address || typeof address === 'string')
113
- reject(new Error('dev session server has no port'));
114
- else {
115
- this.port = address.port;
116
- resolve();
117
- }
118
- });
119
- });
120
- await this.restartChild();
236
+ start() {
237
+ // A session started for a nonce nobody redeems still idles out.
238
+ this.updateIdle();
239
+ // The first boot goes through the same queue as file-change restarts, so
240
+ // an edit made while it bundles waits for it instead of racing it.
241
+ const run = this.restartQueue.then(() => this.restartChild());
242
+ this.restartQueue = run.catch(() => undefined);
243
+ this.starting = run;
244
+ const clear = () => {
245
+ this.starting = null;
246
+ };
247
+ this.starting.then(clear, clear);
248
+ return this.starting;
121
249
  }
122
- mintNonce(author) {
250
+ /** Whether this upgrade carries a credential this session issued. */
251
+ ownsUpgrade(url) {
252
+ if (url.pathname === '/__castle/platform') {
253
+ return !!this.bootToken && url.searchParams.get('bootToken') === this.bootToken;
254
+ }
255
+ const nonce = url.searchParams.get('nonce');
256
+ if (nonce)
257
+ return this.nonces.has(nonce);
258
+ const reconnect = url.searchParams.get('reconnect');
259
+ return !!reconnect && this.reconnects.has(reconnect);
260
+ }
261
+ mintNonce(author, experimentVariants) {
123
262
  this.pruneNonces();
124
263
  const nonce = randomUUID();
125
- this.nonces.set(nonce, { author, mintedAt: Date.now() });
264
+ this.nonces.set(nonce, { author, experimentVariants, mintedAt: Date.now() });
126
265
  return nonce;
127
266
  }
128
267
  handleFilesChanged(message) {
@@ -150,35 +289,38 @@ class DevSessionServerImpl {
150
289
  async shutdown() {
151
290
  if (this.closed)
152
291
  return;
153
- this.closed = true;
154
- if (this.restartTimer)
155
- clearTimeout(this.restartTimer);
292
+ this.markClosed();
156
293
  this.closeClients(1001, 'dev serve stopped');
294
+ // A boot or restart still in flight sees `closed` after its awaits and
295
+ // stops short; wait for it so its child and temp dir are cleaned up here.
296
+ await this.restartQueue.catch(() => undefined);
157
297
  await this.stopChild();
158
298
  await Promise.all([
159
299
  closeWebSocketServer(this.clientWss),
160
300
  closeWebSocketServer(this.platformWss),
161
- closeHttpServer(this.server),
162
301
  ]);
163
302
  this.removeTempDir();
164
303
  }
165
304
  shutdownNow() {
166
- this.closed = true;
167
- if (this.restartTimer)
168
- clearTimeout(this.restartTimer);
305
+ this.markClosed();
169
306
  this.closeClients(1001, 'dev serve stopped');
170
307
  this.platformSocket?.terminate();
171
308
  this.child?.kill('SIGKILL');
172
- this.server.close();
173
309
  this.removeTempDir();
174
310
  }
175
- handleUpgrade(request, socket, head) {
176
- let url;
177
- try {
178
- url = new URL(request.url ?? '/', 'ws://127.0.0.1');
179
- }
180
- catch {
181
- rejectUpgrade(socket, 400);
311
+ markClosed() {
312
+ this.closed = true;
313
+ if (this.restartTimer)
314
+ clearTimeout(this.restartTimer);
315
+ if (this.idleTimer)
316
+ clearTimeout(this.idleTimer);
317
+ this.idleTimer = null;
318
+ }
319
+ handleUpgrade(request, socket, head, url) {
320
+ // A named session's first join can beat its child's boot; hold it until
321
+ // the runtime is up instead of bouncing it.
322
+ if (url.pathname === '/__castle/mp' && !this.runtimeReady && this.starting) {
323
+ this.starting.then(() => this.handleUpgrade(request, socket, head, url), () => rejectUpgrade(socket, 503));
182
324
  return;
183
325
  }
184
326
  if (url.pathname === '/__castle/platform') {
@@ -257,7 +399,14 @@ class DevSessionServerImpl {
257
399
  const identity = isFirstConnection ? auth.record.author : this.nextGuest();
258
400
  if (isFirstConnection)
259
401
  this.primaryPlayerId = playerId;
260
- player = { identity, reconnectToken: this.rotateReconnect(playerId), socket };
402
+ // A guest is the same page-side user in another tab, so it keeps the arms
403
+ // its page was given.
404
+ player = {
405
+ identity,
406
+ experimentVariants: auth.record.experimentVariants,
407
+ reconnectToken: this.rotateReconnect(playerId),
408
+ socket,
409
+ };
261
410
  this.players.set(playerId, player);
262
411
  }
263
412
  else {
@@ -295,8 +444,13 @@ class DevSessionServerImpl {
295
444
  protocolVersion: PROTOCOL_VERSION,
296
445
  t: 'playerJoined',
297
446
  player: { playerId, ...player.identity },
447
+ // Beside the player, never on it: decks broadcast player objects.
448
+ ...(player.experimentVariants && Object.keys(player.experimentVariants).length > 0
449
+ ? { experimentVariants: player.experimentVariants }
450
+ : {}),
298
451
  });
299
452
  this.broadcastRoster();
453
+ this.updateIdle();
300
454
  }
301
455
  handleClientMessage(playerId, socket, data, isBinary) {
302
456
  // Frames queued on the superseded socket must not act as the new player.
@@ -354,6 +508,7 @@ class DevSessionServerImpl {
354
508
  this.primaryPlayerId = null;
355
509
  }
356
510
  this.broadcastRoster();
511
+ this.updateIdle();
357
512
  }
358
513
  attachPlatform(socket) {
359
514
  this.platformSocket = socket;
@@ -444,13 +599,18 @@ class DevSessionServerImpl {
444
599
  this.log('log', warning);
445
600
  }
446
601
  async handleStorageRequest(reqId, op, args) {
602
+ const socket = this.platformSocket;
447
603
  const deckId = readCastleJson(this.projectDir)?.deckId;
448
604
  // Local serve has no host credential to stamp a remote player's authority. Its
449
605
  // authenticated OPEN roster proves presence here; GraphQL separately restricts
450
606
  // funded audience sends to the signed-in CLI user's own subject.
451
- const result = await runDevStorageOperation(deckId, op, args, this.connectedPlayers().map((player) => player.userId));
607
+ const result = SAVE_VERBS.has(op)
608
+ ? runDevSave(this.projectDir, this.sessionId, op, args)
609
+ : await runDevStorageOperation(deckId, op, args, this.connectedPlayers().map((player) => player.userId));
452
610
  // The child may have restarted while this was out; its replacement never asked, so
453
611
  // there is nobody to tell.
612
+ if (this.platformSocket !== socket)
613
+ return;
454
614
  this.sendPlatform({
455
615
  protocolVersion: PROTOCOL_VERSION,
456
616
  t: 'storageResult',
@@ -481,7 +641,15 @@ class DevSessionServerImpl {
481
641
  throw new Error('multiplayer server entry is unavailable');
482
642
  this.serverEntry = config.entry;
483
643
  this.serverDir = serverDirOf(config.entry);
484
- const code = await bundleServerModule(this.projectDir, config, false);
644
+ // A deck whose doors lead to other local decks (`devDecks`) gets their
645
+ // castle.json at `import.meta.env.CASTLE_DEV_DECKS`, read when it builds.
646
+ const devDecks = devDeckCastleJsons(this.projectDir);
647
+ const define = Object.keys(devDecks).length
648
+ ? { 'import.meta.env.CASTLE_DEV_DECKS': JSON.stringify(devDecks) }
649
+ : {};
650
+ const code = await bundleServerModule(this.projectDir, config, false, define);
651
+ if (this.closed)
652
+ return;
485
653
  this.removeTempDir();
486
654
  this.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-dev-session-'));
487
655
  const bundlePath = path.join(this.tempDir, 'server.mjs');
@@ -497,7 +665,7 @@ class DevSessionServerImpl {
497
665
  stdio: ['ignore', 'pipe', 'pipe'],
498
666
  env: {
499
667
  ...process.env,
500
- CASTLE_DEV_SESSION_CHANNEL_URL: `ws://127.0.0.1:${this.port}/__castle/platform`,
668
+ CASTLE_DEV_SESSION_CHANNEL_URL: `ws://127.0.0.1:${this.port()}/__castle/platform`,
501
669
  CASTLE_DEV_SESSION_BOOT_TOKEN: this.bootToken,
502
670
  CASTLE_DEV_SESSION_BUNDLE_PATH: bundlePath,
503
671
  },
@@ -539,12 +707,16 @@ class DevSessionServerImpl {
539
707
  }
540
708
  }
541
709
  currentConfig() {
542
- return (resolveServerConfig(this.projectDir) ?? {
710
+ const config = resolveServerConfig(this.projectDir) ?? {
543
711
  entry: 'server/index.js',
544
712
  tickRate: 20,
545
713
  maxPlayers: 8,
546
714
  voiceEnabled: true,
547
- });
715
+ };
716
+ // A load test of a session bigger than any deck may declare (a hub town's
717
+ // 100-bot run) raises the cap for this serve only; production never reads it.
718
+ const loadTest = Number(process.env.CASTLE_DEV_SESSION_MAX_PLAYERS);
719
+ return Number.isInteger(loadTest) && loadTest > 0 ? { ...config, maxPlayers: loadTest } : config;
548
720
  }
549
721
  sendPlatform(frame) {
550
722
  if (this.platformSocket?.readyState === WebSocket.OPEN)
@@ -593,6 +765,24 @@ class DevSessionServerImpl {
593
765
  player.socket = undefined;
594
766
  socket?.close(code, reason);
595
767
  }
768
+ this.updateIdle();
769
+ }
770
+ updateIdle() {
771
+ if (this.key === null || this.closed)
772
+ return;
773
+ if (this.connectedPlayers().length > 0) {
774
+ if (this.idleTimer)
775
+ clearTimeout(this.idleTimer);
776
+ this.idleTimer = null;
777
+ return;
778
+ }
779
+ if (this.idleTimer)
780
+ return;
781
+ this.idleTimer = setTimeout(() => {
782
+ this.idleTimer = null;
783
+ if (this.connectedPlayers().length === 0)
784
+ this.onIdle();
785
+ }, this.idleMs);
596
786
  }
597
787
  kick(playerId, reason) {
598
788
  const player = this.players.get(playerId);
@@ -607,6 +797,7 @@ class DevSessionServerImpl {
607
797
  player.socket.close(4002, 'kicked');
608
798
  }
609
799
  this.broadcastRoster();
800
+ this.updateIdle();
610
801
  }
611
802
  rotateReconnect(playerId) {
612
803
  const token = randomUUID();
@@ -1,9 +1,18 @@
1
+ import type { GraphqlResponse } from './castle-host/host.js';
1
2
  export interface DevStorageResult {
2
3
  ok: boolean;
3
4
  value?: unknown;
4
5
  error?: {
5
6
  code: string;
6
7
  message: string;
8
+ [detail: string]: unknown;
7
9
  };
8
10
  }
11
+ /** A session server's save. Its args are what the platform's storage route takes. */
12
+ export declare function runDevSave(projectDir: string, sessionId: string, op: string, args: Record<string, unknown>): DevStorageResult;
13
+ /**
14
+ * A page's save, answered in place of the GraphQL call the browser host makes
15
+ * for it. Undefined for every other document, which goes to the real API.
16
+ */
17
+ export declare function devSaveGraphql(projectDir: string, userId: string | null, query: string, variables: Record<string, unknown>): GraphqlResponse | undefined;
9
18
  export declare function runDevStorageOperation(deckId: string | undefined, op: string, args: Record<string, unknown>, connectedUserIds?: readonly string[]): Promise<DevStorageResult>;
@@ -1,4 +1,62 @@
1
1
  import { graphql } from './api.js';
2
+ import { readCastleJson } from './castleJson.js';
3
+ import { DevSaveStorage } from './devSaveStorage.js';
4
+ // The platform's reply allowance for one storage call: its byte-rate window.
5
+ const SERVER_REPLY_BYTES = 2 * 1024 * 1024;
6
+ const CLIENT_REPLY_BYTES = 512 * 1024;
7
+ const saveStores = new Map();
8
+ function saveStoreFor(projectDir) {
9
+ let store = saveStores.get(projectDir);
10
+ if (!store) {
11
+ store = new DevSaveStorage();
12
+ saveStores.set(projectDir, store);
13
+ }
14
+ return store;
15
+ }
16
+ /** A session server's save. Its args are what the platform's storage route takes. */
17
+ export function runDevSave(projectDir, sessionId, op, args) {
18
+ const input = op === 'operation' ? args : args.input;
19
+ return saveStoreFor(projectDir).execute(op, input, {
20
+ principal: 'server',
21
+ binding: `session:${sessionId}`,
22
+ server: true,
23
+ deckWritable: true,
24
+ replyEnvelope: (value) => ({ value }),
25
+ replyBytes: SERVER_REPLY_BYTES,
26
+ });
27
+ }
28
+ const SAVE_FIELDS = {
29
+ cauldronStorageSnapshot: 'snapshot',
30
+ cauldronStorageOperation: 'operation',
31
+ cauldronStorageTransaction: 'transaction',
32
+ cauldronStorageClaim: 'claim',
33
+ cauldronStorageInitialize: 'initialize',
34
+ };
35
+ /**
36
+ * A page's save, answered in place of the GraphQL call the browser host makes
37
+ * for it. Undefined for every other document, which goes to the real API.
38
+ */
39
+ export function devSaveGraphql(projectDir, userId, query, variables) {
40
+ const field = /\b(cauldronStorage[A-Z][A-Za-z]*)\s*\(/.exec(query)?.[1];
41
+ const op = field && SAVE_FIELDS[field];
42
+ if (!field || !op)
43
+ return undefined;
44
+ const input = op === 'operation'
45
+ ? { operationId: variables.operationId }
46
+ : variables.input;
47
+ const result = saveStoreFor(projectDir).execute(op, input, {
48
+ principal: `user:${userId}`,
49
+ binding: `user:${userId}`,
50
+ server: false,
51
+ ...(userId ? { userId } : {}),
52
+ deckWritable: !readCastleJson(projectDir)?.server,
53
+ replyEnvelope: (value) => ({ data: { [field]: value } }),
54
+ replyBytes: CLIENT_REPLY_BYTES,
55
+ });
56
+ return result.ok
57
+ ? { data: { [field]: result.value } }
58
+ : { errors: [{ message: result.error.message, extensions: result.error }] };
59
+ }
2
60
  const SCOPE_ARGS = `
3
61
  $deckId: ID!
4
62
  $scope: CauldronStorageScope!
@@ -402,7 +460,14 @@ export async function runDevStorageOperation(deckId, op, args, connectedUserIds
402
460
  const error = response.errors?.[0];
403
461
  if (error) {
404
462
  const code = error.extensions?.code;
405
- return failure(typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE', error.message ?? 'storage request failed');
463
+ return {
464
+ ok: false,
465
+ error: {
466
+ ...error.extensions,
467
+ code: typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE',
468
+ message: error.message ?? 'storage request failed',
469
+ },
470
+ };
406
471
  }
407
472
  return { ok: true, value: response.data?.[operation.field] ?? null };
408
473
  }
@@ -0,0 +1,15 @@
1
+ export interface ExperimentAssignmentConfig {
2
+ variants: readonly string[];
3
+ weights?: readonly number[];
4
+ winner?: string;
5
+ }
6
+ export declare const EXPERIMENT_BUCKETS = 1000;
7
+ /** 0 through 999: the first 8 bytes of SHA-256, big-endian, mod 1000. */
8
+ export declare function experimentBucket(userId: string, deckId: string, name: string): number;
9
+ /**
10
+ * The split used when `weights` is omitted: 100 shared equally, the remainder
11
+ * going one point at a time to the earliest variants (three variants are
12
+ * 34, 33, 33).
13
+ */
14
+ export declare function equalExperimentWeights(count: number): number[];
15
+ export declare function assignExperimentVariant(userId: string, deckId: string, name: string, config: ExperimentAssignmentConfig): string;
@@ -0,0 +1,41 @@
1
+ // Which variant of a deck experiment a player gets. Pure, and the SAME function
2
+ // Castle's server runs (ghost-server): `castle-web serve` answers with it so a
3
+ // deck sees in dev the arm its player would get once published, and the fixed
4
+ // vectors in scripts/tests/experiments.mjs are asserted on both sides. Change
5
+ // one and the other has to change with it.
6
+ //
7
+ // Nothing is stored. The bucket is a hash of the player, the deck and the
8
+ // experiment's name, so it is the same on every load, differs between
9
+ // experiments and between decks, and moves a player only when a change to
10
+ // `variants` or `weights` moves the boundary their bucket sits beside.
11
+ import { createHash } from 'node:crypto';
12
+ export const EXPERIMENT_BUCKETS = 1000;
13
+ /** 0 through 999: the first 8 bytes of SHA-256, big-endian, mod 1000. */
14
+ export function experimentBucket(userId, deckId, name) {
15
+ const hex = createHash('sha256').update(`${userId}:${deckId}:${name}`, 'utf8').digest('hex');
16
+ return Number(BigInt(`0x${hex.slice(0, 16)}`) % BigInt(EXPERIMENT_BUCKETS));
17
+ }
18
+ /**
19
+ * The split used when `weights` is omitted: 100 shared equally, the remainder
20
+ * going one point at a time to the earliest variants (three variants are
21
+ * 34, 33, 33).
22
+ */
23
+ export function equalExperimentWeights(count) {
24
+ const base = Math.floor(100 / count);
25
+ const extra = 100 - base * count;
26
+ return Array.from({ length: count }, (_, index) => base + (index < extra ? 1 : 0));
27
+ }
28
+ export function assignExperimentVariant(userId, deckId, name, config) {
29
+ if (config.winner !== undefined)
30
+ return config.winner;
31
+ const weights = config.weights ?? equalExperimentWeights(config.variants.length);
32
+ const bucket = experimentBucket(userId, deckId, name);
33
+ let upper = 0;
34
+ for (let index = 0; index < config.variants.length; index += 1) {
35
+ upper += weights[index] * 10;
36
+ if (bucket < upper)
37
+ return config.variants[index];
38
+ }
39
+ // Unreachable for a validated block, whose weights sum to 100.
40
+ return config.variants[config.variants.length - 1];
41
+ }
@@ -0,0 +1,40 @@
1
+ import { type DeckImport } from './castleJson.js';
2
+ /** The alias a deck's OWN `onCheck` is reported under. */
3
+ export declare const SELF_CHECK_ALIAS = "self";
4
+ export interface ImportCheckOutcome {
5
+ alias: string;
6
+ errors: string[];
7
+ warnings: string[];
8
+ }
9
+ export interface ImportChecksResult {
10
+ outcomes: ImportCheckOutcome[];
11
+ /** Every error, each prefixed with the alias whose check raised it. */
12
+ errors: string[];
13
+ }
14
+ export interface CheckTarget {
15
+ alias: string;
16
+ importDir: string;
17
+ declared: string;
18
+ /** The import's pin, or null for the deck's own check. */
19
+ pin: DeckImport | null;
20
+ }
21
+ /**
22
+ * Run every applicable `onCheck`, one at a time, and collect what they found.
23
+ * Warnings are logged here; errors are returned for the caller to refuse on --
24
+ * `check` exits non-zero, `save-deck` publishes nothing.
25
+ */
26
+ export declare function runImportChecks(deckDir: string, log?: (message: string) => void): Promise<ImportChecksResult>;
27
+ /** The castle.json hooks an import names that run against the deck importing it. */
28
+ export type HookField = 'onCheck' | 'onPack';
29
+ export interface RunnableImportHook {
30
+ target: CheckTarget;
31
+ modulePath: string;
32
+ }
33
+ /**
34
+ * Every `field` hook that applies to this deck and may run here, in order: each
35
+ * import's, then the deck's own. One that cannot be run from where its pin says
36
+ * it comes from, or is not on the trusted account, is logged and left out.
37
+ */
38
+ export declare function runnableImportHooks(deckDir: string, field: HookField, log: (message: string) => void): Promise<RunnableImportHook[]>;
39
+ /** The message `check` and `save-deck` refuse with. */
40
+ export declare function importChecksFailedMessage(errors: string[]): string;