castle-web-cli 0.4.239 → 0.4.240

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 (386) hide show
  1. package/dist/agent.js +5 -1
  2. package/dist/api.d.ts +20 -0
  3. package/dist/api.js +57 -0
  4. package/dist/bundle.d.ts +38 -1
  5. package/dist/bundle.js +309 -13
  6. package/dist/castle-host/host.js +163 -11
  7. package/dist/castleJson.d.ts +10 -0
  8. package/dist/castleJson.js +46 -2
  9. package/dist/check.js +5 -2
  10. package/dist/devSessionServer.js +4 -1
  11. package/dist/devSessionStorage.d.ts +1 -0
  12. package/dist/devSessionStorage.js +32 -7
  13. package/dist/importOrder.d.ts +2 -0
  14. package/dist/importOrder.js +29 -0
  15. package/dist/index.js +6 -3
  16. package/dist/init.js +24 -2
  17. package/dist/platformDoc.js +2 -1
  18. package/dist/playPagePolicy.js +5 -1
  19. package/dist/resetLeaderboards.d.ts +8 -1
  20. package/dist/resetLeaderboards.js +43 -8
  21. package/dist/save-deck.d.ts +32 -2
  22. package/dist/save-deck.js +240 -39
  23. package/kits/base/CLAUDE.md +1 -1
  24. package/kits/base/castle.json +1 -1
  25. package/kits/base/sdk/README.md +174 -6
  26. package/kits/base/sdk/analytics.d.ts +8 -0
  27. package/kits/base/sdk/analytics.js +92 -0
  28. package/kits/base/sdk/castle.d.ts +5 -1
  29. package/kits/base/sdk/castle.js +2 -0
  30. package/kits/base/sdk/commands.d.ts +48 -0
  31. package/kits/base/sdk/commands.js +1 -0
  32. package/kits/base/sdk/debugConsole.d.ts +17 -0
  33. package/kits/base/sdk/debugConsole.js +154 -0
  34. package/kits/base/sdk/experiments.js +24 -1
  35. package/kits/base/sdk/hostRetry.d.ts +7 -0
  36. package/kits/base/sdk/hostRetry.js +57 -0
  37. package/kits/base/sdk/hub.d.ts +20 -2
  38. package/kits/base/sdk/hub.js +99 -13
  39. package/kits/base/sdk/multiplayer.d.ts +2 -0
  40. package/kits/base/sdk/multiplayer.js +168 -26
  41. package/kits/base/sdk/reconnectBudget.d.ts +6 -0
  42. package/kits/base/sdk/reconnectBudget.js +41 -1
  43. package/kits/base/sdk/runtime.js +36 -19
  44. package/kits/base/sdk/server/hub.d.ts +19 -0
  45. package/kits/base/sdk/server/hub.js +12 -0
  46. package/kits/base/sdk/server/platformHandle.d.ts +1 -0
  47. package/kits/base/sdk/server/wrapper.d.ts +1 -1
  48. package/kits/base/sdk/server/wrapper.js +26 -1
  49. package/kits/base/sdk/transport.d.ts +2 -1
  50. package/kits/base/sdk/transport.js +35 -0
  51. package/kits/hub-game/CLAUDE.md +66 -19
  52. package/kits/hub-game/code/client/act.js +9 -6
  53. package/kits/hub-game/code/client/actCore.js +26 -6
  54. package/kits/hub-game/code/client/actGateLog.js +36 -0
  55. package/kits/hub-game/code/client/actionOverflow.js +29 -8
  56. package/kits/hub-game/code/client/actionRailSurface.js +186 -0
  57. package/kits/hub-game/code/client/actionRailTree.js +173 -0
  58. package/kits/hub-game/code/client/askSurface.js +85 -0
  59. package/kits/hub-game/code/client/askTree.js +51 -0
  60. package/kits/hub-game/code/client/attention.js +31 -6
  61. package/kits/hub-game/code/client/ballot.js +42 -5
  62. package/kits/hub-game/code/client/ballotSurface.js +115 -0
  63. package/kits/hub-game/code/client/ballotTree.js +180 -0
  64. package/kits/hub-game/code/client/catchingUp.js +19 -0
  65. package/kits/hub-game/code/client/celebrate.js +66 -0
  66. package/kits/hub-game/code/client/chrome.js +473 -53
  67. package/kits/hub-game/code/client/companion.js +93 -23
  68. package/kits/hub-game/code/client/companionDress.js +1 -1
  69. package/kits/hub-game/code/client/cornerSurface.js +106 -0
  70. package/kits/hub-game/code/client/cornerTree.js +83 -0
  71. package/kits/hub-game/code/client/decor.js +20 -11
  72. package/kits/hub-game/code/client/deviceStorage.js +121 -0
  73. package/kits/hub-game/code/client/disguise.js +23 -0
  74. package/kits/hub-game/code/client/disguiseDraw.js +87 -0
  75. package/kits/hub-game/code/client/dockSurface.js +206 -0
  76. package/kits/hub-game/code/client/dockTree.js +232 -0
  77. package/kits/hub-game/code/client/earned.js +29 -0
  78. package/kits/hub-game/code/client/emoteSurface.js +188 -0
  79. package/kits/hub-game/code/client/emoteTree.js +264 -0
  80. package/kits/hub-game/code/client/farAvatars.js +4 -3
  81. package/kits/hub-game/code/client/fpsTelemetry.js +3 -1
  82. package/kits/hub-game/code/client/grab.js +121 -50
  83. package/kits/hub-game/code/client/holdShow.js +19 -0
  84. package/kits/hub-game/code/client/hookLayer.js +96 -12
  85. package/kits/hub-game/code/client/hubControls.js +7 -1
  86. package/kits/hub-game/code/client/hudSurface.js +11 -3
  87. package/kits/hub-game/code/client/hudTree.js +7 -4
  88. package/kits/hub-game/code/client/idle.js +21 -3
  89. package/kits/hub-game/code/client/invites.js +24 -3
  90. package/kits/hub-game/code/client/keys.js +15 -0
  91. package/kits/hub-game/code/client/labelsNear.js +8 -1
  92. package/kits/hub-game/code/client/layoutCache.js +57 -8
  93. package/kits/hub-game/code/client/loadingCover.js +53 -4
  94. package/kits/hub-game/code/client/menuIcons.js +15 -0
  95. package/kits/hub-game/code/client/menuSurface.js +102 -0
  96. package/kits/hub-game/code/client/menuTree.js +135 -0
  97. package/kits/hub-game/code/client/modelLook.js +41 -0
  98. package/kits/hub-game/code/client/pickerSurface.js +152 -0
  99. package/kits/hub-game/code/client/pickerTree.js +163 -0
  100. package/kits/hub-game/code/client/pushVisit.js +4 -2
  101. package/kits/hub-game/code/client/quality.js +188 -29
  102. package/kits/hub-game/code/client/qualityEntry.js +10 -1
  103. package/kits/hub-game/code/client/quickChatSurface.js +222 -0
  104. package/kits/hub-game/code/client/quickChatTree.js +201 -0
  105. package/kits/hub-game/code/client/rehello.js +75 -0
  106. package/kits/hub-game/code/client/renderVisibility.js +17 -0
  107. package/kits/hub-game/code/client/replay.js +118 -0
  108. package/kits/hub-game/code/client/role.js +3 -0
  109. package/kits/hub-game/code/client/safeLayout.js +441 -56
  110. package/kits/hub-game/code/client/safeStyle.js +13 -10
  111. package/kits/hub-game/code/client/say.js +2 -0
  112. package/kits/hub-game/code/client/soundSurface.js +77 -0
  113. package/kits/hub-game/code/client/soundTree.js +74 -0
  114. package/kits/hub-game/code/client/soundscape.js +12 -9
  115. package/kits/hub-game/code/client/soundscapeCues.js +1 -1
  116. package/kits/hub-game/code/client/state.js +67 -1
  117. package/kits/hub-game/code/client/stuckSurface.js +76 -0
  118. package/kits/hub-game/code/client/stuckTree.js +67 -0
  119. package/kits/hub-game/code/client/talk.js +42 -12
  120. package/kits/hub-game/code/client/talkTree.js +4 -2
  121. package/kits/hub-game/code/client/textAskSurface.js +147 -0
  122. package/kits/hub-game/code/client/textAskTree.js +67 -0
  123. package/kits/hub-game/code/client/tiers.js +252 -27
  124. package/kits/hub-game/code/client/together.js +4 -1
  125. package/kits/hub-game/code/client/uiDom.js +86 -8
  126. package/kits/hub-game/code/client/uiTree.js +33 -4
  127. package/kits/hub-game/code/client/vehicle.js +72 -51
  128. package/kits/hub-game/code/client/weakestTier.js +75 -31
  129. package/kits/hub-game/code/client/wear.js +159 -5
  130. package/kits/hub-game/code/client/worldLabels.js +205 -25
  131. package/kits/hub-game/code/companionSpec.js +4 -2
  132. package/kits/hub-game/code/server/act.js +3 -0
  133. package/kits/hub-game/code/server/actGate.js +83 -0
  134. package/kits/hub-game/code/server/actions.js +71 -15
  135. package/kits/hub-game/code/server/actors.js +20 -5
  136. package/kits/hub-game/code/server/analytics.js +35 -3
  137. package/kits/hub-game/code/server/ask.js +39 -3
  138. package/kits/hub-game/code/server/ballot.js +167 -4
  139. package/kits/hub-game/code/server/celebrate.js +64 -0
  140. package/kits/hub-game/code/server/companion.js +17 -2
  141. package/kits/hub-game/code/server/decor.js +11 -2
  142. package/kits/hub-game/code/server/disguise.js +63 -0
  143. package/kits/hub-game/code/server/earned.js +6 -2
  144. package/kits/hub-game/code/server/friendBests.js +13 -4
  145. package/kits/hub-game/code/server/friendsAmong.js +67 -8
  146. package/kits/hub-game/code/server/grab.js +12 -2
  147. package/kits/hub-game/code/server/heldOffers.js +142 -0
  148. package/kits/hub-game/code/server/holdShow.js +98 -0
  149. package/kits/hub-game/code/server/hub.js +851 -45
  150. package/kits/hub-game/code/server/idle.js +110 -9
  151. package/kits/hub-game/code/server/index.js +9 -0
  152. package/kits/hub-game/code/server/labels.js +13 -3
  153. package/kits/hub-game/code/server/manifest.js +94 -6
  154. package/kits/hub-game/code/server/menu.js +26 -3
  155. package/kits/hub-game/code/server/npcs.js +55 -9
  156. package/kits/hub-game/code/server/observe.js +67 -6
  157. package/kits/hub-game/code/server/players.js +8 -1
  158. package/kits/hub-game/code/server/replay.js +135 -0
  159. package/kits/hub-game/code/server/storageLimit.js +4 -1
  160. package/kits/hub-game/code/server/townDay.js +74 -0
  161. package/kits/hub-game/code/server/vehicle.js +3 -0
  162. package/kits/hub-game/code/server/vis.js +26 -4
  163. package/kits/hub-game/code/server/wallet.js +677 -0
  164. package/kits/hub-game/code/server/wear.js +13 -3
  165. package/kits/hub-game/code/server/writerLease.js +191 -0
  166. package/kits/hub-game/code/shared/act.js +1 -1
  167. package/kits/hub-game/code/shared/expression.js +6 -0
  168. package/kits/hub-game/code/shared/replay.js +37 -0
  169. package/kits/hub-game/code/systems/hub.js +427 -54
  170. package/kits/hub-game/docs/analytics.md +16 -2
  171. package/kits/hub-game/docs/contract.md +942 -99
  172. package/kits/hub-game/docs/home-pieces.md +5 -6
  173. package/kits/hub-game/docs/observed-progress.md +49 -1
  174. package/kits/hub-game/docs/vehicle-preset.md +23 -0
  175. package/kits/hub-game/index.html +1 -0
  176. package/kits/hub-game/models/hats/baker-cap.pxmodel +3 -3
  177. package/kits/hub-game/models/hats/bat-clip.pxmodel +3 -3
  178. package/kits/hub-game/models/hats/beekeeper.pxmodel +3 -3
  179. package/kits/hub-game/models/hats/cap.pxmodel +3 -3
  180. package/kits/hub-game/models/hats/captain.pxmodel +3 -3
  181. package/kits/hub-game/models/hats/chef-toque.pxmodel +3 -3
  182. package/kits/hub-game/models/hats/crooked-top.pxmodel +3 -3
  183. package/kits/hub-game/models/hats/delivery-cap.pxmodel +3 -3
  184. package/kits/hub-game/models/hats/fire-helmet.pxmodel +3 -3
  185. package/kits/hub-game/models/hats/flower-crown.pxmodel +3 -3
  186. package/kits/hub-game/models/hats/foam-crown.pxmodel +3 -3
  187. package/kits/hub-game/models/hats/hard-hat.pxmodel +3 -3
  188. package/kits/hub-game/models/hats/lantern.pxmodel +3 -3
  189. package/kits/hub-game/models/hats/laurel.pxmodel +3 -3
  190. package/kits/hub-game/models/hats/lighthouse.pxmodel +3 -3
  191. package/kits/hub-game/models/hats/nurse-cap.pxmodel +3 -3
  192. package/kits/hub-game/models/hats/police-cap.pxmodel +3 -3
  193. package/kits/hub-game/models/hats/sailor.pxmodel +3 -3
  194. package/kits/hub-game/models/hats/souwester.pxmodel +3 -3
  195. package/kits/hub-game/models/hats/straw.pxmodel +3 -3
  196. package/kits/hub-game/models/hats/sunflower.pxmodel +3 -3
  197. package/kits/hub-game/models/hats/sweatband.pxmodel +3 -3
  198. package/kits/hub-game/models/hats/teacher-beret.pxmodel +3 -3
  199. package/kits/hub-game/models/hats/witch.pxmodel +3 -3
  200. package/kits/hub-game/models/hold-show/daisy.pxmodel +231 -0
  201. package/kits/hub-game/models/hold-show/moonflower.pxmodel +171 -0
  202. package/kits/hub-game/models/hold-show/rose.pxmodel +191 -0
  203. package/kits/hub-game/models/hold-show/square/daisy.pxmodel +233 -0
  204. package/kits/hub-game/models/hold-show/square/moonflower.pxmodel +173 -0
  205. package/kits/hub-game/models/hold-show/square/rose.pxmodel +193 -0
  206. package/kits/hub-game/models/hold-show/square/sunflower.pxmodel +313 -0
  207. package/kits/hub-game/models/hold-show/square/tulip.pxmodel +133 -0
  208. package/kits/hub-game/models/hold-show/sunflower.pxmodel +311 -0
  209. package/kits/hub-game/models/hold-show/tulip.pxmodel +131 -0
  210. package/kits/hub-game/package-lock.json +3 -3
  211. package/kits/hub-game/package.json +4 -3
  212. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +1 -0
  213. package/kits/hub-game/scripts/fixtures/hud-surface.json +12 -12
  214. package/kits/hub-game/scripts/fixtures/talk-surface.json +8 -8
  215. package/kits/hub-game/scripts/gen-hats.mjs +1 -1
  216. package/kits/hub-game/scripts/gen-hold-show.mjs +27 -0
  217. package/kits/hub-game/scripts/pack.mjs +89 -23
  218. package/kits/hub-game/scripts/test-act-client.mjs +5 -0
  219. package/kits/hub-game/scripts/test-act-core.mjs +32 -0
  220. package/kits/hub-game/scripts/test-act-gate.mjs +186 -0
  221. package/kits/hub-game/scripts/test-action-rail-crowded-dom.mjs +7 -1
  222. package/kits/hub-game/scripts/test-action-rail-default-dom.mjs +102 -0
  223. package/kits/hub-game/scripts/test-action-rail-never-silent-dom.mjs +50 -0
  224. package/kits/hub-game/scripts/test-action-rail-surface.mjs +368 -0
  225. package/kits/hub-game/scripts/test-action-rail-town-jobs-dom.mjs +118 -0
  226. package/kits/hub-game/scripts/test-actions-client.mjs +5 -3
  227. package/kits/hub-game/scripts/test-actions.mjs +24 -0
  228. package/kits/hub-game/scripts/test-actors.mjs +19 -0
  229. package/kits/hub-game/scripts/test-again-corner-dom.mjs +59 -0
  230. package/kits/hub-game/scripts/test-analytics.mjs +79 -0
  231. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +25 -8
  232. package/kits/hub-game/scripts/test-ask-client.mjs +9 -0
  233. package/kits/hub-game/scripts/test-ask-surface.mjs +188 -0
  234. package/kits/hub-game/scripts/test-attention.mjs +43 -1
  235. package/kits/hub-game/scripts/test-ballot-sheet-dom.mjs +71 -0
  236. package/kits/hub-game/scripts/test-ballot-surface.mjs +276 -0
  237. package/kits/hub-game/scripts/test-ballot.mjs +420 -3
  238. package/kits/hub-game/scripts/test-ban-join.mjs +1 -1
  239. package/kits/hub-game/scripts/test-celebrate-client.mjs +62 -0
  240. package/kits/hub-game/scripts/test-celebrate.mjs +116 -0
  241. package/kits/hub-game/scripts/test-chat.mjs +73 -0
  242. package/kits/hub-game/scripts/test-companion-client.mjs +203 -21
  243. package/kits/hub-game/scripts/test-companion.mjs +110 -3
  244. package/kits/hub-game/scripts/test-control-layout-dom.mjs +57 -10
  245. package/kits/hub-game/scripts/test-corner-surface.mjs +268 -0
  246. package/kits/hub-game/scripts/test-decor-client.mjs +59 -3
  247. package/kits/hub-game/scripts/test-decor.mjs +27 -0
  248. package/kits/hub-game/scripts/test-device-class.mjs +4 -1
  249. package/kits/hub-game/scripts/test-disguise-client.mjs +281 -0
  250. package/kits/hub-game/scripts/test-disguise.mjs +176 -0
  251. package/kits/hub-game/scripts/test-dock-surface.mjs +404 -0
  252. package/kits/hub-game/scripts/test-door-stay-client.mjs +602 -0
  253. package/kits/hub-game/scripts/test-door-stay.mjs +613 -0
  254. package/kits/hub-game/scripts/test-earned-client.mjs +119 -0
  255. package/kits/hub-game/scripts/test-emote-surface.mjs +616 -0
  256. package/kits/hub-game/scripts/test-fps-telemetry.mjs +39 -4
  257. package/kits/hub-game/scripts/test-friend-bests.mjs +38 -12
  258. package/kits/hub-game/scripts/test-ghost-click-dom.mjs +75 -0
  259. package/kits/hub-game/scripts/test-grab-client.mjs +29 -2
  260. package/kits/hub-game/scripts/test-grab-orbit.mjs +260 -11
  261. package/kits/hub-game/scripts/test-grab.mjs +10 -1
  262. package/kits/hub-game/scripts/test-hats.mjs +28 -0
  263. package/kits/hub-game/scripts/test-held-offers.mjs +394 -0
  264. package/kits/hub-game/scripts/test-high-only.mjs +3 -3
  265. package/kits/hub-game/scripts/test-hold-show-client.mjs +175 -0
  266. package/kits/hub-game/scripts/test-hold-show.mjs +355 -0
  267. package/kits/hub-game/scripts/test-hub-controls.mjs +3 -1
  268. package/kits/hub-game/scripts/test-hub-idle.mjs +348 -0
  269. package/kits/hub-game/scripts/test-hub-leaving.mjs +21 -0
  270. package/kits/hub-game/scripts/test-hub-ops.mjs +119 -0
  271. package/kits/hub-game/scripts/test-hub-trip.mjs +240 -4
  272. package/kits/hub-game/scripts/test-hud-clear.mjs +83 -0
  273. package/kits/hub-game/scripts/test-hud-rate.mjs +2 -1
  274. package/kits/hub-game/scripts/test-idle.mjs +160 -0
  275. package/kits/hub-game/scripts/test-invites-client.mjs +53 -0
  276. package/kits/hub-game/scripts/test-labels.mjs +11 -0
  277. package/kits/hub-game/scripts/test-landscape-layout.mjs +20 -0
  278. package/kits/hub-game/scripts/test-loading-cover.mjs +67 -1
  279. package/kits/hub-game/scripts/test-manifest.mjs +27 -0
  280. package/kits/hub-game/scripts/test-menu-client.mjs +54 -5
  281. package/kits/hub-game/scripts/test-menu-surface.mjs +236 -0
  282. package/kits/hub-game/scripts/test-npcs.mjs +128 -0
  283. package/kits/hub-game/scripts/test-observed.mjs +171 -3
  284. package/kits/hub-game/scripts/test-pack.mjs +166 -0
  285. package/kits/hub-game/scripts/test-picker-surface.mjs +321 -0
  286. package/kits/hub-game/scripts/test-placeat-server.mjs +395 -0
  287. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  288. package/kits/hub-game/scripts/test-pointer-clear-dom.mjs +82 -0
  289. package/kits/hub-game/scripts/test-progress-reset.mjs +184 -6
  290. package/kits/hub-game/scripts/test-push-visit.mjs +9 -0
  291. package/kits/hub-game/scripts/test-quality.mjs +312 -9
  292. package/kits/hub-game/scripts/test-quick-chat-surface.mjs +511 -0
  293. package/kits/hub-game/scripts/test-rehello.mjs +237 -0
  294. package/kits/hub-game/scripts/test-rejoin-yaw.mjs +138 -0
  295. package/kits/hub-game/scripts/test-relations-among.mjs +13 -7
  296. package/kits/hub-game/scripts/test-relations-refresh.mjs +90 -2
  297. package/kits/hub-game/scripts/test-replay-client.mjs +110 -0
  298. package/kits/hub-game/scripts/test-replay.mjs +178 -0
  299. package/kits/hub-game/scripts/test-resume-held.mjs +13 -0
  300. package/kits/hub-game/scripts/test-resume-pose-server.mjs +43 -5
  301. package/kits/hub-game/scripts/test-role-client.mjs +2 -1
  302. package/kits/hub-game/scripts/test-safe-act.mjs +233 -0
  303. package/kits/hub-game/scripts/test-safe-caption.mjs +364 -0
  304. package/kits/hub-game/scripts/test-safe-layout.mjs +79 -0
  305. package/kits/hub-game/scripts/test-safe-prompt.mjs +163 -0
  306. package/kits/hub-game/scripts/test-sound-surface.mjs +256 -0
  307. package/kits/hub-game/scripts/test-soundscape.mjs +85 -2
  308. package/kits/hub-game/scripts/test-stuck-surface.mjs +174 -0
  309. package/kits/hub-game/scripts/test-stuck.mjs +31 -0
  310. package/kits/hub-game/scripts/test-talk-surface.mjs +23 -6
  311. package/kits/hub-game/scripts/test-talk-walk-dom.mjs +123 -0
  312. package/kits/hub-game/scripts/test-text-ask-surface.mjs +273 -0
  313. package/kits/hub-game/scripts/test-tiers.mjs +453 -3
  314. package/kits/hub-game/scripts/test-toast-no-row-dom.mjs +71 -0
  315. package/kits/hub-game/scripts/test-together.mjs +11 -0
  316. package/kits/hub-game/scripts/test-town-day.mjs +90 -0
  317. package/kits/hub-game/scripts/test-try-on.mjs +39 -0
  318. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +49 -2
  319. package/kits/hub-game/scripts/test-ui-tree.mjs +28 -0
  320. package/kits/hub-game/scripts/test-vehicle-client.mjs +68 -1
  321. package/kits/hub-game/scripts/test-vis.mjs +145 -0
  322. package/kits/hub-game/scripts/test-wallet.mjs +650 -0
  323. package/kits/hub-game/scripts/test-weakest-tier.mjs +135 -1
  324. package/kits/hub-game/scripts/test-world-labels.mjs +340 -0
  325. package/kits/hub-game/scripts/test-writer-lease-server.mjs +234 -0
  326. package/kits/hub-game/scripts/test-writer-lease.mjs +281 -0
  327. package/kits/hub-game/scripts/writer-storage-fixture.mjs +37 -0
  328. package/kits/hub-game/tools/hubScene/export.mjs +6 -5
  329. package/kits/hub-game/tools/hubScene/hubdata.mjs +10 -0
  330. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +36 -2
  331. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +10 -2
  332. package/kits/multiplayer-3d/castle.json +5 -5
  333. package/kits/multiplayer-3d/code/client/resumeGate.js +49 -2
  334. package/kits/multiplayer-3d/code/server/ownership.js +25 -6
  335. package/kits/multiplayer-3d/code/server/world.js +19 -4
  336. package/kits/multiplayer-3d/code/systems/multiplayer.js +67 -11
  337. package/kits/multiplayer-3d/package-lock.json +1 -1
  338. package/kits/multiplayer-3d/package.json +2 -1
  339. package/kits/multiplayer-3d/scripts/test-ground-half.mjs +56 -0
  340. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +54 -3
  341. package/kits/multiplayer-3d/scripts/test-owned-moves.mjs +190 -0
  342. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +191 -5
  343. package/kits/multiplayer-3d/scripts/test-resync-reconnect.mjs +68 -0
  344. package/kits/physics-2d/castle.json +2 -2
  345. package/kits/physics-2d/engine/scene.js +10 -2
  346. package/kits/physics-3d/CLAUDE.md +14 -0
  347. package/kits/physics-3d/behaviors/Player.jsx +39 -3
  348. package/kits/physics-3d/castle.json +3 -3
  349. package/kits/physics-3d/docs/engine-model-cache.md +109 -0
  350. package/kits/physics-3d/docs/engine-player.md +76 -0
  351. package/kits/physics-3d/docs/engine-skip-work.md +16 -0
  352. package/kits/physics-3d/docs/pxmodel-format.md +5 -1
  353. package/kits/physics-3d/engine3d/gait.js +16 -8
  354. package/kits/physics-3d/engine3d/groundsize.js +23 -0
  355. package/kits/physics-3d/engine3d/kithooks.js +50 -0
  356. package/kits/physics-3d/engine3d/look.js +110 -17
  357. package/kits/physics-3d/engine3d/lookbake.js +19 -1
  358. package/kits/physics-3d/engine3d/materialpresets.js +3 -2
  359. package/kits/physics-3d/engine3d/modelcache.js +280 -0
  360. package/kits/physics-3d/engine3d/modelcachedigest.js +37 -0
  361. package/kits/physics-3d/engine3d/modelcachegate.js +69 -0
  362. package/kits/physics-3d/engine3d/modelrefs.js +13 -0
  363. package/kits/physics-3d/engine3d/optimize.js +20 -9
  364. package/kits/physics-3d/engine3d/playerRun.js +26 -1
  365. package/kits/physics-3d/engine3d/pxmodel.js +7 -3
  366. package/kits/physics-3d/engine3d/templatecache.js +722 -0
  367. package/kits/physics-3d/engine3d/world3d.js +211 -17
  368. package/kits/physics-3d/package-lock.json +1 -1
  369. package/kits/physics-3d/package.json +2 -1
  370. package/kits/physics-3d/play/behaviors/Player.js +43 -3
  371. package/kits/physics-3d/scripts/render.mjs +56 -8
  372. package/kits/physics-3d/scripts/template-cache-fixtures.mjs +37 -0
  373. package/kits/physics-3d/scripts/template-cache-v1-bytes.json +49 -0
  374. package/kits/physics-3d/scripts/test-gait.mjs +53 -9
  375. package/kits/physics-3d/scripts/test-ground-half.mjs +120 -0
  376. package/kits/physics-3d/scripts/test-model-cache.mjs +600 -0
  377. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1 -0
  378. package/kits/physics-3d/scripts/test-sleeping-models.mjs +384 -0
  379. package/kits/physics-3d/scripts/test-template-cache-minified.mjs +106 -0
  380. package/kits/physics-3d/scripts/test-template-cache.mjs +519 -0
  381. package/kits/physics-3d/scripts/test-wall-slide.mjs +272 -0
  382. package/kits/physics-3d/systems/physics3d.js +51 -2
  383. package/kits/real-time/castle.json +2 -2
  384. package/kits/real-time/code/client/connection.js +3 -0
  385. package/package.json +2 -2
  386. package/vendor/three/examples/jsm/libs/fflate.module.js +2672 -0
package/dist/agent.js CHANGED
@@ -19,6 +19,7 @@ import { resolveFileTypes } from './editorConfig.js';
19
19
  import { kitCatalogLines } from './kitCatalog.js';
20
20
  import { panelWritesSince } from './paramsWrites.js';
21
21
  import { IMPORTS_DIR } from './imports.js';
22
+ import { declaredImports, mostSpecificFirst } from './importOrder.js';
22
23
  import { isSameOriginUpgrade } from './wsOrigin.js';
23
24
  import { resolveDeckPath } from './ide.js';
24
25
  import { lineRange, uniqueLocators } from './deckLocatorShape.js';
@@ -1077,14 +1078,17 @@ function readQuickReference(deckDir) {
1077
1078
  return readClaudeSectionWithImports(deckDir, 'Quick reference');
1078
1079
  }
1079
1080
  // One greeting, not a pile of them: the mounted kit's welcome is the deck's.
1081
+ // When it has none, the most specific kit under it speaks, never a kit it is
1082
+ // built on (importOrder.ts).
1080
1083
  function readWelcomeMessage(deckDir) {
1081
1084
  const own = readClaudeSection(deckDir, 'Welcome message');
1082
1085
  if (own)
1083
1086
  return own;
1084
1087
  const entry = entryImportAlias(deckDir);
1085
- const ordered = entry
1088
+ const preferred = entry
1086
1089
  ? [entry, ...importAliases(deckDir).filter((a) => a !== entry)]
1087
1090
  : importAliases(deckDir);
1091
+ const ordered = mostSpecificFirst(preferred, (alias) => declaredImports(path.join(deckDir, IMPORTS_DIR, alias)));
1088
1092
  for (const alias of ordered) {
1089
1093
  const text = readClaudeSection(path.join(deckDir, IMPORTS_DIR, alias), 'Welcome message');
1090
1094
  if (text)
package/dist/api.d.ts CHANGED
@@ -223,6 +223,22 @@ export interface CauldronBundleChunk {
223
223
  export type CauldronBundleChunkKind = 'JS' | 'WASM';
224
224
  /** Stores an uploaded chunk at its content-addressed URL once Ghost has checked its hash. */
225
225
  export declare function storeCauldronBundleChunk(deckId: string, uploadId: string, sha256: string, kind?: CauldronBundleChunkKind): Promise<CauldronBundleChunk>;
226
+ /**
227
+ * A presigned upload for one media asset, POSTed as exactly `contentType`, or
228
+ * null when this Ghost does not store assets yet (the field is not in its
229
+ * schema). Anything else is thrown.
230
+ */
231
+ export declare function createCauldronAssetUploadConfig(deckId: string, contentType: string): Promise<CauldronServerBundleUploadConfig | null>;
232
+ export interface CauldronAsset {
233
+ sha256: string;
234
+ url: string;
235
+ }
236
+ /**
237
+ * Stores an uploaded asset at its content-addressed URL once Ghost has checked
238
+ * its hash. Null when the Ghost answering does not know the field -- during a
239
+ * deploy, one app server may grant an upload and an older one take the store.
240
+ */
241
+ export declare function storeCauldronAsset(deckId: string, uploadId: string, sha256: string, contentType: string): Promise<CauldronAsset | null>;
226
242
  /**
227
243
  * Sets, or with null clears, the A/B experiments a deck runs (castle.json
228
244
  * `experiments`, already validated). Returns false when this Ghost predates
@@ -259,6 +275,10 @@ export interface SavedSourceVersion {
259
275
  }
260
276
  export declare function savedSourceHistory(deckId: string, timeoutMs?: number): Promise<SavedSourceVersion[]>;
261
277
  export declare function clearDeckLeaderboards(deckId: string): Promise<void>;
278
+ export declare function resetCauldronDeckLeaderboards(deckId: string): Promise<{
279
+ undoUntil: string | null;
280
+ }>;
281
+ export declare function undoCauldronDeckLeaderboardsReset(deckId: string): Promise<void>;
262
282
  export declare function saveWebDeckSource(deckId: string, uploadId: string, expectedS3Key?: string | null): Promise<WebDeckSource>;
263
283
  export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';
264
284
  export interface RegisteredCloudDeck {
package/dist/api.js CHANGED
@@ -375,6 +375,45 @@ export async function storeCauldronBundleChunk(deckId, uploadId, sha256, kind =
375
375
  handleAPIError(data);
376
376
  return pickData(data, 'storeCauldronBundleChunk');
377
377
  }
378
+ // A deck's audio and video (bundle.ts ExternalMedia), stored by Ghost at an
379
+ // immutable, content-addressed URL the bundle names. Unlike a chunk, an asset
380
+ // has somewhere to fall back to: a Ghost without the store gets the media
381
+ // inline, as before.
382
+ /**
383
+ * A presigned upload for one media asset, POSTed as exactly `contentType`, or
384
+ * null when this Ghost does not store assets yet (the field is not in its
385
+ * schema). Anything else is thrown.
386
+ */
387
+ export async function createCauldronAssetUploadConfig(deckId, contentType) {
388
+ const data = await graphql(`mutation($deckId: ID!, $contentType: String!) {
389
+ createCauldronAssetUploadConfig(deckId: $deckId, contentType: $contentType) {
390
+ deckId uploadId postUrl postFields
391
+ }
392
+ }`, { deckId, contentType });
393
+ const first = data?.errors?.[0];
394
+ if (first && /Cannot query field "createCauldronAssetUploadConfig"/.test(first.message ?? '')) {
395
+ return null;
396
+ }
397
+ handleAPIError(data);
398
+ return pickData(data, 'createCauldronAssetUploadConfig');
399
+ }
400
+ /**
401
+ * Stores an uploaded asset at its content-addressed URL once Ghost has checked
402
+ * its hash. Null when the Ghost answering does not know the field -- during a
403
+ * deploy, one app server may grant an upload and an older one take the store.
404
+ */
405
+ export async function storeCauldronAsset(deckId, uploadId, sha256, contentType) {
406
+ const data = await graphql(`mutation($deckId: ID!, $uploadId: String!, $sha256: String!, $contentType: String!) {
407
+ storeCauldronAsset(deckId: $deckId, uploadId: $uploadId, sha256: $sha256, contentType: $contentType) {
408
+ sha256 url
409
+ }
410
+ }`, { deckId, uploadId, sha256, contentType }, { timeoutMs: 120_000 });
411
+ const first = data?.errors?.[0];
412
+ if (first && /Cannot query field "storeCauldronAsset"/.test(first.message ?? ''))
413
+ return null;
414
+ handleAPIError(data);
415
+ return pickData(data, 'storeCauldronAsset');
416
+ }
378
417
  /**
379
418
  * Sets, or with null clears, the A/B experiments a deck runs (castle.json
380
419
  * `experiments`, already validated). Returns false when this Ghost predates
@@ -430,6 +469,24 @@ export async function clearDeckLeaderboards(deckId) {
430
469
  }`, { deckId });
431
470
  handleAPIError(data);
432
471
  }
472
+ // Starts a Cauldron deck's Store boards and classic leaderboards over from empty,
473
+ // keeping every player's saved data; undoable until `undoUntil`. Creator only. Ghost
474
+ // refuses a classic deck with DECK_DATA_RESET_NOT_WEB_DECK.
475
+ export async function resetCauldronDeckLeaderboards(deckId) {
476
+ const data = await graphql(`mutation($deckId: ID!) {
477
+ resetCauldronDeckLeaderboards(deckId: $deckId) { undoUntil }
478
+ }`, { deckId });
479
+ handleAPIError(data);
480
+ return pickData(data, 'resetCauldronDeckLeaderboards');
481
+ }
482
+ // Undoes the deck's last leaderboard reset while its window is open. Ghost refuses
483
+ // one that also reset saved data.
484
+ export async function undoCauldronDeckLeaderboardsReset(deckId) {
485
+ const data = await graphql(`mutation($deckId: ID!) {
486
+ undoCauldronDeckLeaderboardsReset(deckId: $deckId) { undoUntil }
487
+ }`, { deckId });
488
+ handleAPIError(data);
489
+ }
433
490
  // `expectedS3Key` is the save precondition: omitted (undefined) means no check, null means
434
491
  // "there must be no saved source yet", and a key means "the saved source must still be this
435
492
  // one" -- otherwise Ghost refuses with WEB_DECK_SOURCE_STALE. The argument is left out of the
package/dist/bundle.d.ts CHANGED
@@ -1,4 +1,37 @@
1
1
  import { type Plugin } from 'vite';
2
+ /** Content type -> stored extension: what Ghost stores (anything else stays inline). */
3
+ export declare const EXTERNAL_MEDIA_TYPES: Readonly<Record<string, string>>;
4
+ /**
5
+ * Smaller media stays inline. 64 KiB is the knee on the largest live deck:
6
+ * 78 of its 91 media files move and its page goes from 35.2 MB to 1.4 MB; the
7
+ * 13 under it total 303 KiB, not worth a request each.
8
+ */
9
+ export declare const EXTERNAL_MEDIA_MIN_BYTES: number;
10
+ export declare const EXTERNAL_MEDIA_BASE_URL: string;
11
+ export interface ExternalMediaAsset {
12
+ /** Lowercase hex SHA-256 of `bytes`. */
13
+ sha256: string;
14
+ contentType: string;
15
+ /** Where the bundle names it: `<base><sha256>.<ext>`. */
16
+ url: string;
17
+ bytes: Buffer;
18
+ /** The file it came from, relative to the deck where known, for messages. */
19
+ source: string;
20
+ }
21
+ export declare class ExternalMedia {
22
+ private readonly baseUrl;
23
+ private readonly exclude;
24
+ private readonly byUrl;
25
+ /** `exclude`: sha256s that stay inline (Ghost refused to store them). */
26
+ constructor(baseUrl?: string, exclude?: ReadonlySet<string>);
27
+ /** The deck build's two plugins: the loader (ahead of Vite's) and the late swap (ahead of InlineAssets). */
28
+ plugin(): Plugin[];
29
+ private loadedUrl;
30
+ private record;
31
+ private urlFor;
32
+ /** Every asset the finished page names (a module the build dropped names none). */
33
+ assetsIn(html: string): ExternalMediaAsset[];
34
+ }
2
35
  export declare class InlineAssets {
3
36
  private readonly token;
4
37
  private readonly marker;
@@ -23,7 +56,11 @@ export declare class InlineAssets {
23
56
  * counts as not inert.
24
57
  */
25
58
  export declare function markersInert(code: string, token: string): boolean;
26
- export declare function bundleProject(dir: string): Promise<string>;
59
+ export interface BundleOptions {
60
+ /** Name media by its CDN URL (save-deck and check; see ExternalMedia). Read its assets after. */
61
+ externalMedia?: ExternalMedia | null;
62
+ }
63
+ export declare function bundleProject(dir: string, options?: BundleOptions): Promise<string>;
27
64
  /** Above this a chunk risks being too big for WebView's code cache (~4-5 MB). */
28
65
  export declare const CHUNK_WARN_BYTES: number;
29
66
  export interface BundleChunk {
package/dist/bundle.js CHANGED
@@ -43,6 +43,276 @@ const INLINE_ASSET_MIN_PAYLOAD = 1024;
43
43
  * not checked, and builds the old way.
44
44
  */
45
45
  const INLINE_ASSET_MAX_CHECKED_CODE = 10 * 1024 * 1024;
46
+ // ---------------------------------------------------------------------------
47
+ // Audio and video served by URL, on save.
48
+ //
49
+ // Inlining keeps a published deck one file, but a 30 MB .wav inlines to 40 MB
50
+ // of base64, past Ghost's 50 MB scene cap with little else in the deck, and
51
+ // rolldown holds that 40 MB string many times over (the 30 MB deck peaked at
52
+ // 1.35 GB). So when save-deck asks, each audio or video file of
53
+ // EXTERNAL_MEDIA_MIN_BYTES or more that Vite would inline is named by its URL
54
+ // on Castle's CDN instead (`https://hosted.castle.games/cauldron-assets/
55
+ // <sha256>.<ext>`, immutable, which save-deck stores before it publishes the
56
+ // page).
57
+ //
58
+ // Where InlineAssets swaps a payload for a stand-in that has to come back, the
59
+ // URL here is the literal's true final value: the minifier may fold, alias or
60
+ // compare it as it likes, so there is nothing to check. What changes is the
61
+ // value itself. A deck that plays it (`new Audio(url)`, `video.src = url`,
62
+ // `fetch(url)` then `decodeAudioData`) never notices; a deck that reads the
63
+ // bytes out of the data: URI string itself would break. That is why this is
64
+ // media only (the one kind a deck hands to a loader rather than inspects),
65
+ // save only (the serve and `check` keep the data: URI), and only for the MIME
66
+ // types Ghost stores. A Ghost that refuses a type (video, before it stores
67
+ // video) or a file keeps that file inline; the save goes on.
68
+ //
69
+ // Two places, one rule. A media file imported plainly or with `?url` -- the
70
+ // way nearly every deck imports one, globs included -- is loaded here, ahead
71
+ // of Vite's asset plugin, so its base64 is never made at all: that is what
72
+ // takes the memory away, not only the bytes. Any other data: URI Vite writes
73
+ // for media (`new URL("data:...", '' + import.meta.url)`) is matched in the
74
+ // finished module by VITE_DATA_URI and swapped the same way, just before
75
+ // InlineAssets would mark it. Either way the URL is the one the data: URI's
76
+ // own MIME and bytes give. An `?inline` import asked for a data: URI by name,
77
+ // and keeps it; so does a file Ghost refused to store (`exclude`).
78
+ //
79
+ // A media element loads a cross-origin URL without CORS unless told to, and
80
+ // Web Audio then hears silence from it (`createMediaElementSource`), where the
81
+ // data: URI played; a video drawn into a WebGL texture taints it. The CDN
82
+ // answers `Access-Control-Allow-Origin: *`, so a page naming any asset gets
83
+ // mediaCorsShim first in its <head>, which puts a media element (audio or
84
+ // video) given an asset URL in CORS mode up front, and one routed into Web
85
+ // Audio by the time Web Audio reads it.
86
+ // Vite places it
87
+ // (transformIndexHtml, at the end of the build, once the chunks say whether
88
+ // any asset is named), as it places the deck's own entry script.
89
+ //
90
+ // The single file only, and the deck's own build only (a worker keeps its
91
+ // URIs), like InlineAssets.
92
+ /** Content type -> stored extension: what Ghost stores (anything else stays inline). */
93
+ export const EXTERNAL_MEDIA_TYPES = {
94
+ 'audio/wav': 'wav',
95
+ 'audio/x-wav': 'wav',
96
+ 'audio/wave': 'wav',
97
+ 'audio/mpeg': 'mp3',
98
+ 'audio/ogg': 'ogg',
99
+ 'audio/mp4': 'm4a',
100
+ 'audio/aac': 'aac',
101
+ 'audio/flac': 'flac',
102
+ 'audio/webm': 'weba',
103
+ // The declared type picks the extension: a .webm is video/webm (Vite's own
104
+ // lookup), a .weba audio/webm, though both are the same container.
105
+ 'video/mp4': 'mp4',
106
+ 'video/webm': 'webm',
107
+ };
108
+ // The MIME Vite's own lookup gives each media extension (its data: URI
109
+ // header), for the files loaded here. Every one is in EXTERNAL_MEDIA_TYPES.
110
+ // No .mov or .m4v: Chromium and Android WebView do not play them reliably.
111
+ const MEDIA_EXTENSION_TYPES = {
112
+ wav: 'audio/wav',
113
+ mp3: 'audio/mpeg',
114
+ ogg: 'audio/ogg',
115
+ oga: 'audio/ogg',
116
+ opus: 'audio/ogg',
117
+ m4a: 'audio/mp4',
118
+ aac: 'audio/aac',
119
+ flac: 'audio/flac',
120
+ weba: 'audio/webm',
121
+ mp4: 'video/mp4',
122
+ webm: 'video/webm',
123
+ };
124
+ // The media extensions Vite treats as assets without a `?url` (its KNOWN_ASSET_TYPES).
125
+ const VITE_MEDIA_ASSETS = new Set(['wav', 'mp3', 'ogg', 'opus', 'm4a', 'aac', 'flac', 'mp4', 'webm']);
126
+ const MEDIA_ID = /\.(wav|mp3|ogg|oga|opus|m4a|aac|flac|weba|mp4|webm)(\?url)?$/i;
127
+ /**
128
+ * Smaller media stays inline. 64 KiB is the knee on the largest live deck:
129
+ * 78 of its 91 media files move and its page goes from 35.2 MB to 1.4 MB; the
130
+ * 13 under it total 303 KiB, not worth a request each.
131
+ */
132
+ export const EXTERNAL_MEDIA_MIN_BYTES = 64 * 1024;
133
+ // Where Ghost serves stored assets. The override is for tests against a fake API.
134
+ export const EXTERNAL_MEDIA_BASE_URL = process.env.CASTLE_ASSET_BASE_URL || 'https://hosted.castle.games/cauldron-assets/';
135
+ // Run before any deck script. CORS matters only where a media element is
136
+ // routed into Web Audio (createMediaElementSource), so that is where it is
137
+ // made sure of: any element given to it with no crossOrigin of its own becomes
138
+ // `anonymous`, whatever it names now or is given later (a detached <source>
139
+ // appended afterwards, innerHTML, a template). That is safe for every element
140
+ // a published deck can play: the deck CSP's media-src allows only 'self',
141
+ // data:, blob: and Castle's hosts (castle.imgix.net, image.castle.xyz,
142
+ // audio.castle.xyz, the asset path), and data: and blob: are same-origin to
143
+ // CORS while those hosts answer `Access-Control-Allow-Origin: *`. An element
144
+ // already fetching some other URL without CORS is loaded again, keeping its
145
+ // time, rate, loop, muted and volume, and playing again if it was -- unless
146
+ // the deck acts on it first (play, pause, load, a new src or a seek), which
147
+ // cancels that restore. The cheap paths -- `new Audio(url)` (its constructor
148
+ // sets src natively, past any setter, so it is wrapped, keeping `instanceof
149
+ // Audio`), the `src` property and `setAttribute('src')` -- set CORS up front
150
+ // for an asset URL, so the common case never reloads. Those are on
151
+ // HTMLMediaElement, so a <video> given an asset URL that way is CORS before it
152
+ // fetches, which is what lets a deck draw it into a WebGL texture or a canvas.
153
+ // A video that named one past them (markup, a template, a detached <source>)
154
+ // is reloaded in CORS mode where its pixels are first read -- texImage2D and
155
+ // texSubImage2D (and the 3D ones), drawImage, createImageBitmap -- the same
156
+ // reload as for Web Audio; that one upload or draw is skipped, since reading
157
+ // the frame fetched without CORS would taint the canvas for good.
158
+ // Anything unexpected leaves the page as it was.
159
+ function mediaCorsShim(prefix) {
160
+ return `(function(){try{var P=${JSON.stringify(prefix)},M=window.HTMLMediaElement,S=window.HTMLSourceElement;if(!M)return;var H=M.prototype;` +
161
+ // A pending restore per element; anything the deck does to it cancels it.
162
+ 'var R=new WeakMap();function z(e){try{R.delete(e)}catch(x){}}' +
163
+ 'function c(e,u){try{if(e instanceof M&&typeof u=="string"&&u.indexOf(P)===0&&e.getAttribute("crossorigin")===null)e.crossOrigin="anonymous"}catch(x){}}' +
164
+ 'function w(T,k,f){var d=T&&Object.getOwnPropertyDescriptor(T.prototype,k);if(d&&d.set&&d.configurable)Object.defineProperty(T.prototype,k,{configurable:true,enumerable:d.enumerable,get:d.get,set:function(v){try{f(this,v)}catch(x){}d.set.call(this,v)}});return d}' +
165
+ 'w(M,"src",function(e,v){z(e);c(e,String(v))});w(S,"src",function(e,v){c(e.parentNode,String(v))});var T=w(M,"currentTime",z);' +
166
+ 'var g=Element.prototype.setAttribute;Element.prototype.setAttribute=function(n,v){try{if(String(n).toLowerCase()==="src"){if(this instanceof M)z(this);c(this instanceof M?this:S&&this instanceof S?this.parentNode:null,String(v))}}catch(x){}return g.apply(this,arguments)};' +
167
+ 'var L=H.load;["play","pause","load"].forEach(function(k){var f=H[k];if(f)H[k]=function(){z(this);return f.apply(this,arguments)}});' +
168
+ 'var A=window.Audio;if(A){var W=function Audio(u){var e=new A();if(u!==undefined){c(e,String(u));e.src=u}return e};W.prototype=A.prototype;window.Audio=W}' +
169
+ 'function r(e){if(!(e instanceof M)||e.getAttribute("crossorigin")!==null)return;var u=e.currentSrc||e.src||"";e.crossOrigin="anonymous";' +
170
+ 'if(e.networkState===M.NETWORK_EMPTY||/^(data|blob):/i.test(u))return;' +
171
+ 'var t=e.currentTime,b=e.playbackRate,l=e.loop,m=e.muted,v=e.volume,p=!e.paused;L.call(e);e.loop=l;e.muted=m;e.volume=v;' +
172
+ // Registered after load(), so nothing load() queues can be taken for the deck.
173
+ 'var k={};R.set(e,k);e.addEventListener("loadedmetadata",function f(){e.removeEventListener("loadedmetadata",f);if(R.get(e)!==k)return;R.delete(e);' +
174
+ 'try{if(T&&T.set)T.set.call(e,t);e.playbackRate=b;if(p){var q=e.play();if(q&&q.catch)q.catch(function(){})}}catch(x){}});return true}' +
175
+ // A video read as pixels (a WebGL texture, a 2D canvas, an ImageBitmap)
176
+ // that names an asset without CORS: reloaded in CORS mode on its first read,
177
+ // and that one texture upload or draw skipped, so nothing is tainted.
178
+ 'var V=window.HTMLVideoElement;function n(e){if(!V||!(e instanceof V)||e.getAttribute("crossorigin")!==null)return false;if((e.currentSrc||e.src||"").indexOf(P)===0)return true;var s=e.querySelectorAll("source");for(var i=0;i<s.length;i++)if((s[i].src||"").indexOf(P)===0)return true;return false}' +
179
+ 'function y(C,k){var K=C&&C.prototype,o=K&&K[k];if(typeof o!="function"||o.__castle)return;var h=function(){for(var i=0;i<arguments.length;i++){var e=arguments[i];if(V&&e instanceof V){try{if(n(e)&&r(e))return}catch(x){}break}}return o.apply(this,arguments)};h.__castle=1;K[k]=h}' +
180
+ '[window.WebGLRenderingContext,window.WebGL2RenderingContext].forEach(function(C){["texImage2D","texSubImage2D","texImage3D","texSubImage3D"].forEach(function(k){y(C,k)})});' +
181
+ '[window.CanvasRenderingContext2D,window.OffscreenCanvasRenderingContext2D].forEach(function(C){y(C,"drawImage")});' +
182
+ // createImageBitmap answers a promise, so it waits out the reload (a CORS
183
+ // frame, and the restored time settled) and then reads, instead of skipping.
184
+ 'var B=window.createImageBitmap;if(B&&!B.__castle){window.createImageBitmap=function(e){var a=arguments,s=this;try{if(n(e)&&r(e))return new Promise(function(ok){var E=["loadeddata","seeked","canplay","error"],t,d=function(){if(!(e.readyState>=2&&!e.seeking)&&!e.error&&d!==t)return;E.forEach(function(k){e.removeEventListener(k,d)});clearTimeout(t);ok()};t=setTimeout(function(){t=d;d()},10000);E.forEach(function(k){e.addEventListener(k,d)})}).then(function(){return B.apply(s,a)})}catch(x){}return B.apply(this,arguments)};window.createImageBitmap.__castle=1}' +
185
+ '[window.AudioContext,window.webkitAudioContext].forEach(function(C){var K=C&&C.prototype,o=K&&K.createMediaElementSource;if(!o||o.__castle)return;var h=function(e){try{r(e)}catch(x){}return o.apply(this,arguments)};h.__castle=1;K.createMediaElementSource=h});' +
186
+ '}catch(x){}})();';
187
+ }
188
+ export class ExternalMedia {
189
+ baseUrl;
190
+ exclude;
191
+ byUrl = new Map();
192
+ /** `exclude`: sha256s that stay inline (Ghost refused to store them). */
193
+ constructor(baseUrl = EXTERNAL_MEDIA_BASE_URL, exclude = new Set()) {
194
+ this.baseUrl = baseUrl;
195
+ this.exclude = exclude;
196
+ }
197
+ /** The deck build's two plugins: the loader (ahead of Vite's) and the late swap (ahead of InlineAssets). */
198
+ plugin() {
199
+ let publicDir = '';
200
+ let root = '';
201
+ const load = {
202
+ name: 'castle-external-media-load',
203
+ enforce: 'pre',
204
+ apply: 'build',
205
+ configResolved(config) {
206
+ publicDir = config.publicDir ? path.resolve(config.publicDir) + path.sep : '';
207
+ root = config.root;
208
+ },
209
+ // A build that fell back starts over: only the last build's assets count.
210
+ buildStart: () => {
211
+ this.byUrl.clear();
212
+ },
213
+ load: {
214
+ order: 'pre',
215
+ filter: { id: { include: MEDIA_ID, exclude: /^\0/ } },
216
+ handler: (id) => {
217
+ const url = this.loadedUrl(id, publicDir, root);
218
+ // What Vite's asset plugin answers for an asset, with this URL for the data: URI.
219
+ return url
220
+ ? { code: `export default ${JSON.stringify(url)}`, moduleSideEffects: false, moduleType: 'js' }
221
+ : null;
222
+ },
223
+ },
224
+ };
225
+ const late = {
226
+ name: 'castle-external-media',
227
+ enforce: 'post',
228
+ apply: 'build',
229
+ // In a build this runs in generateBundle, when every chunk is rendered:
230
+ // the shim goes in only when one of them names an asset.
231
+ transformIndexHtml: {
232
+ order: 'post',
233
+ handler: (_html, ctx) => {
234
+ const urls = [...this.byUrl.keys()];
235
+ const named = Object.values(ctx.bundle ?? {}).some((out) => out.type === 'chunk' && urls.some((url) => out.code.includes(url)));
236
+ return named ? [{ tag: 'script', children: mediaCorsShim(this.baseUrl), injectTo: 'head-prepend' }] : undefined;
237
+ },
238
+ },
239
+ transform: {
240
+ order: 'post',
241
+ filter: { code: /"data:(?:audio|video)\// },
242
+ handler: (code, id) => {
243
+ // An `?inline` import's module: a data: URI asked for by name.
244
+ if (/[?&]inline(?:[&=]|$)/.test(id))
245
+ return null;
246
+ const source = relativeSource(root, id);
247
+ let swapped = false;
248
+ const out = code.replace(VITE_DATA_URI, (whole, before, header, payload) => {
249
+ const url = this.urlFor(header, payload, source);
250
+ if (!url)
251
+ return whole;
252
+ swapped = true;
253
+ return `${before}${JSON.stringify(url)}`;
254
+ });
255
+ return swapped ? { code: out, map: null } : null;
256
+ },
257
+ },
258
+ };
259
+ return [load, late];
260
+ }
261
+ // The URL for a media file Vite would inline from this id, or null to leave
262
+ // the id to Vite: another query, a public file, a file that is not there, or
263
+ // one too small.
264
+ loadedUrl(id, publicDir, root) {
265
+ const [file, query = ''] = id.split('?', 2);
266
+ const ext = path.extname(file).slice(1).toLowerCase();
267
+ const mime = MEDIA_EXTENSION_TYPES[ext];
268
+ if (!mime || (query !== 'url' && !(query === '' && VITE_MEDIA_ASSETS.has(ext))))
269
+ return null;
270
+ if (!path.isAbsolute(file) || (publicDir && file.startsWith(publicDir)))
271
+ return null;
272
+ let size;
273
+ try {
274
+ const stat = fs.statSync(file);
275
+ if (!stat.isFile())
276
+ return null;
277
+ size = stat.size;
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ if (size < EXTERNAL_MEDIA_MIN_BYTES)
283
+ return null;
284
+ return this.record(mime, fs.readFileSync(file), relativeSource(root, file));
285
+ }
286
+ record(mime, bytes, source) {
287
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
288
+ if (this.exclude.has(sha256))
289
+ return null;
290
+ const url = `${this.baseUrl}${sha256}.${EXTERNAL_MEDIA_TYPES[mime]}`;
291
+ if (!this.byUrl.has(url))
292
+ this.byUrl.set(url, { sha256, contentType: mime, url, bytes, source });
293
+ return url;
294
+ }
295
+ urlFor(header, payload, source) {
296
+ // `data:<mime>;base64,` with no parameters: anything more is not a plain media file.
297
+ const mime = /^data:([\w.+-]+\/[\w.+-]+);base64,$/.exec(header)?.[1];
298
+ const ext = mime ? EXTERNAL_MEDIA_TYPES[mime] : undefined;
299
+ // Base64 is 4 characters per 3 bytes: a shorter payload cannot reach the minimum.
300
+ if (!mime || !ext || payload.length < (EXTERNAL_MEDIA_MIN_BYTES / 3) * 4)
301
+ return null;
302
+ const bytes = Buffer.from(payload, 'base64');
303
+ if (bytes.byteLength < EXTERNAL_MEDIA_MIN_BYTES)
304
+ return null;
305
+ return this.record(mime, bytes, source);
306
+ }
307
+ /** Every asset the finished page names (a module the build dropped names none). */
308
+ assetsIn(html) {
309
+ return [...this.byUrl.values()].filter((asset) => html.includes(asset.url));
310
+ }
311
+ }
312
+ function relativeSource(root, id) {
313
+ const file = id.split('?', 1)[0];
314
+ return root && file.startsWith(root + path.sep) ? path.relative(root, file) : path.basename(file);
315
+ }
46
316
  export class InlineAssets {
47
317
  token = `CASTLE${randomBytes(6).toString('hex')}x`;
48
318
  marker = new RegExp(`${this.token}(\\d+)x`, 'g');
@@ -427,18 +697,19 @@ function inertUse(node, ancestors, opaqueCallee) {
427
697
  }
428
698
  return false;
429
699
  }
430
- export async function bundleProject(dir) {
700
+ export async function bundleProject(dir, options = {}) {
431
701
  const inline = new InlineAssets();
702
+ const external = options.externalMedia ?? null;
432
703
  try {
433
- return await bundleSingleFile(dir, inline);
704
+ return await bundleSingleFile(dir, inline, external);
434
705
  }
435
706
  catch (err) {
436
707
  if (!inline.evaluated)
437
708
  throw err;
438
- return bundleSingleFile(dir, null);
709
+ return bundleSingleFile(dir, null, external);
439
710
  }
440
711
  }
441
- async function bundleSingleFile(dir, inline) {
712
+ async function bundleSingleFile(dir, inline, external) {
442
713
  const result = await build({
443
714
  root: dir,
444
715
  worker: castleWorkerOptions(),
@@ -449,6 +720,8 @@ async function bundleSingleFile(dir, inline) {
449
720
  viteSingleFile(),
450
721
  singleFileBuildCompatPlugin(),
451
722
  sceneFilesPlugin(),
723
+ // Before InlineAssets: a URI this names is no longer one to mark.
724
+ external?.plugin(),
452
725
  inline?.plugin(),
453
726
  ],
454
727
  build: {
@@ -489,18 +762,24 @@ async function bundleSingleFile(dir, inline) {
489
762
  // and compiled by streaming, which gets Chromium's wasm code cache.
490
763
  /** Above this a chunk risks being too big for WebView's code cache (~4-5 MB). */
491
764
  export const CHUNK_WARN_BYTES = 3 * 1024 * 1024;
492
- // Third-party code split out by package. Grouping modules into a chunk by
493
- // path moves their side effects relative to the rest of the graph, and rolldown
494
- // also hoists any shared chunk's require above the importer's own code; so the
495
- // build sets `strictExecutionOrder`, which wraps each module's top level in an
496
- // init function that runs in import order whatever chunk it lands in. That is
497
- // what keeps `import "./setup.js"; import "vendor"` running setup first, as the
498
- // single file does.
499
765
  const CHUNK_GROUPS = [
500
766
  { name: 'rapier', test: /[\\/]node_modules[\\/]@dimforge[\\/]/, priority: 3 },
501
767
  { name: 'three', test: /[\\/]node_modules[\\/]three[\\/]/, priority: 2 },
502
768
  { name: 'vendor', test: /[\\/]node_modules[\\/]/, priority: 1, maxSize: 2 * 1024 * 1024 },
503
769
  ];
770
+ // Everything else -- a kit's code under imports/, the deck's own -- lands in
771
+ // the entry chunk, which for a large kit deck (the hub Town: 5.2 MB) is past
772
+ // what WebView's code cache keeps. When the entry comes out over
773
+ // CHUNK_WARN_BYTES the build runs again with this group, which splits that
774
+ // code into pieces near maxSize. entriesAware keeps code behind a dynamic
775
+ // import() out of the pieces the page loads up front. A deck whose entry is
776
+ // smaller builds exactly as before.
777
+ const APP_SPLIT_GROUP = {
778
+ name: 'app',
779
+ priority: 0,
780
+ maxSize: 2 * 1024 * 1024,
781
+ entriesAware: true,
782
+ };
504
783
  export function wrapChunk(name, code) {
505
784
  return (`__castleDefine(${JSON.stringify(name)},function(require,module,exports,__castleImport,__castleUrl,__castleMeta){"use strict";\n` +
506
785
  `${code}\n});\n`);
@@ -840,7 +1119,8 @@ export function sha256Hex(bytes) {
840
1119
  function scriptJson(value) {
841
1120
  return JSON.stringify(value).replace(/</g, '\\u003c');
842
1121
  }
843
- export async function bundleProjectChunked(dir) {
1122
+ /** One chunked build: its output, and the Rapier wasm it split out. */
1123
+ async function buildChunked(dir, groups) {
844
1124
  const wasm = new Map();
845
1125
  const missedWasm = [];
846
1126
  const result = await build({
@@ -868,7 +1148,7 @@ export async function bundleProjectChunked(dir) {
868
1148
  format: 'cjs',
869
1149
  entryFileNames: '[name]-[hash].js',
870
1150
  chunkFileNames: '[name]-[hash].js',
871
- codeSplitting: { groups: CHUNK_GROUPS },
1151
+ codeSplitting: { groups },
872
1152
  strictExecutionOrder: true,
873
1153
  },
874
1154
  },
@@ -878,6 +1158,22 @@ export async function bundleProjectChunked(dir) {
878
1158
  const output = Array.isArray(result) ? result[0] : result;
879
1159
  if (!('output' in output))
880
1160
  throw new Error('Unexpected build result');
1161
+ return { output, wasm, missedWasm };
1162
+ }
1163
+ function entryBytes(output) {
1164
+ let bytes = 0;
1165
+ for (const item of output.output) {
1166
+ if (item.type === 'chunk' && item.isEntry)
1167
+ bytes += Buffer.byteLength(item.code ?? '', 'utf8');
1168
+ }
1169
+ return bytes;
1170
+ }
1171
+ export async function bundleProjectChunked(dir) {
1172
+ let built0 = await buildChunked(dir, CHUNK_GROUPS);
1173
+ if (entryBytes(built0.output) > CHUNK_WARN_BYTES) {
1174
+ built0 = await buildChunked(dir, [...CHUNK_GROUPS, APP_SPLIT_GROUP]);
1175
+ }
1176
+ const { output, wasm, missedWasm } = built0;
881
1177
  let html = null;
882
1178
  const css = [];
883
1179
  const built = [];