castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  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 +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -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 +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. package/package.json +2 -2
@@ -0,0 +1,273 @@
1
+ // A deck's content pack: a data artifact an import exports about the deck built
2
+ // on it (castle.json `onPack`), for another deck's engine to mount by hash. The
3
+ // hub-game kit is the one that does today -- a hub game's client half as data
4
+ // -- but the CLI knows nothing of what a pack holds: it runs the import's
5
+ // exporter like an `onCheck`, then canonicalizes the JSON it wrote, hashes it,
6
+ // holds it to a size cap, stores it under `.castle/content-pack/<sha256>.json`
7
+ // and publishes it beside the server bundle.
8
+ //
9
+ // A pack's identity is the SHA-256 of its canonical bytes (object keys sorted,
10
+ // no whitespace), so the same content always has the same hash, whichever
11
+ // machine built it.
12
+ import { createHash, randomUUID } from 'crypto';
13
+ import * as fs from 'fs';
14
+ import * as path from 'path';
15
+ import { execHookModule, failureDetail, HOOK_RESULT_PREFIX, outputLines } from './importUpdateHook.js';
16
+ import { runnableImportHooks } from './importCheckHook.js';
17
+ import { readCastleJson } from './castleJson.js';
18
+ /** The most a pack may be, whatever its exporter allows. */
19
+ export const CONTENT_PACK_MAX_BYTES = 8 * 1024 * 1024;
20
+ const STORE_DIR = path.join('.castle', 'content-pack');
21
+ const STORE_KEEP = 12;
22
+ const SHA256 = /^[0-9a-f]{64}$/;
23
+ /**
24
+ * Build the deck's content pack, or null when no import exports one. Throws
25
+ * with the exporter's own errors when it refuses: a deck that cannot pack is a
26
+ * deck that does not build.
27
+ */
28
+ export async function buildContentPack(deckDir, log = (message) => console.log(message)) {
29
+ const exporters = await runnableImportHooks(deckDir, 'onPack', log);
30
+ if (exporters.length === 0)
31
+ return null;
32
+ if (exporters.length > 1) {
33
+ throw new Error(`Content pack: more than one import exports one (${exporters.map((e) => e.target.alias).join(', ')}).`);
34
+ }
35
+ const { target, modulePath } = exporters[0];
36
+ const store = path.join(deckDir, STORE_DIR);
37
+ fs.mkdirSync(store, { recursive: true });
38
+ const outFile = path.join(store, `.out-${randomUUID()}.json`);
39
+ try {
40
+ const context = {
41
+ deckDir,
42
+ importDir: target.importDir,
43
+ alias: target.alias,
44
+ self: target.pin === null,
45
+ outFile,
46
+ };
47
+ let output;
48
+ try {
49
+ output = await execHookModule(modulePath, context, deckDir, { reportResult: true });
50
+ }
51
+ catch (e) {
52
+ throw new Error(`Content pack: ${target.alias}'s exporter failed: ${failureDetail(e)}`);
53
+ }
54
+ const verdict = parseVerdict(output.stdout);
55
+ if (verdict.errors.length > 0) {
56
+ throw new Error([`Content pack refused by ${target.alias}:`, ...verdict.errors.map((e) => ` - ${e}`)].join('\n'));
57
+ }
58
+ let document;
59
+ try {
60
+ document = JSON.parse(fs.readFileSync(outFile, 'utf8'));
61
+ }
62
+ catch {
63
+ throw new Error(`Content pack: ${target.alias}'s exporter wrote no JSON pack.`);
64
+ }
65
+ const shape = document;
66
+ if (!shape || typeof shape !== 'object' || typeof shape.format !== 'string' || !Number.isInteger(shape.version)) {
67
+ throw new Error(`Content pack: ${target.alias}'s pack has no { format, version }.`);
68
+ }
69
+ const bytes = Buffer.from(canonicalJson(document), 'utf8');
70
+ if (bytes.byteLength > CONTENT_PACK_MAX_BYTES) {
71
+ throw new Error(`Content pack is ${(bytes.byteLength / 1048576).toFixed(1)} MB, over the ${CONTENT_PACK_MAX_BYTES / 1048576} MB cap.`);
72
+ }
73
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
74
+ const file = path.join(store, `${sha256}.json`);
75
+ if (!fs.existsSync(file))
76
+ fs.writeFileSync(file, bytes);
77
+ else
78
+ fs.utimesSync(file, new Date(), new Date());
79
+ pruneStore(store);
80
+ return { sha256, bytes, file, alias: target.alias, summary: verdict.summary };
81
+ }
82
+ finally {
83
+ fs.rmSync(outFile, { force: true });
84
+ }
85
+ }
86
+ /** A pack this deck built before, by hash, or null. */
87
+ export function readStoredContentPack(deckDir, sha256) {
88
+ if (!SHA256.test(sha256))
89
+ return null;
90
+ try {
91
+ return fs.readFileSync(path.join(deckDir, STORE_DIR, `${sha256}.json`));
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ /** JSON with every object's keys sorted and no whitespace. */
98
+ export function canonicalJson(value) {
99
+ return JSON.stringify(value, (_key, v) => {
100
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
101
+ const sorted = {};
102
+ for (const key of Object.keys(v).sort()) {
103
+ sorted[key] = v[key];
104
+ }
105
+ return sorted;
106
+ }
107
+ return v;
108
+ });
109
+ }
110
+ function parseVerdict(stdout) {
111
+ const line = outputLines(stdout)
112
+ .reverse()
113
+ .find((l) => l.startsWith(HOOK_RESULT_PREFIX));
114
+ let result;
115
+ try {
116
+ result = line ? JSON.parse(line.slice(HOOK_RESULT_PREFIX.length)) : null;
117
+ }
118
+ catch {
119
+ result = null;
120
+ }
121
+ const errors = result?.errors;
122
+ if (!result || !Array.isArray(errors) || errors.some((e) => typeof e !== 'string')) {
123
+ return { errors: ['its exporter did not return { errors: string[] }.'], summary: null };
124
+ }
125
+ return { errors: errors, summary: typeof result.summary === 'string' ? result.summary : null };
126
+ }
127
+ // The newest packs stay; a deck republished many times does not grow without end.
128
+ function pruneStore(store) {
129
+ const packs = fs
130
+ .readdirSync(store)
131
+ .filter((name) => /^[0-9a-f]{64}\.json$/.test(name))
132
+ .map((name) => ({ name, at: fs.statSync(path.join(store, name)).mtimeMs }))
133
+ .sort((a, b) => b.at - a.at);
134
+ for (const { name } of packs.slice(STORE_KEEP))
135
+ fs.rmSync(path.join(store, name), { force: true });
136
+ }
137
+ // --- On `castle-web serve`: other local decks' packs, for doors to them in dev ---
138
+ //
139
+ // A deck opts the decks beside it in by name: castle.json `devDecks`
140
+ // (`{ "dash": "../hub-dash" }`). A page can then ask the serve to resolve one
141
+ // (`GET /__castle/content-pack/resolve?deck=dash`): the serve builds that deck's
142
+ // pack with that deck's own exporter, and answers with its hash, where to fetch
143
+ // it, and the session key prefix that runs that deck's server
144
+ // (`deck:dash/<key>`, devSessionServer.ts) -- the shape a production host gets
145
+ // from Ghost, with the serve standing in. Only named decks are reachable, so a
146
+ // page cannot make the serve build or run anything its author did not list.
147
+ const DEV_DECK_NAME = /^[A-Za-z0-9_-]{1,40}$/;
148
+ const DEV_DECK_KEY = /^deck:([A-Za-z0-9_-]{1,40})\/(.+)$/;
149
+ /** The directory of a deck this deck lists in `devDecks`, or null. */
150
+ export function devDeckDir(projectDir, name) {
151
+ if (!DEV_DECK_NAME.test(name))
152
+ return null;
153
+ const declared = readCastleJson(projectDir)?.devDecks?.[name];
154
+ if (typeof declared !== 'string' || !declared.trim())
155
+ return null;
156
+ const dir = path.resolve(projectDir, declared);
157
+ return fs.existsSync(path.join(dir, 'castle.json')) && dir !== path.resolve(projectDir) ? dir : null;
158
+ }
159
+ /**
160
+ * The castle.json of every deck this deck lists in `devDecks`, by name: what a
161
+ * dev session's server is told about the decks its doors lead to, so a door
162
+ * can read the destination's own settings rather than repeat them. Decks that
163
+ * are missing or unreadable are left out.
164
+ */
165
+ export function devDeckCastleJsons(projectDir) {
166
+ const declared = readCastleJson(projectDir)?.devDecks;
167
+ const out = {};
168
+ if (!declared || typeof declared !== 'object')
169
+ return out;
170
+ for (const name of Object.keys(declared)) {
171
+ const dir = devDeckDir(projectDir, name);
172
+ const json = dir ? readCastleJson(dir) : null;
173
+ if (json)
174
+ out[name] = json;
175
+ }
176
+ return out;
177
+ }
178
+ /** `deck:<name>/<key>` -> the listed deck's directory and its own key, or null. */
179
+ export function devDeckSessionKey(projectDir, key) {
180
+ const match = key ? DEV_DECK_KEY.exec(key) : null;
181
+ const dir = match ? devDeckDir(projectDir, match[1]) : null;
182
+ return match && dir ? { name: match[1], dir, key: match[2] } : null;
183
+ }
184
+ // Packs this serve has handed out, by hash -> bytes, so a fetch reads only a
185
+ // pack the serve built, and a pinned one survives the store being pruned. A
186
+ // serve hands out few (one per destination edit), and the oldest go first.
187
+ const servedPacks = new Map();
188
+ const SERVED_PACKS_MAX = 32;
189
+ // The pack each destination session was first resolved with
190
+ // (`<deck>/<session key>` -> hash): a late joiner of a running instance gets
191
+ // the content that instance started with, not whatever is on disk now, the
192
+ // way a production session keeps its release.
193
+ const sessionPacks = new Map();
194
+ const SESSION_PACKS_MAX = 500;
195
+ // Drop the oldest packs no session is pinned to, down to the cap. A pinned
196
+ // one stays for as long as its pin does (SESSION_PACKS_MAX of them), and so
197
+ // does `current`, the pack about to be handed out.
198
+ function evictUnpinned(current) {
199
+ const pinned = new Set([...sessionPacks.values(), current]);
200
+ for (const sha of servedPacks.keys()) {
201
+ if (servedPacks.size <= SERVED_PACKS_MAX)
202
+ return;
203
+ if (!pinned.has(sha))
204
+ servedPacks.delete(sha);
205
+ }
206
+ }
207
+ /**
208
+ * The content-origin endpoints under `/__castle/content-pack/`. GET only; true
209
+ * when the request was one of them (answered), false to fall through.
210
+ */
211
+ export async function handleContentPackRequest(projectDir, req, res, reqPath) {
212
+ if (!reqPath.startsWith('/__castle/content-pack/'))
213
+ return false;
214
+ const json = (status, body) => res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify(body));
215
+ if (req.method !== 'GET') {
216
+ res.writeHead(405).end();
217
+ return true;
218
+ }
219
+ const file = /^\/__castle\/content-pack\/([0-9a-f]{64})\.json$/.exec(reqPath);
220
+ if (file) {
221
+ const bytes = servedPacks.get(file[1]) ?? null;
222
+ if (!bytes) {
223
+ res.writeHead(404).end();
224
+ return true;
225
+ }
226
+ res
227
+ .writeHead(200, { 'content-type': 'application/json', 'cache-control': 'public, max-age=31536000, immutable' })
228
+ .end(bytes);
229
+ return true;
230
+ }
231
+ if (reqPath === '/__castle/content-pack/resolve') {
232
+ const params = new URL(req.url ?? '', 'http://x').searchParams;
233
+ const name = params.get('deck') ?? '';
234
+ const sessionKey = `${name}/${params.get('key') ?? ''}`;
235
+ const dir = devDeckDir(projectDir, name);
236
+ if (!dir) {
237
+ json(404, { status: 'not_found', error: `this deck's castle.json lists no devDecks.${name}` });
238
+ return true;
239
+ }
240
+ try {
241
+ let sha256 = params.get('key') ? sessionPacks.get(sessionKey) : undefined;
242
+ if (!sha256 || !servedPacks.has(sha256)) {
243
+ const pack = await buildContentPack(dir, (line) => console.log(`[content-pack ${name}] ${line}`));
244
+ if (!pack) {
245
+ json(409, { status: 'unavailable', error: `${name} has no content pack exporter` });
246
+ return true;
247
+ }
248
+ servedPacks.delete(pack.sha256);
249
+ servedPacks.set(pack.sha256, pack.bytes);
250
+ sha256 = pack.sha256;
251
+ if (params.get('key')) {
252
+ sessionPacks.set(sessionKey, sha256);
253
+ if (sessionPacks.size > SESSION_PACKS_MAX)
254
+ sessionPacks.delete(sessionPacks.keys().next().value);
255
+ }
256
+ evictUnpinned(sha256);
257
+ }
258
+ json(200, {
259
+ status: 'ok',
260
+ sha256,
261
+ url: `/__castle/content-pack/${sha256}.json`,
262
+ sessionKeyPrefix: `deck:${name}/`,
263
+ deckId: readCastleJson(dir)?.deckId ?? null,
264
+ });
265
+ }
266
+ catch (e) {
267
+ json(422, { status: 'refused', error: e instanceof Error ? e.message : String(e) });
268
+ }
269
+ return true;
270
+ }
271
+ res.writeHead(404).end();
272
+ return true;
273
+ }
@@ -0,0 +1,21 @@
1
+ export declare class DevExperiments {
2
+ private readonly projectDir;
3
+ private readonly log;
4
+ private readonly overrides;
5
+ private readonly pages;
6
+ private lastWarning;
7
+ constructor(projectDir: string, log?: (text: string) => void);
8
+ /** Takes the `experiment.<name>` overrides out of a requested URL. */
9
+ noteUrl(url: string | undefined): void;
10
+ /** `{ name: variant }` for one player: what a host hands the deck and its server. */
11
+ variantsFor(userId: string, deckId: string | null): Record<string, string>;
12
+ /**
13
+ * The arms of one page load, resolved the first time the page asks anything
14
+ * and the same from then on: the deck's SDK keeps its first answer, so the
15
+ * map handed to the deck's server at a later join has to be that one too. An
16
+ * override taken afterwards shows on the next page load. `page` is null for
17
+ * a caller that names none, which is resolved afresh.
18
+ */
19
+ variantsForPage(page: string | null, userId: string, deckId: string | null): Record<string, string>;
20
+ private read;
21
+ }
@@ -0,0 +1,139 @@
1
+ // A/B experiments on the dev serve. Published, Castle's server resolves a
2
+ // player's variants once per deck load; here the serve does, from the folder's
3
+ // castle.json, with the same assignment function (experimentAssignment.ts):
4
+ //
5
+ // "experiments": { "tutorial_length": { "variants": ["short", "long"] } }
6
+ // "devExperiments": { "hub_avatar_style": "blocky" }
7
+ //
8
+ // `experiments` are the deck's own, assigned to the dev user as they would be
9
+ // once published. `devExperiments` stands in for experiments Castle runs across
10
+ // decks, which no local folder declares: each name simply answers its variant.
11
+ //
12
+ // `?experiment.<name>=<variant>` on any page of the serve forces an arm, for a
13
+ // declared experiment and one of its variants or for a `devExperiments` name.
14
+ // It holds for every page and local multiplayer session of this serve until
15
+ // `?experiment.<name>=` clears it or the serve stops; nothing published reads it.
16
+ // A page load keeps the arms it first read (`variantsForPage`), so a page and
17
+ // the session it joins never disagree; an override shows on the next load.
18
+ import { isPlatformExperimentName, readCastleJson, readDevExperiments, validateExperiments, } from './castleJson.js';
19
+ import { assignExperimentVariant } from './experimentAssignment.js';
20
+ const OVERRIDE_PREFIX = 'experiment.';
21
+ // The deck id a deck is assigned under before its first save gives it one.
22
+ const UNSAVED_DECK_ID = 'dev';
23
+ // Page loads whose arms are remembered; past this the one idle longest is forgotten.
24
+ const PAGE_LOADS_CAP = 1024;
25
+ export class DevExperiments {
26
+ projectDir;
27
+ log;
28
+ overrides = new Map();
29
+ pages = new Map();
30
+ lastWarning = null;
31
+ constructor(projectDir, log = () => { }) {
32
+ this.projectDir = projectDir;
33
+ this.log = log;
34
+ }
35
+ /** Takes the `experiment.<name>` overrides out of a requested URL. */
36
+ noteUrl(url) {
37
+ if (!url || !url.includes(OVERRIDE_PREFIX))
38
+ return;
39
+ let params;
40
+ try {
41
+ params = new URL(url, 'http://localhost').searchParams;
42
+ }
43
+ catch {
44
+ return;
45
+ }
46
+ const { declared, platform } = this.read();
47
+ for (const [key, variant] of params) {
48
+ if (!key.startsWith(OVERRIDE_PREFIX))
49
+ continue;
50
+ const name = key.slice(OVERRIDE_PREFIX.length);
51
+ if (variant === '') {
52
+ if (this.overrides.delete(name))
53
+ this.log(`${name} is no longer forced`);
54
+ continue;
55
+ }
56
+ const refusal = overrideRefusal(name, variant, declared, platform);
57
+ if (refusal) {
58
+ this.log(`?${key}=${variant} ignored: ${refusal}`);
59
+ continue;
60
+ }
61
+ if (this.overrides.get(name) !== variant) {
62
+ this.overrides.set(name, variant);
63
+ this.log(`${name} forced to "${variant}" until ?${key}= clears it or the serve stops`);
64
+ }
65
+ }
66
+ }
67
+ /** `{ name: variant }` for one player: what a host hands the deck and its server. */
68
+ variantsFor(userId, deckId) {
69
+ const { declared, platform } = this.read();
70
+ const variants = new Map();
71
+ for (const [name, config] of Object.entries(declared)) {
72
+ variants.set(name, assignExperimentVariant(userId, deckId ?? UNSAVED_DECK_ID, name, config));
73
+ }
74
+ // As on Castle's server: a name an experiment of Castle's holds is Castle's alone.
75
+ for (const [name, variant] of Object.entries(platform))
76
+ variants.set(name, variant);
77
+ for (const [name, variant] of this.overrides) {
78
+ // castle.json may have changed since the override was taken.
79
+ if (!overrideRefusal(name, variant, declared, platform))
80
+ variants.set(name, variant);
81
+ }
82
+ return Object.fromEntries(variants);
83
+ }
84
+ /**
85
+ * The arms of one page load, resolved the first time the page asks anything
86
+ * and the same from then on: the deck's SDK keeps its first answer, so the
87
+ * map handed to the deck's server at a later join has to be that one too. An
88
+ * override taken afterwards shows on the next page load. `page` is null for
89
+ * a caller that names none, which is resolved afresh.
90
+ */
91
+ variantsForPage(page, userId, deckId) {
92
+ if (page === null)
93
+ return this.variantsFor(userId, deckId);
94
+ let variants = this.pages.get(page);
95
+ if (variants) {
96
+ // Moved to the newest end: the cap drops the page that has gone longest
97
+ // without sending a command, never one still in use.
98
+ this.pages.delete(page);
99
+ }
100
+ else {
101
+ variants = this.variantsFor(userId, deckId);
102
+ }
103
+ this.pages.set(page, variants);
104
+ if (this.pages.size > PAGE_LOADS_CAP) {
105
+ this.pages.delete(this.pages.keys().next().value);
106
+ }
107
+ return variants;
108
+ }
109
+ read() {
110
+ const castleJson = readCastleJson(this.projectDir);
111
+ const warnings = [];
112
+ let declared = {};
113
+ try {
114
+ declared = validateExperiments(castleJson?.experiments) ?? {};
115
+ }
116
+ catch (error) {
117
+ warnings.push(`castle.json ${error instanceof Error ? error.message : String(error)} No experiment is assigned until it is fixed.`);
118
+ }
119
+ const platform = readDevExperiments(castleJson?.devExperiments, (text) => warnings.push(text));
120
+ // Read on every command, so a standing problem is reported once, not per call.
121
+ const warning = warnings.join('\n');
122
+ if (warning && warning !== this.lastWarning)
123
+ this.log(warning);
124
+ this.lastWarning = warning || null;
125
+ return { declared, platform };
126
+ }
127
+ }
128
+ function overrideRefusal(name, variant, declared, platform) {
129
+ if (Object.hasOwn(platform, name)) {
130
+ return isPlatformExperimentName(variant) ? null : `"${variant}" is not a variant name`;
131
+ }
132
+ const config = Object.hasOwn(declared, name) ? declared[name] : undefined;
133
+ if (config) {
134
+ return config.variants.includes(variant)
135
+ ? null
136
+ : `"${variant}" is not a variant of ${name} (${config.variants.join(', ')})`;
137
+ }
138
+ return `castle.json declares no experiment named "${name}" (experiments or devExperiments)`;
139
+ }
@@ -0,0 +1,55 @@
1
+ import type { HostContext, HostHub, HubCancelResult, HubCommitResult, HubDoorsResult, HubHandoffResult } from './castle-host/host.js';
2
+ export interface DevHubDoorRow {
3
+ from: string;
4
+ doorId: string;
5
+ to: string;
6
+ placementKind: 'layer' | 'pad' | 'exact';
7
+ placement: {
8
+ key?: string;
9
+ };
10
+ launcherKind: string;
11
+ padSize: number | null;
12
+ enabled: boolean;
13
+ featured: boolean;
14
+ }
15
+ export interface DevHubSessions {
16
+ /** The local WebSocket URL, or null when multiplayer is not running. */
17
+ url(): string | null;
18
+ mintNonce(ctx: HostContext, key: string | null): string;
19
+ sessionIdFor(key: string | null): string;
20
+ }
21
+ export declare function readDevHubDoors(projectDir: string, log?: (text: string) => void): DevHubDoorRow[];
22
+ /** The place a session key is: `hub.<place>.<n>`, else the deck's main place. */
23
+ export declare function devPlaceOf(key: string | null): string;
24
+ export interface DevPadGroups {
25
+ get(id: string): {
26
+ key: string;
27
+ openedAt: number;
28
+ members: number;
29
+ } | undefined;
30
+ set(id: string, group: {
31
+ key: string;
32
+ openedAt: number;
33
+ members: number;
34
+ }): void;
35
+ }
36
+ export declare class DevHubVisit implements HostHub {
37
+ private readonly rows;
38
+ private readonly sessions;
39
+ private readonly pads;
40
+ private readonly now;
41
+ private readonly random;
42
+ private key;
43
+ private joined;
44
+ private pending;
45
+ private readonly trail;
46
+ constructor(rows: () => DevHubDoorRow[], sessions: DevHubSessions, pads: DevPadGroups, now?: () => number, random?: () => string);
47
+ sessionAcquired(sessionId: string): void;
48
+ doors(): Promise<HubDoorsResult>;
49
+ go(doorId: string, ctx: HostContext): Promise<HubHandoffResult>;
50
+ back(ctx: HostContext): Promise<HubHandoffResult>;
51
+ commit(nonce: string): Promise<HubCommitResult>;
52
+ cancel(nonce: string | null): Promise<HubCancelResult>;
53
+ private acquire;
54
+ private destinationKey;
55
+ }
package/dist/devHub.js ADDED
@@ -0,0 +1,187 @@
1
+ // Hub doors on the dev serve. Production doors are rows in ghost's door table
2
+ // and lead between decks; a deck being developed locally runs every place it
3
+ // has as a named session of itself, so its door rows are a fixture in
4
+ // castle.json and each one leads to a session whose named key names the place,
5
+ // `hub.<place>.<instance>` (the key a hub kit reads its place from on
6
+ // `castle-web serve`). The public session is the deck's main place.
7
+ //
8
+ // "devHubDoors": [
9
+ // { "from": "main", "doorId": "race", "to": "race", "placementKind": "pad", "padSize": 4 },
10
+ // { "from": "main", "doorId": "inn", "to": "inn", "placementKind": "exact", "placement": { "key": "inn" } },
11
+ // { "from": "race", "doorId": "to-arena", "to": "arena", "placementKind": "layer" }
12
+ // ]
13
+ //
14
+ // One DevHubVisit per page playing the deck (each Play panel, each browser
15
+ // tab): the place it is in, its pending trip and its way back, the same state a
16
+ // web or app host keeps with ghost. A pad's players arrive together because the
17
+ // door is used by all of them within moments of the pad firing; the first one
18
+ // opens an instance and the rest of the window joins it.
19
+ import * as fs from 'node:fs';
20
+ import * as path from 'node:path';
21
+ const MAIN_PLACE = 'main';
22
+ const PLACE_ID = /^[a-z][a-z0-9-]{0,23}$/;
23
+ const DOOR_ID = /^[A-Za-z0-9_.:-]{1,64}$/;
24
+ const DEV_KEY = /^hub\.([a-z][a-z0-9-]{0,23})\.[A-Za-z0-9-]{1,40}$/;
25
+ // How long after a pad's first player the rest of it still lands in the same
26
+ // instance.
27
+ const PAD_GATHER_MS = 5000;
28
+ const TRAIL_MAX = 4;
29
+ export function readDevHubDoors(projectDir, log) {
30
+ let raw;
31
+ try {
32
+ raw = JSON.parse(fs.readFileSync(path.join(projectDir, 'castle.json'), 'utf8'))
33
+ .devHubDoors;
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ if (raw === undefined)
39
+ return [];
40
+ if (!Array.isArray(raw)) {
41
+ log?.('castle.json devHubDoors must be an array of door rows');
42
+ return [];
43
+ }
44
+ return raw.flatMap((entry, index) => {
45
+ const row = devHubDoorRow(entry);
46
+ if (!row)
47
+ log?.(`castle.json devHubDoors[${index}] is not a door row; it is ignored`);
48
+ return row ? [row] : [];
49
+ });
50
+ }
51
+ function devHubDoorRow(entry) {
52
+ if (!entry || typeof entry !== 'object')
53
+ return null;
54
+ const e = entry;
55
+ const kind = e.placementKind ?? 'layer';
56
+ const placement = (e.placement && typeof e.placement === 'object' ? e.placement : {});
57
+ if (typeof e.from !== 'string' ||
58
+ !PLACE_ID.test(e.from) ||
59
+ typeof e.to !== 'string' ||
60
+ !PLACE_ID.test(e.to) ||
61
+ typeof e.doorId !== 'string' ||
62
+ !DOOR_ID.test(e.doorId) ||
63
+ (kind !== 'layer' && kind !== 'pad' && kind !== 'exact') ||
64
+ (kind === 'exact' && (typeof placement.key !== 'string' || !/^[A-Za-z0-9-]{1,40}$/.test(placement.key)))) {
65
+ return null;
66
+ }
67
+ return {
68
+ from: e.from,
69
+ doorId: e.doorId,
70
+ to: e.to,
71
+ placementKind: kind,
72
+ placement: kind === 'exact' ? { key: placement.key } : {},
73
+ launcherKind: typeof e.launcherKind === 'string' ? e.launcherKind : 'door',
74
+ padSize: kind === 'pad' && Number.isInteger(e.padSize) && e.padSize > 0 ? e.padSize : kind === 'pad' ? 4 : null,
75
+ enabled: e.enabled !== false,
76
+ featured: e.featured === true,
77
+ };
78
+ }
79
+ /** The place a session key is: `hub.<place>.<n>`, else the deck's main place. */
80
+ export function devPlaceOf(key) {
81
+ return (key && DEV_KEY.exec(key)?.[1]) ?? MAIN_PLACE;
82
+ }
83
+ export class DevHubVisit {
84
+ rows;
85
+ sessions;
86
+ pads;
87
+ now;
88
+ random;
89
+ key = null;
90
+ joined = false;
91
+ pending = null;
92
+ trail = [];
93
+ constructor(rows, sessions, pads, now = () => Date.now(), random = () => Math.random().toString(36).slice(2, 10)) {
94
+ this.rows = rows;
95
+ this.sessions = sessions;
96
+ this.pads = pads;
97
+ this.now = now;
98
+ this.random = random;
99
+ }
100
+ sessionAcquired(sessionId) {
101
+ const local = this.sessions.sessionIdFor(null);
102
+ this.key = sessionId === local ? null : sessionId.startsWith(`${local}:`) ? sessionId.slice(local.length + 1) : this.key;
103
+ this.joined = true;
104
+ }
105
+ doors() {
106
+ const place = devPlaceOf(this.key);
107
+ return Promise.resolve({
108
+ status: 'ok',
109
+ doors: this.rows()
110
+ .filter((row) => row.from === place)
111
+ .map((row) => ({
112
+ doorId: row.doorId,
113
+ launcherKind: row.launcherKind,
114
+ placementKind: row.placementKind,
115
+ placement: row.placement,
116
+ padSize: row.padSize,
117
+ enabled: row.enabled,
118
+ featured: row.featured,
119
+ status: { playersInside: 0, friendsInside: 0 },
120
+ })),
121
+ });
122
+ }
123
+ go(doorId, ctx) {
124
+ if (!this.joined)
125
+ return Promise.resolve(failure('forbidden'));
126
+ const place = devPlaceOf(this.key);
127
+ const row = this.rows().find((r) => r.from === place && r.doorId === doorId);
128
+ if (!row || !row.enabled)
129
+ return Promise.resolve(failure(row ? 'unavailable' : 'not_found'));
130
+ return Promise.resolve(this.acquire('go', this.destinationKey(row), ctx));
131
+ }
132
+ back(ctx) {
133
+ if (this.trail.length === 0)
134
+ return Promise.resolve(failure('not_found'));
135
+ return Promise.resolve(this.acquire('back', this.trail[this.trail.length - 1], ctx));
136
+ }
137
+ commit(nonce) {
138
+ const trip = this.pending;
139
+ if (!trip || trip.nonce !== nonce)
140
+ return Promise.resolve({ status: 'none' });
141
+ this.pending = null;
142
+ if (trip.kind === 'go') {
143
+ this.trail.push(this.key);
144
+ if (this.trail.length > TRAIL_MAX)
145
+ this.trail.shift();
146
+ }
147
+ else {
148
+ this.trail.pop();
149
+ }
150
+ this.key = trip.key;
151
+ return Promise.resolve({ status: 'committed' });
152
+ }
153
+ cancel(nonce) {
154
+ const trip = this.pending;
155
+ if (!trip || (nonce !== null && trip.nonce !== nonce))
156
+ return Promise.resolve({ status: 'none' });
157
+ this.pending = null;
158
+ return Promise.resolve({ status: 'cancelled' });
159
+ }
160
+ acquire(kind, key, ctx) {
161
+ const url = this.sessions.url();
162
+ if (!url)
163
+ return failure('unavailable');
164
+ const nonce = this.sessions.mintNonce(ctx, key);
165
+ this.pending = { kind, key, nonce };
166
+ return { status: 'ok', url, nonce, sessionId: this.sessions.sessionIdFor(key), bundleHash: 'dev', contentUrl: null };
167
+ }
168
+ destinationKey(row) {
169
+ if (row.placementKind === 'exact')
170
+ return `hub.${row.to}.${row.placement.key}`;
171
+ if (row.placementKind === 'layer')
172
+ return row.to === MAIN_PLACE ? null : `hub.${row.to}.layer`;
173
+ const id = `${this.key ?? ''}|${row.doorId}`;
174
+ const group = this.pads.get(id);
175
+ const now = this.now();
176
+ if (group && now - group.openedAt < PAD_GATHER_MS && group.members < (row.padSize ?? 1)) {
177
+ group.members += 1;
178
+ return group.key;
179
+ }
180
+ const key = `hub.${row.to}.${this.random()}`;
181
+ this.pads.set(id, { key, openedAt: now, members: 1 });
182
+ return key;
183
+ }
184
+ }
185
+ function failure(status) {
186
+ return { status, url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null };
187
+ }