@air-jam/sdk 0.9.3 → 1.0.0-beta.1

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 (594) hide show
  1. package/README.md +168 -205
  2. package/dist/actions-D4eh6Xaa.d.cts +72 -0
  3. package/dist/actions-D4eh6Xaa.d.ts +72 -0
  4. package/dist/{agent-contract-CD2QnbBJ.d.cts → agent-contract-DfLm4Mf-.d.ts} +3 -19
  5. package/dist/{agent-contract-CD2QnbBJ.d.ts → agent-contract-TINzp-5Y.d.cts} +3 -19
  6. package/dist/agent-tooling.cjs +135 -46
  7. package/dist/agent-tooling.cjs.map +1 -1
  8. package/dist/agent-tooling.d.cts +96 -5
  9. package/dist/agent-tooling.d.ts +96 -5
  10. package/dist/agent-tooling.js +15 -14
  11. package/dist/agent-tooling.js.map +1 -1
  12. package/dist/{use-air-jam-host-COLy8t4s.d.ts → air-jam-context-BCVCWiaT.d.ts} +121 -114
  13. package/dist/{use-air-jam-host-DM-ybB3C.d.cts → air-jam-context-DavligpM.d.cts} +121 -114
  14. package/dist/arcade/bridge/controller.cjs +873 -603
  15. package/dist/arcade/bridge/controller.cjs.map +1 -1
  16. package/dist/arcade/bridge/controller.d.cts +28 -76
  17. package/dist/arcade/bridge/controller.d.ts +28 -76
  18. package/dist/arcade/bridge/controller.js +27 -28
  19. package/dist/arcade/bridge/controller.js.map +1 -1
  20. package/dist/arcade/bridge/host.cjs +1017 -252
  21. package/dist/arcade/bridge/host.cjs.map +1 -1
  22. package/dist/arcade/bridge/host.d.cts +6 -72
  23. package/dist/arcade/bridge/host.d.ts +6 -72
  24. package/dist/arcade/bridge/host.js +19 -22
  25. package/dist/arcade/bridge/host.js.map +1 -1
  26. package/dist/arcade/bridge/iframe.cjs +3 -31
  27. package/dist/arcade/bridge/iframe.cjs.map +1 -1
  28. package/dist/arcade/bridge/iframe.d.cts +4 -46
  29. package/dist/arcade/bridge/iframe.d.ts +4 -46
  30. package/dist/arcade/bridge/iframe.js +6 -18
  31. package/dist/arcade/bridge/iframe.js.map +1 -1
  32. package/dist/arcade/host.cjs +0 -502
  33. package/dist/arcade/host.cjs.map +1 -1
  34. package/dist/arcade/host.d.cts +1 -19
  35. package/dist/arcade/host.d.ts +1 -19
  36. package/dist/arcade/host.js +0 -14
  37. package/dist/arcade/host.js.map +1 -1
  38. package/dist/arcade/runtime.cjs +10354 -4690
  39. package/dist/arcade/runtime.cjs.map +1 -1
  40. package/dist/arcade/runtime.d.cts +45 -13
  41. package/dist/arcade/runtime.d.ts +45 -13
  42. package/dist/arcade/runtime.js +37 -24
  43. package/dist/arcade/runtime.js.map +1 -1
  44. package/dist/arcade/surface.cjs +3 -35
  45. package/dist/arcade/surface.cjs.map +1 -1
  46. package/dist/arcade/surface.d.cts +14 -2
  47. package/dist/arcade/surface.d.ts +14 -2
  48. package/dist/arcade/surface.js +7 -13
  49. package/dist/arcade/surface.js.map +1 -1
  50. package/dist/arcade/url.cjs +45 -283
  51. package/dist/arcade/url.cjs.map +1 -1
  52. package/dist/arcade/url.d.cts +3 -56
  53. package/dist/arcade/url.d.ts +3 -56
  54. package/dist/arcade/url.js +33 -16
  55. package/dist/arcade/url.js.map +1 -1
  56. package/dist/chunk-24NZZOIO.js +700 -0
  57. package/dist/chunk-24NZZOIO.js.map +1 -0
  58. package/dist/chunk-27QLKLZL.js +469 -0
  59. package/dist/chunk-27QLKLZL.js.map +1 -0
  60. package/dist/{chunk-UWJOIVON.js → chunk-2H2FGF3H.js} +3 -6
  61. package/dist/chunk-2H2FGF3H.js.map +1 -0
  62. package/dist/chunk-2QZADUGA.js +188 -0
  63. package/dist/chunk-2QZADUGA.js.map +1 -0
  64. package/dist/chunk-3LDQCQL2.js +307 -0
  65. package/dist/chunk-3LDQCQL2.js.map +1 -0
  66. package/dist/chunk-3M7656SU.js +389 -0
  67. package/dist/chunk-3M7656SU.js.map +1 -0
  68. package/dist/{chunk-K4OZ54UD.js → chunk-5CRZFIN6.js} +2 -55
  69. package/dist/chunk-5CRZFIN6.js.map +1 -0
  70. package/dist/chunk-5TVVPBQI.js +7 -0
  71. package/dist/chunk-5TVVPBQI.js.map +1 -0
  72. package/dist/chunk-6Y3F6Y2K.js +343 -0
  73. package/dist/chunk-6Y3F6Y2K.js.map +1 -0
  74. package/dist/{chunk-EVZJA6RN.js → chunk-6ZJUA63D.js} +183 -2
  75. package/dist/chunk-6ZJUA63D.js.map +1 -0
  76. package/dist/chunk-A6EOGRRG.js +49 -0
  77. package/dist/chunk-A6EOGRRG.js.map +1 -0
  78. package/dist/chunk-BEM77SVQ.js +57 -0
  79. package/dist/chunk-BEM77SVQ.js.map +1 -0
  80. package/dist/chunk-C5722GTG.js +176 -0
  81. package/dist/chunk-C5722GTG.js.map +1 -0
  82. package/dist/{chunk-CV3PBXPT.js → chunk-C5GS2GMK.js} +99 -105
  83. package/dist/chunk-C5GS2GMK.js.map +1 -0
  84. package/dist/chunk-CDL7LYZH.js +19 -0
  85. package/dist/chunk-CDL7LYZH.js.map +1 -0
  86. package/dist/{chunk-PSUYTD2L.js → chunk-DA3TE4OP.js} +1 -1
  87. package/dist/chunk-DA3TE4OP.js.map +1 -0
  88. package/dist/chunk-DBF7NJ3S.js +72 -0
  89. package/dist/chunk-DBF7NJ3S.js.map +1 -0
  90. package/dist/chunk-DHFKL3DI.js +2477 -0
  91. package/dist/chunk-DHFKL3DI.js.map +1 -0
  92. package/dist/chunk-DRBPVG47.js +89 -0
  93. package/dist/chunk-DRBPVG47.js.map +1 -0
  94. package/dist/{chunk-MIMPMB7O.js → chunk-EG25EXSA.js} +24 -3
  95. package/dist/chunk-EG25EXSA.js.map +1 -0
  96. package/dist/chunk-FCG42U7D.js +131 -0
  97. package/dist/chunk-FCG42U7D.js.map +1 -0
  98. package/dist/chunk-FJ4J2BEC.js +26 -0
  99. package/dist/chunk-FJ4J2BEC.js.map +1 -0
  100. package/dist/chunk-H4DEVMTO.js +221 -0
  101. package/dist/chunk-H4DEVMTO.js.map +1 -0
  102. package/dist/{chunk-X35LLCWV.js → chunk-I6TSHJF7.js} +6 -8
  103. package/dist/chunk-I6TSHJF7.js.map +1 -0
  104. package/dist/{chunk-IG6GZZSS.js → chunk-JCGTL77W.js} +1 -1
  105. package/dist/chunk-JCGTL77W.js.map +1 -0
  106. package/dist/chunk-JJVCBUYM.js +98 -0
  107. package/dist/chunk-JJVCBUYM.js.map +1 -0
  108. package/dist/chunk-K6BJJJJM.js +138 -0
  109. package/dist/chunk-K6BJJJJM.js.map +1 -0
  110. package/dist/chunk-KSYN4I5Y.js +50 -0
  111. package/dist/chunk-KSYN4I5Y.js.map +1 -0
  112. package/dist/chunk-KUGROY5S.js +265 -0
  113. package/dist/chunk-KUGROY5S.js.map +1 -0
  114. package/dist/chunk-LX6CTPDW.js +16 -0
  115. package/dist/chunk-LX6CTPDW.js.map +1 -0
  116. package/dist/{chunk-BE6Z4SIT.js → chunk-M5553I2G.js} +2 -11
  117. package/dist/chunk-M5553I2G.js.map +1 -0
  118. package/dist/{chunk-X24K52DG.js → chunk-MD25536W.js} +1 -1
  119. package/dist/chunk-MD25536W.js.map +1 -0
  120. package/dist/{chunk-3USU7GY2.js → chunk-MJAWAHLT.js} +1 -1
  121. package/dist/chunk-MJAWAHLT.js.map +1 -0
  122. package/dist/chunk-OAXCFPZ7.js +14 -0
  123. package/dist/chunk-OAXCFPZ7.js.map +1 -0
  124. package/dist/{chunk-D4VDEVTZ.js → chunk-QHBRHYMV.js} +18 -17
  125. package/dist/chunk-QHBRHYMV.js.map +1 -0
  126. package/dist/chunk-QTNYGAZ7.js +45 -0
  127. package/dist/chunk-QTNYGAZ7.js.map +1 -0
  128. package/dist/chunk-S3TN7Y7L.js +921 -0
  129. package/dist/chunk-S3TN7Y7L.js.map +1 -0
  130. package/dist/chunk-SMKD4JY3.js +129 -0
  131. package/dist/chunk-SMKD4JY3.js.map +1 -0
  132. package/dist/{chunk-O6X7FJ6N.js → chunk-TFW4NJW2.js} +619 -643
  133. package/dist/chunk-TFW4NJW2.js.map +1 -0
  134. package/dist/chunk-UBBP2UY3.js +83 -0
  135. package/dist/chunk-UBBP2UY3.js.map +1 -0
  136. package/dist/chunk-URVBMQCK.js +802 -0
  137. package/dist/chunk-URVBMQCK.js.map +1 -0
  138. package/dist/chunk-VGX2274F.js +1995 -0
  139. package/dist/chunk-VGX2274F.js.map +1 -0
  140. package/dist/chunk-WAFGYJZN.js +1513 -0
  141. package/dist/chunk-WAFGYJZN.js.map +1 -0
  142. package/dist/chunk-WGHNGQUS.js +78 -0
  143. package/dist/chunk-WGHNGQUS.js.map +1 -0
  144. package/dist/chunk-XLY44PXZ.js +46 -0
  145. package/dist/chunk-XLY44PXZ.js.map +1 -0
  146. package/dist/connection-store-BYpQ50W2.d.ts +41 -0
  147. package/dist/connection-store-D6QqzXU1.d.cts +41 -0
  148. package/dist/control-Bv8dWjyp.d.ts +1400 -0
  149. package/dist/control-CNzybWMd.d.cts +1400 -0
  150. package/dist/controller-0CVO1t_3.d.cts +26 -0
  151. package/dist/controller-agent-vOiuK7T6.d.cts +130 -0
  152. package/dist/controller-agent-vOiuK7T6.d.ts +130 -0
  153. package/dist/controller-bridge.cjs +992 -0
  154. package/dist/controller-bridge.cjs.map +1 -0
  155. package/dist/controller-bridge.d.cts +52 -0
  156. package/dist/controller-bridge.d.ts +52 -0
  157. package/dist/controller-bridge.js +23 -0
  158. package/dist/controller-bridge.js.map +1 -0
  159. package/dist/controller-capture-2GKKGHJ2.js +8 -0
  160. package/dist/controller-capture-2GKKGHJ2.js.map +1 -0
  161. package/dist/controller-h9M2Nngd.d.ts +26 -0
  162. package/dist/controller-press-EWWIMVXP.js +231 -0
  163. package/dist/controller-press-EWWIMVXP.js.map +1 -0
  164. package/dist/core-BAO0pHrJ.d.cts +15 -0
  165. package/dist/core-BAO0pHrJ.d.ts +15 -0
  166. package/dist/core.cjs +5931 -0
  167. package/dist/core.cjs.map +1 -0
  168. package/dist/core.d.cts +232 -0
  169. package/dist/core.d.ts +232 -0
  170. package/dist/core.js +906 -0
  171. package/dist/core.js.map +1 -0
  172. package/dist/dev-events-BffobOfb.d.ts +31 -0
  173. package/dist/dev-events-Ct7QEgKb.d.cts +31 -0
  174. package/dist/dev-log-events-B1_B3guZ.d.cts +47 -0
  175. package/dist/dev-log-events-B1_B3guZ.d.ts +47 -0
  176. package/dist/frames-D-xKuODS.d.cts +686 -0
  177. package/dist/frames-D-xKuODS.d.ts +686 -0
  178. package/dist/game-Db58JNk3.d.cts +77 -0
  179. package/dist/game-bySEy-QO.d.ts +77 -0
  180. package/dist/host-runtime-BuLhGQx5.d.ts +399 -0
  181. package/dist/host-runtime-_06jpW5v.d.cts +399 -0
  182. package/dist/index.cjs +11580 -7584
  183. package/dist/index.cjs.map +1 -1
  184. package/dist/index.d.cts +100 -358
  185. package/dist/index.d.ts +100 -358
  186. package/dist/index.js +414 -1903
  187. package/dist/index.js.map +1 -1
  188. package/dist/input-Xvs80gqG.d.cts +92 -0
  189. package/dist/input-Xvs80gqG.d.ts +92 -0
  190. package/dist/input-bindings-BaEFrgRb.d.cts +129 -0
  191. package/dist/input-bindings-BgsJRLPm.d.ts +129 -0
  192. package/dist/leased-control-BEg4JuXA.d.cts +158 -0
  193. package/dist/leased-control-BEg4JuXA.d.ts +158 -0
  194. package/dist/metadata.cjs +3 -9
  195. package/dist/metadata.cjs.map +1 -1
  196. package/dist/metadata.d.cts +6 -16
  197. package/dist/metadata.d.ts +6 -16
  198. package/dist/metadata.js +8 -76
  199. package/dist/metadata.js.map +1 -1
  200. package/dist/phone-room-session-Ca6rlxJr.d.ts +439 -0
  201. package/dist/phone-room-session-DkPR-K6e.d.cts +439 -0
  202. package/dist/platform-machine.cjs +133 -3
  203. package/dist/platform-machine.cjs.map +1 -1
  204. package/dist/platform-machine.d.cts +525 -27
  205. package/dist/platform-machine.d.ts +525 -27
  206. package/dist/platform-machine.js +119 -4
  207. package/dist/platform-machine.js.map +1 -1
  208. package/dist/{platform-settings-DUWs4JTy.d.cts → platform-settings-Yb0fQ1dl.d.cts} +1 -3
  209. package/dist/{platform-settings-DUWs4JTy.d.ts → platform-settings-Yb0fQ1dl.d.ts} +1 -3
  210. package/dist/prefabs.cjs +134 -3
  211. package/dist/prefabs.cjs.map +1 -1
  212. package/dist/prefabs.d.cts +23 -47
  213. package/dist/prefabs.d.ts +23 -47
  214. package/dist/prefabs.js +23 -4
  215. package/dist/prefabs.js.map +1 -1
  216. package/dist/preview.cjs +2214 -767
  217. package/dist/preview.cjs.map +1 -1
  218. package/dist/preview.d.cts +193 -38
  219. package/dist/preview.d.ts +193 -38
  220. package/dist/preview.js +478 -254
  221. package/dist/preview.js.map +1 -1
  222. package/dist/protocol.cjs +585 -391
  223. package/dist/protocol.cjs.map +1 -1
  224. package/dist/protocol.d.cts +13 -117
  225. package/dist/protocol.d.ts +13 -117
  226. package/dist/protocol.js +43 -80
  227. package/dist/protocol.js.map +1 -1
  228. package/dist/release.cjs.map +1 -1
  229. package/dist/release.d.cts +2 -2
  230. package/dist/release.d.ts +2 -2
  231. package/dist/release.js +1 -1
  232. package/dist/release.js.map +1 -1
  233. package/dist/replay-input-log-BvX4As2f.d.ts +31 -0
  234. package/dist/replay-input-log-Vcl0VDIy.d.cts +31 -0
  235. package/dist/room-protocol.cjs +794 -0
  236. package/dist/room-protocol.cjs.map +1 -0
  237. package/dist/room-protocol.d.cts +63 -0
  238. package/dist/room-protocol.d.ts +63 -0
  239. package/dist/room-protocol.js +143 -0
  240. package/dist/room-protocol.js.map +1 -0
  241. package/dist/room-session.cjs +2336 -0
  242. package/dist/room-session.cjs.map +1 -0
  243. package/dist/room-session.d.cts +77 -0
  244. package/dist/room-session.d.ts +77 -0
  245. package/dist/room-session.js +103 -0
  246. package/dist/room-session.js.map +1 -0
  247. package/dist/runtime/prefab-inspection-bridge.cjs +207 -0
  248. package/dist/runtime/prefab-inspection-bridge.cjs.map +1 -0
  249. package/dist/runtime/prefab-inspection-bridge.d.cts +156 -0
  250. package/dist/runtime/prefab-inspection-bridge.d.ts +156 -0
  251. package/dist/runtime/prefab-inspection-bridge.js +22 -0
  252. package/dist/runtime/prefab-inspection-bridge.js.map +1 -0
  253. package/dist/runtime-control.cjs +2112 -8
  254. package/dist/runtime-control.cjs.map +1 -1
  255. package/dist/runtime-control.d.cts +980 -12
  256. package/dist/runtime-control.d.ts +980 -12
  257. package/dist/runtime-control.js +264 -4
  258. package/dist/runtime-control.js.map +1 -1
  259. package/dist/runtime-inspection.cjs +1222 -558
  260. package/dist/runtime-inspection.cjs.map +1 -1
  261. package/dist/runtime-inspection.d.cts +530 -22
  262. package/dist/runtime-inspection.d.ts +530 -22
  263. package/dist/runtime-inspection.js +21 -22
  264. package/dist/runtime-inspection.js.map +1 -1
  265. package/dist/runtime-reporting-K_ZXpubu.d.cts +43 -0
  266. package/dist/runtime-reporting-K_ZXpubu.d.ts +43 -0
  267. package/dist/runtime-topology.cjs +2 -5
  268. package/dist/runtime-topology.cjs.map +1 -1
  269. package/dist/runtime-topology.d.cts +1 -1
  270. package/dist/runtime-topology.d.ts +1 -1
  271. package/dist/runtime-topology.js +1 -1
  272. package/dist/runtime-topology.js.map +1 -1
  273. package/dist/scoped-connector-CiiWu06D.d.ts +66 -0
  274. package/dist/scoped-connector-D7252pn0.d.cts +66 -0
  275. package/dist/sdk-channels-S6j6AH8v.d.cts +103 -0
  276. package/dist/sdk-channels-S6j6AH8v.d.ts +103 -0
  277. package/dist/simulation-BfRnC4rg.d.ts +782 -0
  278. package/dist/simulation-BwZx2pgt.d.cts +782 -0
  279. package/dist/{standard-match-phase-BzSgBYFg.d.ts → standard-match-phase-D4N-AU0d.d.cts} +3 -13
  280. package/dist/{standard-match-phase-CvJUW8Oe.d.cts → standard-match-phase-abt8ZjCh.d.ts} +3 -13
  281. package/dist/transport-CWF29jU6.d.cts +173 -0
  282. package/dist/transport-CWF29jU6.d.ts +173 -0
  283. package/dist/types-p28maMEo.d.cts +102 -0
  284. package/dist/types-p28maMEo.d.ts +102 -0
  285. package/dist/ui.cjs +2182 -892
  286. package/dist/ui.cjs.map +1 -1
  287. package/dist/ui.d.cts +75 -17
  288. package/dist/ui.d.ts +75 -17
  289. package/dist/ui.js +554 -393
  290. package/dist/ui.js.map +1 -1
  291. package/package.json +38 -21
  292. package/src/agent/agent-action.ts +0 -39
  293. package/src/agent/agent-contract-conformance.ts +8 -1
  294. package/src/agent/agent-contract.ts +2 -4
  295. package/src/agent/agent-evaluator.ts +95 -0
  296. package/src/agent/capture-canvas.ts +79 -0
  297. package/src/agent/host-canvas-capture.ts +189 -0
  298. package/src/agent-tooling.ts +5 -20
  299. package/src/arcade/bridge/controller.ts +8 -11
  300. package/src/arcade/bridge/host.ts +6 -11
  301. package/src/arcade/bridge/iframe.ts +1 -50
  302. package/src/arcade/host.ts +0 -1
  303. package/src/arcade/surface.ts +5 -1
  304. package/src/arcade/url.ts +2 -9
  305. package/src/audio/audio-manager.ts +23 -47
  306. package/src/audio/hooks.tsx +59 -72
  307. package/src/components/controller-player-name-field.tsx +2 -2
  308. package/src/components/controller-primary-action.tsx +1 -1
  309. package/src/components/controls.tsx +398 -0
  310. package/src/components/gamepad-layout.tsx +69 -0
  311. package/src/components/join-url-controls.tsx +5 -1
  312. package/src/components/lifecycle-action-group.tsx +1 -1
  313. package/src/components/player-avatar.tsx +50 -3
  314. package/src/components/room-qr-code.tsx +36 -77
  315. package/src/components/stage-capture-surface.tsx +91 -0
  316. package/src/components/surface-viewport.tsx +16 -3
  317. package/src/components/ui/button.tsx +1 -1
  318. package/src/constants.ts +0 -15
  319. package/src/context/air-jam-context.tsx +56 -187
  320. package/src/context/session-providers.tsx +13 -10
  321. package/src/controller-bridge.ts +7 -0
  322. package/src/core/assets.ts +48 -0
  323. package/src/core/config.ts +70 -0
  324. package/src/core/connection-store.ts +77 -0
  325. package/src/core/controller-input.ts +147 -0
  326. package/src/core/controller-runtime.ts +427 -0
  327. package/src/core/dev-events.ts +18 -0
  328. package/src/core/environment.ts +132 -0
  329. package/src/core/game-description.ts +44 -0
  330. package/src/core/game.ts +130 -0
  331. package/src/core/host-input.ts +207 -0
  332. package/src/core/host-runtime.ts +988 -0
  333. package/src/core/hosted-rooms.ts +26 -0
  334. package/src/core/input-bindings.ts +180 -0
  335. package/src/core/input-log.ts +144 -0
  336. package/src/core/input.ts +228 -0
  337. package/src/core/local-input.ts +319 -0
  338. package/src/core/replay-input-log.ts +298 -0
  339. package/src/core/replicated-store.ts +1178 -0
  340. package/src/core/room-action-ack.ts +43 -0
  341. package/src/core/settings.ts +202 -0
  342. package/src/core/simulation.ts +307 -0
  343. package/src/core/theme.ts +33 -0
  344. package/src/core.ts +162 -0
  345. package/src/dev/browser-log-sink.ts +35 -12
  346. package/src/diagnostics.ts +5 -6
  347. package/src/hooks/internal/use-controller-runtime-api.ts +58 -925
  348. package/src/hooks/internal/use-host-runtime-api.ts +98 -1270
  349. package/src/hooks/internal/use-runtime-inspection-contract.ts +14 -2
  350. package/src/hooks/use-air-jam-controller.ts +32 -53
  351. package/src/hooks/use-air-jam-host.ts +59 -100
  352. package/src/hooks/use-air-jam-settings.ts +27 -0
  353. package/src/hooks/use-controller-toasts.ts +16 -19
  354. package/src/hooks/use-host-agent-capture.ts +31 -0
  355. package/src/hooks/use-lifecycle-action-group-model.ts +1 -1
  356. package/src/hooks/use-send-signal.ts +23 -156
  357. package/src/hooks/use-simulation.ts +83 -0
  358. package/src/index.ts +24 -85
  359. package/src/lifecycle/index.ts +0 -4
  360. package/src/lifecycle/standard-match-phase.ts +1 -22
  361. package/src/metadata/manifest.ts +8 -19
  362. package/src/metadata.ts +1 -1
  363. package/src/platform-machine.ts +127 -3
  364. package/src/prefabs/types.ts +91 -20
  365. package/src/prefabs/view.ts +82 -0
  366. package/src/prefabs.ts +19 -0
  367. package/src/preview/host-workspace.tsx +4 -9
  368. package/src/preview/identity.ts +31 -23
  369. package/src/preview/layout.ts +5 -1
  370. package/src/preview/manager.ts +205 -78
  371. package/src/preview/messages.ts +47 -0
  372. package/src/preview/ownership.ts +6 -1
  373. package/src/preview/url.ts +46 -23
  374. package/src/preview/window.tsx +26 -69
  375. package/src/preview/workspace-local-seats.ts +166 -0
  376. package/src/preview/workspace.tsx +89 -37
  377. package/src/preview.ts +27 -15
  378. package/src/protocol/actions.ts +58 -0
  379. package/src/protocol/arcade-platform-actions.ts +2 -16
  380. package/src/protocol/controller.ts +14 -174
  381. package/src/protocol/core.ts +8 -15
  382. package/src/protocol/dev-log-events.ts +5 -81
  383. package/src/protocol/leased-control.ts +177 -0
  384. package/src/protocol/room/addressing.ts +35 -0
  385. package/src/protocol/room/close-codes.ts +33 -0
  386. package/src/protocol/room/frames.ts +343 -0
  387. package/src/protocol/room/input-codec.ts +182 -0
  388. package/src/protocol/room/limits.ts +58 -0
  389. package/src/protocol/room/patch.ts +135 -0
  390. package/src/protocol/room/sdk-channels.ts +81 -0
  391. package/src/protocol/room/seat-id.ts +31 -0
  392. package/src/protocol/room/transport.ts +63 -0
  393. package/src/protocol/room/weight.ts +58 -0
  394. package/src/protocol/runtime-reporting.ts +56 -10
  395. package/src/protocol.ts +2 -7
  396. package/src/qrcode.d.ts +3 -13
  397. package/src/room-protocol.ts +10 -0
  398. package/src/room-session/browser-wake-events.ts +14 -0
  399. package/src/room-session/channel-state.ts +293 -0
  400. package/src/room-session/clock.ts +24 -0
  401. package/src/room-session/host-room-session.ts +379 -0
  402. package/src/room-session/input-lane.ts +125 -0
  403. package/src/room-session/listeners.ts +22 -0
  404. package/src/room-session/loopback-link.ts +58 -0
  405. package/src/room-session/phone-room-session.ts +368 -0
  406. package/src/room-session/port-link.ts +116 -0
  407. package/src/room-session/room-key.ts +9 -0
  408. package/src/room-session/roster.ts +23 -0
  409. package/src/room-session/scoped-connector.ts +577 -0
  410. package/src/room-session/session-link.ts +306 -0
  411. package/src/room-session/web-socket-link.ts +57 -0
  412. package/src/room-session.ts +12 -0
  413. package/src/runtime/air-jam-config.ts +49 -37
  414. package/src/runtime/air-jam-error-boundary.tsx +9 -3
  415. package/src/runtime/arcade-runtime-url.ts +8 -9
  416. package/src/runtime/browser-controller-environment.ts +116 -0
  417. package/src/runtime/browser-host-environment.ts +137 -0
  418. package/src/runtime/browser-replay.ts +211 -0
  419. package/src/runtime/browser-room.ts +41 -0
  420. package/src/runtime/connected-runtime-error-boundary.tsx +35 -8
  421. package/src/runtime/contracts/agent-control.ts +195 -0
  422. package/src/runtime/contracts/clip.ts +169 -0
  423. package/src/runtime/contracts/control.ts +653 -16
  424. package/src/runtime/contracts/controller-agent.ts +130 -0
  425. package/src/runtime/contracts/input-log.ts +38 -0
  426. package/src/runtime/contracts/inspection.ts +25 -22
  427. package/src/runtime/contracts/observation.ts +186 -0
  428. package/src/runtime/contracts/runtime-identity.ts +43 -0
  429. package/src/runtime/contracts/timeline.ts +59 -0
  430. package/src/runtime/controller-agent-bridge.ts +152 -0
  431. package/src/runtime/controller-bridge-context.ts +29 -0
  432. package/src/runtime/controller-capture.ts +50 -0
  433. package/src/runtime/controller-identity.ts +53 -142
  434. package/src/runtime/controller-presentation.ts +47 -17
  435. package/src/runtime/controller-press.ts +271 -0
  436. package/src/runtime/create-air-jam-app.tsx +103 -74
  437. package/src/runtime/dev-runtime-events.ts +6 -18
  438. package/src/runtime/embedded-parent.ts +22 -0
  439. package/src/runtime/embedded-runtime-adapters.ts +10 -9
  440. package/src/runtime/host-agent-bridge.ts +127 -0
  441. package/src/runtime/host-capture-boundary.tsx +92 -0
  442. package/src/runtime/host-capture-context.ts +7 -0
  443. package/src/runtime/host-clip-reader.ts +93 -0
  444. package/src/runtime/host-clip-recorder.ts +342 -0
  445. package/src/runtime/host-input-log-reader.ts +120 -0
  446. package/src/runtime/host-observation.ts +207 -0
  447. package/src/runtime/host-pace.ts +36 -0
  448. package/src/runtime/host-runtime-fault.ts +51 -0
  449. package/src/runtime/host-timeline.ts +152 -0
  450. package/src/runtime/local-players.tsx +96 -0
  451. package/src/runtime/local-seats.ts +612 -0
  452. package/src/runtime/participant-control.ts +162 -0
  453. package/src/runtime/prefab-inspection-bridge.ts +174 -0
  454. package/src/runtime/prefab-inspection-clock.ts +12 -0
  455. package/src/runtime/prefab-inspection-context.ts +20 -0
  456. package/src/runtime/prefab-inspection-runtime.tsx +328 -0
  457. package/src/runtime/preview-inspection-bridge.ts +130 -0
  458. package/src/runtime/replay-runtime.tsx +101 -0
  459. package/src/runtime/room-bridge.ts +110 -0
  460. package/src/runtime/runtime-owner-contexts.tsx +9 -0
  461. package/src/runtime/runtime-session-params.ts +20 -23
  462. package/src/runtime/session-runtimes.tsx +231 -64
  463. package/src/runtime/stage-capture.ts +25 -0
  464. package/src/runtime-control.ts +41 -0
  465. package/src/runtime-inspection.ts +14 -7
  466. package/src/runtime-topology.ts +7 -8
  467. package/src/settings/platform-settings-runtime.tsx +47 -2
  468. package/src/settings/platform-settings.ts +0 -65
  469. package/src/store/use-air-jam-store.ts +73 -0
  470. package/src/ui.ts +3 -3
  471. package/src/utils/is-rpc-serializable.ts +11 -19
  472. package/src/utils/url-builder.ts +0 -7
  473. package/dist/air-jam-context-BlLPvCup.d.cts +0 -175
  474. package/dist/air-jam-context-DTsxF-tP.d.ts +0 -175
  475. package/dist/arcade/bridge.cjs +0 -1087
  476. package/dist/arcade/bridge.cjs.map +0 -1
  477. package/dist/arcade/bridge.d.cts +0 -11
  478. package/dist/arcade/bridge.d.ts +0 -11
  479. package/dist/arcade/bridge.js +0 -78
  480. package/dist/arcade/bridge.js.map +0 -1
  481. package/dist/arcade-runtime-url-BW-MUAOY.d.cts +0 -28
  482. package/dist/arcade-runtime-url-l8qj01Pg.d.ts +0 -28
  483. package/dist/arcade.cjs +0 -1767
  484. package/dist/arcade.cjs.map +0 -1
  485. package/dist/arcade.d.cts +0 -18
  486. package/dist/arcade.d.ts +0 -18
  487. package/dist/arcade.js +0 -129
  488. package/dist/arcade.js.map +0 -1
  489. package/dist/chunk-2SZ2YYGJ.js +0 -280
  490. package/dist/chunk-2SZ2YYGJ.js.map +0 -1
  491. package/dist/chunk-32RSSFSF.js +0 -214
  492. package/dist/chunk-32RSSFSF.js.map +0 -1
  493. package/dist/chunk-3USU7GY2.js.map +0 -1
  494. package/dist/chunk-3YMUAKPU.js +0 -10
  495. package/dist/chunk-3YMUAKPU.js.map +0 -1
  496. package/dist/chunk-56DM2KEW.js +0 -14
  497. package/dist/chunk-56DM2KEW.js.map +0 -1
  498. package/dist/chunk-BE6Z4SIT.js.map +0 -1
  499. package/dist/chunk-CM53YLT5.js +0 -59
  500. package/dist/chunk-CM53YLT5.js.map +0 -1
  501. package/dist/chunk-CV3PBXPT.js.map +0 -1
  502. package/dist/chunk-D4VDEVTZ.js.map +0 -1
  503. package/dist/chunk-EVZJA6RN.js.map +0 -1
  504. package/dist/chunk-FUA6EMSJ.js +0 -90
  505. package/dist/chunk-FUA6EMSJ.js.map +0 -1
  506. package/dist/chunk-GMLU7RI5.js +0 -70
  507. package/dist/chunk-GMLU7RI5.js.map +0 -1
  508. package/dist/chunk-IG6GZZSS.js.map +0 -1
  509. package/dist/chunk-IKKDONQL.js +0 -1
  510. package/dist/chunk-IKKDONQL.js.map +0 -1
  511. package/dist/chunk-ITMQSBTH.js +0 -26
  512. package/dist/chunk-ITMQSBTH.js.map +0 -1
  513. package/dist/chunk-J5MCII33.js +0 -620
  514. package/dist/chunk-J5MCII33.js.map +0 -1
  515. package/dist/chunk-JTF47B56.js +0 -1
  516. package/dist/chunk-JTF47B56.js.map +0 -1
  517. package/dist/chunk-K4OZ54UD.js.map +0 -1
  518. package/dist/chunk-LIHEEAVE.js +0 -191
  519. package/dist/chunk-LIHEEAVE.js.map +0 -1
  520. package/dist/chunk-LIXPF4P6.js +0 -22
  521. package/dist/chunk-LIXPF4P6.js.map +0 -1
  522. package/dist/chunk-MIMPMB7O.js.map +0 -1
  523. package/dist/chunk-MPDMJIX5.js +0 -1
  524. package/dist/chunk-MPDMJIX5.js.map +0 -1
  525. package/dist/chunk-O6X7FJ6N.js.map +0 -1
  526. package/dist/chunk-PSUYTD2L.js.map +0 -1
  527. package/dist/chunk-QO4KFUEI.js +0 -32
  528. package/dist/chunk-QO4KFUEI.js.map +0 -1
  529. package/dist/chunk-QTLYZADF.js +0 -125
  530. package/dist/chunk-QTLYZADF.js.map +0 -1
  531. package/dist/chunk-TGRTEWYV.js +0 -195
  532. package/dist/chunk-TGRTEWYV.js.map +0 -1
  533. package/dist/chunk-TTQDHKXL.js +0 -3017
  534. package/dist/chunk-TTQDHKXL.js.map +0 -1
  535. package/dist/chunk-UCPY7UJC.js +0 -8
  536. package/dist/chunk-UCPY7UJC.js.map +0 -1
  537. package/dist/chunk-UPV6YWT5.js +0 -43
  538. package/dist/chunk-UPV6YWT5.js.map +0 -1
  539. package/dist/chunk-UWJOIVON.js.map +0 -1
  540. package/dist/chunk-W2VK36RO.js +0 -11
  541. package/dist/chunk-W2VK36RO.js.map +0 -1
  542. package/dist/chunk-X24K52DG.js.map +0 -1
  543. package/dist/chunk-X35LLCWV.js.map +0 -1
  544. package/dist/chunk-YXHH3MQT.js +0 -230
  545. package/dist/chunk-YXHH3MQT.js.map +0 -1
  546. package/dist/controller-PZEM_1cH.d.ts +0 -176
  547. package/dist/controller-vj82tKm4.d.cts +0 -176
  548. package/dist/dev-log-events-BCJKmygo.d.cts +0 -120
  549. package/dist/dev-log-events-BCJKmygo.d.ts +0 -120
  550. package/dist/handshake-CC_LrK5g.d.cts +0 -31
  551. package/dist/handshake-CC_LrK5g.d.ts +0 -31
  552. package/dist/host-B9pRy0Aa.d.cts +0 -122
  553. package/dist/host-DylGsX7p.d.ts +0 -122
  554. package/dist/notices-C4bao3oi.d.ts +0 -38
  555. package/dist/notices-DNdOjwtj.d.cts +0 -38
  556. package/dist/realtime-client-Cu8yVJFw.d.cts +0 -15
  557. package/dist/realtime-client-Cu8yVJFw.d.ts +0 -15
  558. package/dist/runtime-reporting-pe-eryVz.d.cts +0 -27
  559. package/dist/runtime-reporting-pe-eryVz.d.ts +0 -27
  560. package/dist/signals-ZHftIKuc.d.cts +0 -33
  561. package/dist/signals-ZHftIKuc.d.ts +0 -33
  562. package/dist/sync-xtPfWhif.d.cts +0 -81
  563. package/dist/sync-xtPfWhif.d.ts +0 -81
  564. package/src/arcade/bridge.ts +0 -3
  565. package/src/arcade.ts +0 -4
  566. package/src/context/socket-manager.ts +0 -72
  567. package/src/events.ts +0 -119
  568. package/src/hooks/use-connection-status.ts +0 -8
  569. package/src/hooks/use-controller-tick.ts +0 -65
  570. package/src/hooks/use-get-input.ts +0 -100
  571. package/src/hooks/use-host-arcade-restore.ts +0 -35
  572. package/src/hooks/use-host-tick.ts +0 -171
  573. package/src/hooks/use-input-writer.ts +0 -83
  574. package/src/hooks/use-players.ts +0 -12
  575. package/src/internal/input-manager.ts +0 -356
  576. package/src/protocol/errors.ts +0 -21
  577. package/src/protocol/host-grant.ts +0 -103
  578. package/src/protocol/host.ts +0 -150
  579. package/src/protocol/notices.ts +0 -43
  580. package/src/protocol/signals.ts +0 -38
  581. package/src/protocol/socket-events.ts +0 -152
  582. package/src/protocol/sync.ts +0 -105
  583. package/src/runtime/admission-retry.ts +0 -62
  584. package/src/runtime/bridge-envelope-args.ts +0 -21
  585. package/src/runtime/controller-bridge.ts +0 -439
  586. package/src/runtime/controller-realtime-client.ts +0 -552
  587. package/src/runtime/host-bridge.ts +0 -380
  588. package/src/runtime/host-realtime-client.ts +0 -550
  589. package/src/runtime/realtime-client.ts +0 -20
  590. package/src/runtime/validate-arcade-bridge-attach.ts +0 -14
  591. package/src/state/connection-store.ts +0 -159
  592. package/src/store/create-air-jam-store.ts +0 -1193
  593. package/src/store/index.ts +0 -1
  594. package/src/utils/ids.ts +0 -58
@@ -0,0 +1,2336 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/room-session.ts
21
+ var room_session_exports = {};
22
+ __export(room_session_exports, {
23
+ ChannelMirror: () => ChannelMirror,
24
+ ChannelPublisher: () => ChannelPublisher,
25
+ DEFAULT_HEARTBEAT: () => DEFAULT_HEARTBEAT,
26
+ DEFAULT_HELLO_ANSWER_WITHIN_MS: () => DEFAULT_HELLO_ANSWER_WITHIN_MS,
27
+ DEFAULT_REQUEST_TIMEOUT_MS: () => DEFAULT_REQUEST_TIMEOUT_MS,
28
+ DEFAULT_RETRY: () => DEFAULT_RETRY,
29
+ HostInputDecoder: () => HostInputDecoder,
30
+ HostRoomSession: () => HostRoomSession,
31
+ PhoneInputLane: () => PhoneInputLane,
32
+ PhoneRoomSession: () => PhoneRoomSession,
33
+ SESSION_SDK: () => SESSION_SDK,
34
+ STICK_CHANGE_HUNDREDTHS: () => STICK_CHANGE_HUNDREDTHS,
35
+ SessionLink: () => SessionLink,
36
+ browserDeviceWakeEvents: () => browserDeviceWakeEvents,
37
+ createLoopbackConnector: () => createLoopbackConnector,
38
+ createPortConnector: () => createPortConnector,
39
+ createRoomKey: () => createRoomKey,
40
+ createScopedHostConnector: () => createScopedHostConnector,
41
+ createScopedPhoneConnector: () => createScopedPhoneConnector,
42
+ createWebSocketConnector: () => createWebSocketConnector,
43
+ roomSocketUrls: () => roomSocketUrls,
44
+ serveRoomPort: () => serveRoomPort,
45
+ spacingForRate: () => spacingForRate,
46
+ systemRoomClock: () => systemRoomClock
47
+ });
48
+ module.exports = __toCommonJS(room_session_exports);
49
+
50
+ // src/room-session/browser-wake-events.ts
51
+ var browserDeviceWakeEvents = (wake) => {
52
+ const onVisibility = () => {
53
+ if (document.visibilityState === "visible") wake();
54
+ };
55
+ window.addEventListener("online", wake);
56
+ document.addEventListener("visibilitychange", onVisibility);
57
+ return () => {
58
+ window.removeEventListener("online", wake);
59
+ document.removeEventListener("visibilitychange", onVisibility);
60
+ };
61
+ };
62
+
63
+ // src/protocol/room/addressing.ts
64
+ var import_zod = require("zod");
65
+ var roomCodeSchema = import_zod.z.string().regex(/^[A-Z0-9]{4,8}$/);
66
+ var roomPath = (address) => address.role === "phone" ? `/v1/play/${address.code}` : address.code === null ? "/v1/host" : `/v1/host/${address.code}`;
67
+
68
+ // src/protocol/room/close-codes.ts
69
+ var roomCloseCodes = {
70
+ replaced: { code: 4e3, terminal: true },
71
+ removed: { code: 4001, terminal: true },
72
+ left: { code: 4002, terminal: true },
73
+ closed: { code: 4003, terminal: true },
74
+ "not-found": { code: 4004, terminal: true },
75
+ full: { code: 4005, terminal: true },
76
+ unauthorised: { code: 4006, terminal: true },
77
+ "unsupported-version": { code: 4007, terminal: true },
78
+ "limits-broken": { code: 4008, terminal: true },
79
+ restarting: { code: 4100, terminal: false },
80
+ "try-later": { code: 4101, terminal: false }
81
+ };
82
+ var roomCloseReasonForCode = (code) => {
83
+ for (const [reason, entry] of Object.entries(roomCloseCodes))
84
+ if (entry.code === code) return reason;
85
+ return null;
86
+ };
87
+
88
+ // src/protocol/room/frames.ts
89
+ var import_zod4 = require("zod");
90
+
91
+ // src/protocol/room/limits.ts
92
+ var import_zod2 = require("zod");
93
+ var MAXIMUM_ROOM_SEATS = 16;
94
+ var count = import_zod2.z.number().int().positive();
95
+ var duration = import_zod2.z.number().int().nonnegative();
96
+ var roomLimitsShape = {
97
+ seats: count.max(MAXIMUM_ROOM_SEATS),
98
+ channels: count,
99
+ /** How often a phone may send its controls; phones coalesce to it. */
100
+ inputIntervalMs: count,
101
+ /** One phone's whole control state; a host input record states its length in one byte. */
102
+ inputBytes: count.max(255),
103
+ inputsPerSecond: count,
104
+ /** The most a channel's document, or any one state frame, may weigh. */
105
+ stateBytes: count,
106
+ statesPerSecond: count,
107
+ /** The most any other text frame may weigh. */
108
+ frameBytes: count,
109
+ /** Text frames other than state, per connection. */
110
+ framesPerSecond: count,
111
+ /** Frames that do not parse, within one second, before the connection is closed. */
112
+ strikesPerSecond: count,
113
+ seatHoldMs: duration,
114
+ /** How long the room waits for its host, as it opens and after the host's connection ends. */
115
+ hostGraceMs: count,
116
+ maximumAgeMs: count
117
+ };
118
+ var roomLimitsSchema = import_zod2.z.strictObject(roomLimitsShape);
119
+ var roomLimitsWireSchema = import_zod2.z.object(roomLimitsShape);
120
+ var DEFAULT_ROOM_LIMITS = Object.freeze({
121
+ seats: MAXIMUM_ROOM_SEATS,
122
+ channels: 8,
123
+ inputIntervalMs: 16,
124
+ inputBytes: 64,
125
+ inputsPerSecond: 120,
126
+ stateBytes: 65536,
127
+ statesPerSecond: 60,
128
+ frameBytes: 8192,
129
+ framesPerSecond: 60,
130
+ strikesPerSecond: 64,
131
+ seatHoldMs: 12e4,
132
+ hostGraceMs: 6e4,
133
+ maximumAgeMs: 24 * 60 * 60 * 1e3
134
+ });
135
+
136
+ // src/protocol/room/patch.ts
137
+ var isPlainObject = (value) => {
138
+ if (typeof value !== "object" || value === null || Array.isArray(value))
139
+ return false;
140
+ const prototype = Object.getPrototypeOf(value);
141
+ return prototype === Object.prototype || prototype === null;
142
+ };
143
+ var ownValue = (object, key) => Object.hasOwn(object, key) ? object[key] : void 0;
144
+ var diffState = (previous, next) => {
145
+ const set = [];
146
+ const unset = [];
147
+ const walk = (before, after, path) => {
148
+ for (const key of Object.keys(before))
149
+ if (before[key] !== void 0 && ownValue(after, key) === void 0)
150
+ unset.push([...path, key]);
151
+ for (const key of Object.keys(after)) {
152
+ const value = after[key];
153
+ if (value === void 0) continue;
154
+ const old = ownValue(before, key);
155
+ if (old === value) continue;
156
+ if (isPlainObject(old) && isPlainObject(value))
157
+ walk(old, value, [...path, key]);
158
+ else set.push([[...path, key], value]);
159
+ }
160
+ };
161
+ walk(previous, next, []);
162
+ return { set, unset };
163
+ };
164
+ var isEmptyStatePatch = (patch) => patch.set.length === 0 && patch.unset.length === 0;
165
+ var defineEntry = (object, key, value) => Object.defineProperty(object, key, {
166
+ value,
167
+ writable: true,
168
+ enumerable: true,
169
+ configurable: true
170
+ });
171
+ var applyStatePatch = (document2, patch, replaced) => {
172
+ if (isEmptyStatePatch(patch)) return document2;
173
+ const copies = /* @__PURE__ */ new Set();
174
+ const writable = (object) => {
175
+ if (copies.has(object)) return object;
176
+ const copy2 = { ...object };
177
+ copies.add(copy2);
178
+ return copy2;
179
+ };
180
+ const root = writable(document2);
181
+ const parentOf = (path) => {
182
+ let parent = root;
183
+ for (const key of path.slice(0, -1)) {
184
+ const child = ownValue(parent, key);
185
+ if (!isPlainObject(child)) return null;
186
+ const copy2 = writable(child);
187
+ if (copy2 !== child) defineEntry(parent, key, copy2);
188
+ parent = copy2;
189
+ }
190
+ return parent;
191
+ };
192
+ for (const path of patch.unset) {
193
+ const key = path.at(-1);
194
+ const parent = parentOf(path);
195
+ if (key === void 0 || !parent || !Object.hasOwn(parent, key))
196
+ return null;
197
+ replaced?.(key, ownValue(parent, key), void 0);
198
+ delete parent[key];
199
+ }
200
+ for (const [path, value] of patch.set) {
201
+ const key = path.at(-1);
202
+ const parent = parentOf(path);
203
+ if (key === void 0 || !parent) return null;
204
+ replaced?.(key, ownValue(parent, key), value);
205
+ defineEntry(parent, key, value);
206
+ }
207
+ return root;
208
+ };
209
+
210
+ // src/protocol/room/seat-id.ts
211
+ var import_zod3 = require("zod");
212
+ var MAXIMUM_SEAT_NUMBER = 65535;
213
+ var seatIdSchema = import_zod3.z.string().regex(/^p[1-9][0-9]{0,4}$/);
214
+ var seatIdFromNumber = (seatNumber) => {
215
+ if (!Number.isInteger(seatNumber) || seatNumber < 1 || seatNumber > MAXIMUM_SEAT_NUMBER)
216
+ throw new Error(`Seat number ${seatNumber} is out of range.`);
217
+ return `p${seatNumber}`;
218
+ };
219
+ var seatNumberFromId = (seatId) => {
220
+ const seatNumber = Number(seatId.slice(1));
221
+ if (!seatIdSchema.safeParse(seatId).success || seatNumber > MAXIMUM_SEAT_NUMBER)
222
+ throw new Error(`"${seatId}" is not a seat id.`);
223
+ return seatNumber;
224
+ };
225
+
226
+ // src/protocol/room/frames.ts
227
+ var PING_FRAME = "ping";
228
+ var PONG_FRAME = "pong";
229
+ var MAXIMUM_FRAME_DEPTH = 32;
230
+ var keySchema = import_zod4.z.string().min(16).max(128);
231
+ var instanceSchema = import_zod4.z.string().min(1).max(64);
232
+ var channelSchema = import_zod4.z.string().min(1).max(128);
233
+ var revisionSchema = import_zod4.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
234
+ var requestIdSchema = import_zod4.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
235
+ var featuresSchema = import_zod4.z.array(import_zod4.z.string().min(1).max(64)).max(32);
236
+ var documentSchema = import_zod4.z.custom(isPlainObject, {
237
+ message: "A state document is a plain JSON object."
238
+ });
239
+ var pathSchema = import_zod4.z.array(import_zod4.z.string()).min(1).max(32);
240
+ var seatKindSchema = import_zod4.z.enum(["phone", "preview", "agent"]);
241
+ var seatProfileSchema = import_zod4.z.object({
242
+ label: import_zod4.z.string().trim().min(1).max(24).optional(),
243
+ avatarId: import_zod4.z.string().trim().min(1).max(48).optional(),
244
+ /** Shown instead of the label while a local seat plays through this phone. */
245
+ localSeatLabel: import_zod4.z.string().trim().min(1).max(32).optional()
246
+ });
247
+ var helloFields = {
248
+ type: import_zod4.z.literal("hello"),
249
+ key: keySchema,
250
+ instance: instanceSchema.optional(),
251
+ sdk: import_zod4.z.string().min(1).max(64),
252
+ features: featuresSchema.optional()
253
+ };
254
+ var hostHelloSchema = import_zod4.z.object({
255
+ ...helloFields,
256
+ /** Opaque to the room; the gate reads it before the room opens. */
257
+ credential: import_zod4.z.string().min(1).max(8192).optional(),
258
+ /** How many players the game takes; the room admits no more. */
259
+ seats: import_zod4.z.number().int().min(1).max(MAXIMUM_ROOM_SEATS)
260
+ });
261
+ var phoneHelloSchema = import_zod4.z.object({
262
+ ...helloFields,
263
+ kind: seatKindSchema,
264
+ profile: seatProfileSchema.optional(),
265
+ /**
266
+ * The page this phone runs in, the same across its reconnects. A seat
267
+ * resumed from another page (a reload, or another tab taking it over)
268
+ * starts its controls afresh, so the host takes a new input baseline.
269
+ */
270
+ page: import_zod4.z.string().min(1).max(64).optional()
271
+ });
272
+ var statePatchFields = {
273
+ type: import_zod4.z.literal("state"),
274
+ channel: channelSchema,
275
+ revision: revisionSchema,
276
+ base: revisionSchema,
277
+ set: import_zod4.z.array(import_zod4.z.tuple([pathSchema, import_zod4.z.unknown()])).default([]),
278
+ unset: import_zod4.z.array(pathSchema).default([])
279
+ };
280
+ var stateDocumentFields = {
281
+ type: import_zod4.z.literal("state"),
282
+ channel: channelSchema,
283
+ revision: revisionSchema,
284
+ document: documentSchema
285
+ };
286
+ var hostStateFrameSchema = import_zod4.z.union([
287
+ import_zod4.z.object({
288
+ ...stateDocumentFields,
289
+ /** The store's shape, so a reloading host knows whether to take its state back. */
290
+ fingerprint: import_zod4.z.string().min(1).max(256).optional(),
291
+ /** A top-level field keyed by seat whose entries only their own seat sees. */
292
+ private: import_zod4.z.string().min(1).max(128).optional()
293
+ }),
294
+ import_zod4.z.object(statePatchFields).refine(
295
+ (frame) => frame.revision > frame.base,
296
+ "A patch produces a later revision than its base."
297
+ )
298
+ ]);
299
+ var hostToRoomFrameSchemas = {
300
+ state: hostStateFrameSchema,
301
+ response: import_zod4.z.object({
302
+ type: import_zod4.z.literal("response"),
303
+ seat: seatIdSchema,
304
+ id: requestIdSchema,
305
+ result: import_zod4.z.unknown().optional()
306
+ }),
307
+ signal: import_zod4.z.object({
308
+ type: import_zod4.z.literal("signal"),
309
+ seat: seatIdSchema.optional(),
310
+ kind: import_zod4.z.string().min(1).max(64),
311
+ payload: import_zod4.z.unknown().optional()
312
+ }),
313
+ room: import_zod4.z.object({
314
+ type: import_zod4.z.literal("room"),
315
+ seats: import_zod4.z.number().int().min(1).max(MAXIMUM_ROOM_SEATS).optional(),
316
+ locked: import_zod4.z.boolean().optional()
317
+ }),
318
+ remove: import_zod4.z.object({ type: import_zod4.z.literal("remove"), seat: seatIdSchema }),
319
+ drop: import_zod4.z.object({ type: import_zod4.z.literal("drop"), channel: channelSchema }),
320
+ activity: import_zod4.z.object({
321
+ type: import_zod4.z.literal("activity"),
322
+ activity: import_zod4.z.string().min(1).max(128).nullable()
323
+ }),
324
+ end: import_zod4.z.object({ type: import_zod4.z.literal("end") })
325
+ };
326
+ var phoneToRoomFrameSchemas = {
327
+ request: import_zod4.z.object({
328
+ type: import_zod4.z.literal("request"),
329
+ id: requestIdSchema,
330
+ channel: channelSchema,
331
+ name: import_zod4.z.string().min(1).max(128),
332
+ payload: import_zod4.z.unknown().optional()
333
+ }),
334
+ profile: import_zod4.z.object({
335
+ type: import_zod4.z.literal("profile"),
336
+ label: seatProfileSchema.shape.label,
337
+ avatarId: seatProfileSchema.shape.avatarId
338
+ }).refine(
339
+ (frame) => frame.label !== void 0 || frame.avatarId !== void 0,
340
+ "A profile change names a label or an avatar."
341
+ ),
342
+ leave: import_zod4.z.object({ type: import_zod4.z.literal("leave") }),
343
+ /** This seat's controls start again from zero, as a newly loaded controller frame's do. */
344
+ baseline: import_zod4.z.object({ type: import_zod4.z.literal("baseline") })
345
+ };
346
+ var seatViewSchema = import_zod4.z.object({
347
+ id: seatIdSchema,
348
+ label: import_zod4.z.string(),
349
+ color: import_zod4.z.string(),
350
+ avatarId: import_zod4.z.string().optional(),
351
+ kind: seatKindSchema,
352
+ connected: import_zod4.z.boolean()
353
+ });
354
+ var channelCopySchema = import_zod4.z.object({
355
+ channel: channelSchema,
356
+ revision: revisionSchema,
357
+ document: documentSchema,
358
+ fingerprint: import_zod4.z.string().optional(),
359
+ private: import_zod4.z.string().optional()
360
+ });
361
+ var welcomeFields = {
362
+ type: import_zod4.z.literal("welcome"),
363
+ code: import_zod4.z.string(),
364
+ instance: instanceSchema,
365
+ seats: import_zod4.z.array(seatViewSchema),
366
+ channels: import_zod4.z.array(channelCopySchema),
367
+ limits: roomLimitsWireSchema,
368
+ features: featuresSchema
369
+ };
370
+ var roomStateFrameSchema = import_zod4.z.union([
371
+ import_zod4.z.object(stateDocumentFields),
372
+ import_zod4.z.object(statePatchFields)
373
+ ]);
374
+ var roomToHostFrameSchemas = {
375
+ welcome: import_zod4.z.object({
376
+ ...welcomeFields,
377
+ /** Seats the room admits, and whether it admits new players at all. */
378
+ seatsWanted: import_zod4.z.number().int().min(1).max(MAXIMUM_ROOM_SEATS),
379
+ locked: import_zod4.z.boolean(),
380
+ activity: import_zod4.z.string().nullable()
381
+ }),
382
+ wait: import_zod4.z.object({
383
+ type: import_zod4.z.literal("wait"),
384
+ position: import_zod4.z.number().int().positive()
385
+ }),
386
+ seat: import_zod4.z.object({
387
+ type: import_zod4.z.literal("seat"),
388
+ seat: seatViewSchema,
389
+ /** The seat's controls restart from a new page: decode them afresh. */
390
+ inputBaseline: import_zod4.z.literal(true).optional()
391
+ }),
392
+ left: import_zod4.z.object({ type: import_zod4.z.literal("left"), seat: seatIdSchema }),
393
+ need: import_zod4.z.object({ type: import_zod4.z.literal("need"), channel: channelSchema }),
394
+ request: import_zod4.z.object({
395
+ type: import_zod4.z.literal("request"),
396
+ seat: seatIdSchema,
397
+ id: requestIdSchema,
398
+ channel: channelSchema,
399
+ name: import_zod4.z.string(),
400
+ payload: import_zod4.z.unknown().optional()
401
+ })
402
+ };
403
+ var roomToPhoneFrameSchemas = {
404
+ welcome: import_zod4.z.object({
405
+ ...welcomeFields,
406
+ seat: seatIdSchema,
407
+ host: import_zod4.z.boolean()
408
+ }),
409
+ seat: roomToHostFrameSchemas.seat,
410
+ left: roomToHostFrameSchemas.left,
411
+ host: import_zod4.z.object({ type: import_zod4.z.literal("host"), present: import_zod4.z.boolean() }),
412
+ state: roomStateFrameSchema,
413
+ drop: hostToRoomFrameSchemas.drop,
414
+ // The refusal comes first: a result may be absent, so the other branch
415
+ // would accept a refusal and strip what it says.
416
+ response: import_zod4.z.union([
417
+ import_zod4.z.object({
418
+ type: import_zod4.z.literal("response"),
419
+ id: requestIdSchema,
420
+ /** The room answered itself because no host could. */
421
+ refused: import_zod4.z.literal("host-away")
422
+ }),
423
+ import_zod4.z.object({
424
+ type: import_zod4.z.literal("response"),
425
+ id: requestIdSchema,
426
+ result: import_zod4.z.unknown().optional()
427
+ })
428
+ ]),
429
+ signal: import_zod4.z.object({
430
+ type: import_zod4.z.literal("signal"),
431
+ kind: import_zod4.z.string(),
432
+ payload: import_zod4.z.unknown().optional()
433
+ })
434
+ };
435
+ var nestsWithin = (value, depth) => {
436
+ if (typeof value !== "object" || value === null) return true;
437
+ if (depth === 0) return false;
438
+ for (const child of Object.values(value))
439
+ if (!nestsWithin(child, depth - 1)) return false;
440
+ return true;
441
+ };
442
+ var TOO_DEEP = /* @__PURE__ */ Symbol("too deep");
443
+ var parseJson = (text) => {
444
+ let value;
445
+ try {
446
+ value = JSON.parse(text);
447
+ } catch {
448
+ return void 0;
449
+ }
450
+ return nestsWithin(value, MAXIMUM_FRAME_DEPTH) ? value : TOO_DEEP;
451
+ };
452
+ var readType = (value) => isPlainObject(value) && typeof value.type === "string" ? value.type : null;
453
+ var createFrameParser = (schemas) => (text) => {
454
+ const value = parseJson(text);
455
+ if (value === TOO_DEEP) return { status: "too-deep" };
456
+ const type = readType(value);
457
+ if (type === null) return { status: "invalid" };
458
+ if (!Object.hasOwn(schemas, type)) return { status: "unknown" };
459
+ const parsed = schemas[type].safeParse(value);
460
+ return parsed.success ? { status: "frame", frame: parsed.data } : { status: "invalid" };
461
+ };
462
+ var parseHostToRoomFrame = createFrameParser(hostToRoomFrameSchemas);
463
+ var parsePhoneToRoomFrame = createFrameParser(phoneToRoomFrameSchemas);
464
+ var parseRoomToHostFrame = createFrameParser(roomToHostFrameSchemas);
465
+ var parseRoomToPhoneFrame = createFrameParser(roomToPhoneFrameSchemas);
466
+ var createHelloParser = (schema) => (text) => {
467
+ const parsed = schema.safeParse(parseJson(text));
468
+ return parsed.success ? parsed.data : null;
469
+ };
470
+ var parseHostHello = createHelloParser(hostHelloSchema);
471
+ var parsePhoneHello = createHelloParser(phoneHelloSchema);
472
+ var encodeFrame = (frame) => JSON.stringify(frame);
473
+
474
+ // src/protocol/room/input-codec.ts
475
+ var INPUT_FRAME_KIND = 1;
476
+ var BUTTON_DOWN = 128;
477
+ var PRESS_COUNTER = 127;
478
+ var RECORD_HEADER_BYTES = 3;
479
+ var controlBytes = (kind) => kind === "stick" ? 2 : 1;
480
+ var inputPayloadLength = (input) => Object.values(input).reduce(
481
+ (length, control) => length + controlBytes(control.kind),
482
+ 0
483
+ );
484
+ var toHundredths = (value) => Math.round(Math.max(-1, Math.min(1, value)) * 100);
485
+ var encodeInputPayload = (input, state) => {
486
+ const payload = new Uint8Array(inputPayloadLength(input));
487
+ const view = new DataView(payload.buffer);
488
+ let offset = 0;
489
+ for (const control of Object.values(input)) {
490
+ const value = state[control.name];
491
+ if (control.kind === "button") {
492
+ const button = value ?? {
493
+ down: false,
494
+ presses: 0
495
+ };
496
+ payload[offset] = (button.down ? BUTTON_DOWN : 0) | button.presses & PRESS_COUNTER;
497
+ } else if (control.kind === "axis") {
498
+ view.setInt8(offset, toHundredths(value ?? 0));
499
+ } else {
500
+ const vector = value ?? { x: 0, y: 0 };
501
+ view.setInt8(offset, toHundredths(vector.x));
502
+ view.setInt8(offset + 1, toHundredths(vector.y));
503
+ }
504
+ offset += controlBytes(control.kind);
505
+ }
506
+ return payload;
507
+ };
508
+ var decodeInputPayload = (input, payload, previous) => {
509
+ if (payload.byteLength !== inputPayloadLength(input)) return null;
510
+ const view = new DataView(
511
+ payload.buffer,
512
+ payload.byteOffset,
513
+ payload.byteLength
514
+ );
515
+ const unit = (offset2) => {
516
+ const hundredths = view.getInt8(offset2);
517
+ return Math.abs(hundredths) > 100 ? null : hundredths / 100;
518
+ };
519
+ const state = {};
520
+ let offset = 0;
521
+ for (const control of Object.values(input)) {
522
+ if (control.kind === "button") {
523
+ const byte = payload[offset] ?? 0;
524
+ const before = previous?.[control.name];
525
+ const counter = byte & PRESS_COUNTER;
526
+ const presses = before ? before.presses + (counter - (before.presses & PRESS_COUNTER) + PRESS_COUNTER + 1 & PRESS_COUNTER) : counter;
527
+ state[control.name] = { down: (byte & BUTTON_DOWN) !== 0, presses };
528
+ } else if (control.kind === "axis") {
529
+ const value = unit(offset);
530
+ if (value === null) return null;
531
+ state[control.name] = value;
532
+ } else {
533
+ const x = unit(offset);
534
+ const y = unit(offset + 1);
535
+ if (x === null || y === null) return null;
536
+ state[control.name] = { x, y };
537
+ }
538
+ offset += controlBytes(control.kind);
539
+ }
540
+ return state;
541
+ };
542
+ var encodePhoneInputFrame = (payload) => {
543
+ const frame = new Uint8Array(1 + payload.byteLength);
544
+ frame[0] = INPUT_FRAME_KIND;
545
+ frame.set(payload, 1);
546
+ return frame;
547
+ };
548
+ var encodeHostInputFrame = (seat, phoneFrame) => {
549
+ const payloadLength = phoneFrame.byteLength - 1;
550
+ const seatNumber = seatNumberFromId(seat);
551
+ const frame = new Uint8Array(1 + RECORD_HEADER_BYTES + payloadLength);
552
+ frame[0] = INPUT_FRAME_KIND;
553
+ frame[1] = seatNumber >> 8;
554
+ frame[2] = seatNumber & 255;
555
+ frame[3] = payloadLength;
556
+ frame.set(phoneFrame.subarray(1), 1 + RECORD_HEADER_BYTES);
557
+ return frame;
558
+ };
559
+ var joinHostInputFrames = (frames) => {
560
+ const records = frames.reduce(
561
+ (length, frame) => length + frame.byteLength - 1,
562
+ 0
563
+ );
564
+ const joined = new Uint8Array(1 + records);
565
+ joined[0] = INPUT_FRAME_KIND;
566
+ let offset = 1;
567
+ for (const frame of frames) {
568
+ joined.set(frame.subarray(1), offset);
569
+ offset += frame.byteLength - 1;
570
+ }
571
+ return joined;
572
+ };
573
+ var decodeHostInputFrame = (frame) => {
574
+ if (frame[0] !== INPUT_FRAME_KIND) throw new Error("Not an input frame.");
575
+ const records = [];
576
+ let offset = 1;
577
+ while (offset < frame.byteLength) {
578
+ if (offset + RECORD_HEADER_BYTES > frame.byteLength)
579
+ throw new Error("Truncated input record header.");
580
+ const seatNumber = (frame[offset] ?? 0) << 8 | (frame[offset + 1] ?? 0);
581
+ const length = frame[offset + 2] ?? 0;
582
+ const start = offset + RECORD_HEADER_BYTES;
583
+ if (start + length > frame.byteLength)
584
+ throw new Error("Truncated input record.");
585
+ records.push({
586
+ seat: seatIdFromNumber(seatNumber),
587
+ payload: frame.subarray(start, start + length)
588
+ });
589
+ offset = start + length;
590
+ }
591
+ return records;
592
+ };
593
+
594
+ // src/protocol/room/sdk-channels.ts
595
+ var import_zod5 = require("zod");
596
+ var runtimeStateSchema = import_zod5.z.enum(["paused", "playing"]);
597
+ var controllerOrientationSchema = import_zod5.z.enum(["portrait", "landscape"]);
598
+ var presentationDocumentSchema = import_zod5.z.object({
599
+ runtimeState: runtimeStateSchema,
600
+ orientation: controllerOrientationSchema
601
+ });
602
+ var presentationRequestSchema = import_zod5.z.enum(["pause", "resume"]);
603
+ var hapticSignalPayloadSchema = import_zod5.z.object({
604
+ pattern: import_zod5.z.enum(["light", "medium", "heavy", "success", "failure", "custom"]),
605
+ sequence: import_zod5.z.union([import_zod5.z.number().nonnegative(), import_zod5.z.array(import_zod5.z.number().nonnegative())]).optional()
606
+ });
607
+ var toastSignalPayloadSchema = import_zod5.z.object({
608
+ message: import_zod5.z.string(),
609
+ color: import_zod5.z.string().optional(),
610
+ duration: import_zod5.z.number().nonnegative().optional()
611
+ });
612
+ var soundSignalPayloadSchema = import_zod5.z.object({
613
+ soundId: import_zod5.z.string().min(1),
614
+ volume: import_zod5.z.number().min(0).max(1).optional(),
615
+ loop: import_zod5.z.boolean().optional()
616
+ });
617
+
618
+ // src/protocol/room/transport.ts
619
+ var ABNORMAL_CLOSE_CODE = 1006;
620
+
621
+ // src/protocol/room/weight.ts
622
+ var utf8ByteLength = (text) => {
623
+ let bytes = 0;
624
+ for (let index = 0; index < text.length; index += 1) {
625
+ const unit = text.charCodeAt(index);
626
+ if (unit < 128) bytes += 1;
627
+ else if (unit < 2048) bytes += 2;
628
+ else if (unit >= 55296 && unit <= 56319 && index + 1 < text.length) {
629
+ bytes += 4;
630
+ index += 1;
631
+ } else bytes += 3;
632
+ }
633
+ return bytes;
634
+ };
635
+ var jsonBytes = (value) => utf8ByteLength(JSON.stringify(value) ?? "");
636
+ var stateWeight = (value) => {
637
+ if (!isPlainObject(value)) return jsonBytes(value);
638
+ let weight = 0;
639
+ for (const [key, child] of Object.entries(value))
640
+ if (child !== void 0) weight += stateEntryWeight(key, child);
641
+ return weight;
642
+ };
643
+ var stateEntryWeight = (key, value) => jsonBytes(key) + stateWeight(value);
644
+ var applyWeighedStatePatch = (document2, weight, patch) => {
645
+ let next = weight;
646
+ const entryWeight = (key, value) => value === void 0 ? 0 : stateEntryWeight(key, value);
647
+ const patched = applyStatePatch(document2, patch, (key, before, after) => {
648
+ next += entryWeight(key, after) - entryWeight(key, before);
649
+ });
650
+ return patched && { document: patched, weight: next };
651
+ };
652
+
653
+ // src/room-session/channel-state.ts
654
+ var pathWeight = (path) => path.reduce((weight, key) => weight + utf8ByteLength(JSON.stringify(key)), 0);
655
+ var patchWeight = (patch) => patch.set.reduce(
656
+ (weight, [path, value]) => weight + pathWeight(path) + stateWeight(value),
657
+ 0
658
+ ) + patch.unset.reduce((weight, path) => weight + pathWeight(path), 0);
659
+ var sameOptions = (left, right) => left.fingerprint === right.fingerprint && left.private === right.private;
660
+ var ChannelPublisher = class {
661
+ channels = /* @__PURE__ */ new Map();
662
+ /** Channels with something to send, oldest first. */
663
+ due = /* @__PURE__ */ new Set();
664
+ /** What the room held when it last welcomed this host: the base of every later patch. */
665
+ rebase(copies) {
666
+ const held = new Map(copies.map((copy2) => [copy2.channel, copy2]));
667
+ for (const [channel, published] of this.channels) {
668
+ const copy2 = held.get(channel);
669
+ published.sent = copy2?.document ?? null;
670
+ published.sentRevision = copy2?.revision ?? published.sentRevision;
671
+ published.sentOptions = copy2 ? optionsOf(copy2) : {};
672
+ published.needsDocument = false;
673
+ this.due.add(channel);
674
+ }
675
+ for (const copy2 of copies) {
676
+ if (this.channels.has(copy2.channel)) continue;
677
+ this.channels.set(copy2.channel, {
678
+ sent: copy2.document,
679
+ sentRevision: copy2.revision,
680
+ sentOptions: optionsOf(copy2),
681
+ latest: copy2.document,
682
+ latestWeight: stateWeight(copy2.document),
683
+ options: optionsOf(copy2),
684
+ needsDocument: false
685
+ });
686
+ }
687
+ }
688
+ /** Records the channel's latest document; throws when the room could not hold it. */
689
+ publish(channel, document2, options, limits) {
690
+ const published = this.channels.get(channel);
691
+ if (!published) {
692
+ if (this.channels.size >= limits.channels)
693
+ throw new Error(
694
+ `A room holds at most ${limits.channels} channels; "${channel}" would be one more.`
695
+ );
696
+ const weight = stateWeight(document2);
697
+ assertFits(channel, weight, limits);
698
+ this.channels.set(channel, {
699
+ sent: null,
700
+ sentRevision: 0,
701
+ sentOptions: {},
702
+ latest: document2,
703
+ latestWeight: weight,
704
+ options,
705
+ needsDocument: true
706
+ });
707
+ this.due.add(channel);
708
+ return;
709
+ }
710
+ if (document2 === published.latest && sameOptions(options, published.options))
711
+ return;
712
+ const weighed = applyWeighedStatePatch(
713
+ published.latest,
714
+ published.latestWeight,
715
+ diffState(published.latest, document2)
716
+ );
717
+ if (!weighed)
718
+ throw new Error(
719
+ "A state diff did not apply to the document it came from."
720
+ );
721
+ assertFits(channel, weighed.weight, limits);
722
+ published.latest = document2;
723
+ published.latestWeight = weighed.weight;
724
+ published.options = options;
725
+ this.due.add(channel);
726
+ }
727
+ /** The room could not apply a patch and asks for the whole document. */
728
+ need(channel) {
729
+ const published = this.channels.get(channel);
730
+ if (!published) return;
731
+ published.needsDocument = true;
732
+ this.due.add(channel);
733
+ }
734
+ drop(channel) {
735
+ this.channels.delete(channel);
736
+ this.due.delete(channel);
737
+ }
738
+ /** Every channel's latest document as this host holds it, published or taken back from a welcome. */
739
+ latest() {
740
+ return [...this.channels].map(([channel, published]) => ({
741
+ channel,
742
+ revision: published.sentRevision,
743
+ document: published.latest,
744
+ ...definedOptions(published.options)
745
+ }));
746
+ }
747
+ hasDue() {
748
+ return this.due.size > 0;
749
+ }
750
+ /** The next frame worth sending, marking it sent; null when nothing is due. */
751
+ take() {
752
+ for (const channel of this.due) {
753
+ this.due.delete(channel);
754
+ const published = this.channels.get(channel);
755
+ if (!published) continue;
756
+ const frame = this.frameFor(channel, published);
757
+ if (!frame) continue;
758
+ published.sent = published.latest;
759
+ published.sentRevision = frame.revision;
760
+ published.sentOptions = published.options;
761
+ published.needsDocument = false;
762
+ return frame;
763
+ }
764
+ return null;
765
+ }
766
+ frameFor(channel, published) {
767
+ const revision = published.sentRevision + 1;
768
+ const documentFrame = {
769
+ type: "state",
770
+ channel,
771
+ revision,
772
+ document: published.latest,
773
+ ...published.options
774
+ };
775
+ if (published.sent === null || published.needsDocument || !sameOptions(published.options, published.sentOptions))
776
+ return documentFrame;
777
+ const patch = diffState(published.sent, published.latest);
778
+ if (isEmptyStatePatch(patch)) return null;
779
+ if (patchWeight(patch) >= published.latestWeight) return documentFrame;
780
+ return {
781
+ type: "state",
782
+ channel,
783
+ revision,
784
+ base: published.sentRevision,
785
+ set: patch.set.map(([path, value]) => [[...path], value]),
786
+ unset: patch.unset.map((path) => [...path])
787
+ };
788
+ }
789
+ };
790
+ var definedOptions = (options) => ({
791
+ ...options.fingerprint === void 0 ? {} : { fingerprint: options.fingerprint },
792
+ ...options.private === void 0 ? {} : { private: options.private }
793
+ });
794
+ var optionsOf = (copy2) => ({
795
+ ...copy2.fingerprint === void 0 ? {} : { fingerprint: copy2.fingerprint },
796
+ ...copy2.private === void 0 ? {} : { private: copy2.private }
797
+ });
798
+ var assertFits = (channel, weight, limits) => {
799
+ if (weight > limits.stateBytes)
800
+ throw new Error(
801
+ `Channel "${channel}" would weigh ${weight} bytes; the room holds at most ${limits.stateBytes}.`
802
+ );
803
+ };
804
+ var ChannelMirror = class {
805
+ copies = /* @__PURE__ */ new Map();
806
+ reset(copies) {
807
+ this.copies.clear();
808
+ for (const copy2 of copies)
809
+ this.copies.set(copy2.channel, { copy: copy2, diverged: false });
810
+ }
811
+ /** The channel's new document, or null when the frame did not apply. */
812
+ receive(frame) {
813
+ if ("document" in frame) {
814
+ this.copies.set(frame.channel, {
815
+ copy: {
816
+ channel: frame.channel,
817
+ revision: frame.revision,
818
+ document: frame.document,
819
+ ..."fingerprint" in frame && frame.fingerprint !== void 0 ? { fingerprint: frame.fingerprint } : {},
820
+ ..."private" in frame && frame.private !== void 0 ? { private: frame.private } : {}
821
+ },
822
+ diverged: false
823
+ });
824
+ return frame.document;
825
+ }
826
+ const held = this.copies.get(frame.channel);
827
+ if (!held || held.diverged) return null;
828
+ const next = held.copy.revision === frame.base ? applyStatePatch(held.copy.document, frame) : null;
829
+ if (!next) {
830
+ held.diverged = true;
831
+ return null;
832
+ }
833
+ held.copy = { ...held.copy, revision: frame.revision, document: next };
834
+ return next;
835
+ }
836
+ drop(channel) {
837
+ return this.copies.delete(channel);
838
+ }
839
+ document(channel) {
840
+ return this.copies.get(channel)?.copy.document;
841
+ }
842
+ copy(channel) {
843
+ return this.copies.get(channel)?.copy;
844
+ }
845
+ documents() {
846
+ return new Map(
847
+ [...this.copies].map(([channel, held]) => [channel, held.copy.document])
848
+ );
849
+ }
850
+ };
851
+
852
+ // src/room-session/clock.ts
853
+ var systemRoomClock = {
854
+ now: () => Date.now(),
855
+ at: (time, callback) => {
856
+ const timer = setTimeout(callback, Math.max(0, time - Date.now()));
857
+ return () => clearTimeout(timer);
858
+ }
859
+ };
860
+ var spacingForRate = (perSecond) => perSecond <= 1 ? 1e3 : Math.ceil(1e3 / (perSecond - 1));
861
+
862
+ // src/room-session/input-lane.ts
863
+ var STICK_CHANGE_HUNDREDTHS = 2;
864
+ var RIM_HUNDREDTHS = 99.5;
865
+ var isMovement = (before, after) => {
866
+ if (before.every((value, index) => value === after[index])) return false;
867
+ const largest = Math.max(
868
+ ...after.map((value, index) => Math.abs(value - (before[index] ?? 0)))
869
+ );
870
+ return largest >= STICK_CHANGE_HUNDREDTHS || after.every((value) => value === 0) || Math.hypot(...after) >= RIM_HUNDREDTHS;
871
+ };
872
+ var signed = (byte) => byte === void 0 ? 0 : byte > 127 ? byte - 256 : byte;
873
+ var PhoneInputLane = class {
874
+ constructor(layout) {
875
+ this.layout = layout;
876
+ }
877
+ latest = null;
878
+ sent = null;
879
+ sentAt = Number.NEGATIVE_INFINITY;
880
+ update(state) {
881
+ this.latest = encodeInputPayload(this.layout, state);
882
+ }
883
+ /**
884
+ * When the latest state should go out, or null when nothing worth sending
885
+ * changed. `spacingMs` keeps every frame within the room's input rate.
886
+ */
887
+ due(intervalMs, spacingMs) {
888
+ const change = this.change();
889
+ if (change === "none") return null;
890
+ return this.sentAt + (change === "edge" ? spacingMs : Math.max(intervalMs, spacingMs));
891
+ }
892
+ /** The frame to send now, whether or not it changed; null before any state. */
893
+ take(now) {
894
+ if (this.latest === null) return null;
895
+ this.sent = this.latest;
896
+ this.sentAt = now;
897
+ return encodePhoneInputFrame(this.latest);
898
+ }
899
+ change() {
900
+ const latest = this.latest;
901
+ if (latest === null) return "none";
902
+ const sent = this.sent;
903
+ if (sent === null) return "edge";
904
+ let offset = 0;
905
+ let change = "none";
906
+ for (const control of Object.values(this.layout)) {
907
+ if (control.kind === "button") {
908
+ if (latest[offset] !== sent[offset]) return "edge";
909
+ offset += 1;
910
+ continue;
911
+ }
912
+ const width = control.kind === "stick" ? 2 : 1;
913
+ const before = [];
914
+ const after = [];
915
+ for (let index = 0; index < width; index += 1) {
916
+ before.push(signed(sent[offset + index]));
917
+ after.push(signed(latest[offset + index]));
918
+ }
919
+ if (isMovement(before, after)) change = "movement";
920
+ offset += width;
921
+ }
922
+ return change;
923
+ }
924
+ };
925
+ var HostInputDecoder = class {
926
+ constructor(layout) {
927
+ this.layout = layout;
928
+ }
929
+ bySeat = /* @__PURE__ */ new Map();
930
+ /** The seats' states in a host input frame; malformed records are skipped. */
931
+ decode(frame) {
932
+ const decoded = [];
933
+ for (const record of decodeHostInputFrame(frame)) {
934
+ const state = decodeInputPayload(
935
+ this.layout,
936
+ record.payload,
937
+ this.bySeat.get(record.seat) ?? null
938
+ );
939
+ if (state === null) continue;
940
+ this.bySeat.set(record.seat, state);
941
+ decoded.push({ seat: record.seat, state });
942
+ }
943
+ return decoded;
944
+ }
945
+ forget(seat) {
946
+ this.bySeat.delete(seat);
947
+ }
948
+ };
949
+
950
+ // src/room-session/listeners.ts
951
+ var Listeners = class {
952
+ listeners = /* @__PURE__ */ new Map();
953
+ on(name, listener) {
954
+ const set = this.listeners.get(name) ?? /* @__PURE__ */ new Set();
955
+ set.add(listener);
956
+ this.listeners.set(name, set);
957
+ return () => set.delete(listener);
958
+ }
959
+ emit(name, event) {
960
+ for (const listener of [...this.listeners.get(name) ?? []])
961
+ listener(event);
962
+ }
963
+ };
964
+
965
+ // src/room-session/roster.ts
966
+ var Roster = class {
967
+ seats = /* @__PURE__ */ new Map();
968
+ reset(seats) {
969
+ this.seats.clear();
970
+ for (const seat of seats) this.seats.set(seat.id, seat);
971
+ }
972
+ upsert(seat) {
973
+ this.seats.set(seat.id, seat);
974
+ }
975
+ remove(seat) {
976
+ this.seats.delete(seat);
977
+ }
978
+ list() {
979
+ return [...this.seats.values()];
980
+ }
981
+ };
982
+
983
+ // src/runtime/sdk-version.ts
984
+ var AIR_JAM_SDK_VERSION = true ? "1.0.0-beta.1" : "0.0.0";
985
+
986
+ // src/room-session/session-link.ts
987
+ var DEFAULT_HEARTBEAT = {
988
+ intervalMs: 2e4,
989
+ answerWithinMs: 1e4
990
+ };
991
+ var DEFAULT_HELLO_ANSWER_WITHIN_MS = 5e3;
992
+ var DEFAULT_RETRY = {
993
+ firstDelayMs: 250,
994
+ maximumDelayMs: 5e3
995
+ };
996
+ var SESSION_SDK = `air-jam-sdk/${AIR_JAM_SDK_VERSION}`;
997
+ var SessionLink = class {
998
+ constructor(options, role) {
999
+ this.options = options;
1000
+ this.role = role;
1001
+ this.clock = options.clock ?? systemRoomClock;
1002
+ this.random = options.random ?? Math.random;
1003
+ this.heartbeat = options.heartbeat === void 0 ? DEFAULT_HEARTBEAT : options.heartbeat;
1004
+ this.retry = options.retry ?? DEFAULT_RETRY;
1005
+ }
1006
+ link = null;
1007
+ welcomed = false;
1008
+ attempt = 0;
1009
+ cancelRetry = null;
1010
+ cancelPing = null;
1011
+ cancelAnswer = null;
1012
+ cancelHello = null;
1013
+ stopWakeEvents = null;
1014
+ current = { phase: "connecting" };
1015
+ clock;
1016
+ random;
1017
+ heartbeat;
1018
+ retry;
1019
+ get status() {
1020
+ return this.current;
1021
+ }
1022
+ get open() {
1023
+ return this.welcomed;
1024
+ }
1025
+ /** True while the link still holds data sent earlier, so fresher data should wait instead of queueing behind it. */
1026
+ get buffered() {
1027
+ return this.link?.buffered() ?? false;
1028
+ }
1029
+ start() {
1030
+ this.stopWakeEvents = this.options.deviceWakeEvents?.(() => this.deviceWoke()) ?? null;
1031
+ this.connect();
1032
+ }
1033
+ /** Sends on a welcomed link; false when there is none. */
1034
+ send(data) {
1035
+ if (!this.welcomed || !this.link) return false;
1036
+ this.link.send(data);
1037
+ return true;
1038
+ }
1039
+ /** The room welcomed this link. */
1040
+ markOpen() {
1041
+ this.answered();
1042
+ this.welcomed = true;
1043
+ this.attempt = 0;
1044
+ this.setStatus({ phase: "open" });
1045
+ }
1046
+ waiting(position) {
1047
+ this.answered();
1048
+ this.setStatus({ phase: "waiting", position });
1049
+ }
1050
+ /** Ends the session from this side, for good. */
1051
+ close() {
1052
+ this.end("owner");
1053
+ }
1054
+ /** The room sent a frame this client cannot read: they do not speak the same protocol. */
1055
+ fail() {
1056
+ this.end("unsupported-version");
1057
+ }
1058
+ end(reason) {
1059
+ if (this.current.phase === "closed") return;
1060
+ this.link?.close();
1061
+ this.drop();
1062
+ this.finish(reason);
1063
+ }
1064
+ connect() {
1065
+ if (this.attempt === 0) this.setStatus({ phase: "connecting" });
1066
+ const link = this.options.connector(this.role.address(), {
1067
+ open: () => {
1068
+ if (this.link !== link) return;
1069
+ const hello = this.role.hello();
1070
+ if (typeof hello === "string") return this.greet(link, hello);
1071
+ hello.then(
1072
+ (frame) => {
1073
+ if (this.link === link) this.greet(link, frame);
1074
+ },
1075
+ () => {
1076
+ if (this.link === link) this.end("unauthorised");
1077
+ }
1078
+ );
1079
+ },
1080
+ message: (data) => {
1081
+ if (this.link !== link) return;
1082
+ this.heard();
1083
+ if (data !== PONG_FRAME) this.role.receive(data);
1084
+ },
1085
+ close: (code) => {
1086
+ if (this.link !== link) return;
1087
+ this.lost(code);
1088
+ }
1089
+ });
1090
+ this.link = link;
1091
+ }
1092
+ greet(link, hello) {
1093
+ link.send(hello);
1094
+ this.schedulePing();
1095
+ const within = this.options.helloAnswerWithinMs ?? DEFAULT_HELLO_ANSWER_WITHIN_MS;
1096
+ this.cancelHello = this.clock.at(this.clock.now() + within, () => {
1097
+ this.cancelHello = null;
1098
+ if (this.link !== link) return;
1099
+ link.close();
1100
+ this.lost(ABNORMAL_CLOSE_CODE);
1101
+ });
1102
+ }
1103
+ /** The room welcomed or queued the link, so its hello arrived. */
1104
+ answered() {
1105
+ this.cancelHello?.();
1106
+ this.cancelHello = null;
1107
+ }
1108
+ lost(code) {
1109
+ this.drop();
1110
+ const reason = roomCloseReasonForCode(code);
1111
+ if (reason !== null && roomCloseCodes[reason].terminal)
1112
+ return this.finish(reason);
1113
+ this.attempt += 1;
1114
+ this.setStatus({ phase: "reconnecting", attempt: this.attempt });
1115
+ const ceiling = Math.min(
1116
+ this.retry.maximumDelayMs,
1117
+ this.retry.firstDelayMs * 2 ** (this.attempt - 1)
1118
+ );
1119
+ const delay = ceiling / 2 + this.random() * ceiling / 2;
1120
+ this.cancelRetry = this.clock.at(this.clock.now() + delay, () => {
1121
+ this.cancelRetry = null;
1122
+ this.connect();
1123
+ });
1124
+ }
1125
+ /** Forgets the link and everything that ran on it. */
1126
+ drop() {
1127
+ const hadLink = this.link !== null;
1128
+ this.link = null;
1129
+ this.welcomed = false;
1130
+ this.cancelPing?.();
1131
+ this.cancelPing = null;
1132
+ this.cancelAnswer?.();
1133
+ this.cancelAnswer = null;
1134
+ this.answered();
1135
+ if (hadLink) this.role.lost();
1136
+ }
1137
+ finish(reason) {
1138
+ this.cancelRetry?.();
1139
+ this.cancelRetry = null;
1140
+ this.stopWakeEvents?.();
1141
+ this.stopWakeEvents = null;
1142
+ this.setStatus({ phase: "closed", reason });
1143
+ }
1144
+ deviceWoke() {
1145
+ if (this.current.phase === "reconnecting" && this.cancelRetry) {
1146
+ this.cancelRetry();
1147
+ this.cancelRetry = null;
1148
+ this.connect();
1149
+ } else if (this.welcomed) this.ping();
1150
+ }
1151
+ schedulePing() {
1152
+ if (!this.heartbeat) return;
1153
+ const { intervalMs } = this.heartbeat;
1154
+ this.cancelPing = this.clock.at(this.clock.now() + intervalMs, () => {
1155
+ this.cancelPing = null;
1156
+ this.ping();
1157
+ this.schedulePing();
1158
+ });
1159
+ }
1160
+ /** Asks the room to answer; a link that stays silent is dead. */
1161
+ ping() {
1162
+ const link = this.link;
1163
+ if (!link || this.cancelAnswer) return;
1164
+ link.send(PING_FRAME);
1165
+ const answerWithinMs = this.heartbeat?.answerWithinMs ?? DEFAULT_HEARTBEAT.answerWithinMs;
1166
+ this.cancelAnswer = this.clock.at(this.clock.now() + answerWithinMs, () => {
1167
+ this.cancelAnswer = null;
1168
+ if (this.link !== link) return;
1169
+ link.close();
1170
+ this.lost(ABNORMAL_CLOSE_CODE);
1171
+ });
1172
+ }
1173
+ heard() {
1174
+ this.cancelAnswer?.();
1175
+ this.cancelAnswer = null;
1176
+ }
1177
+ setStatus(status) {
1178
+ this.current = status;
1179
+ this.role.status(status);
1180
+ }
1181
+ };
1182
+
1183
+ // src/room-session/host-room-session.ts
1184
+ var HostRoomSession = class {
1185
+ constructor(options) {
1186
+ this.options = options;
1187
+ this.currentCode = options.code;
1188
+ this.currentInstance = options.instance;
1189
+ this.seatsWanted = options.seats;
1190
+ this.decoder = options.input ? new HostInputDecoder(options.input) : null;
1191
+ this.link = new SessionLink(options, {
1192
+ address: () => ({ role: "host", code: this.currentCode ?? null }),
1193
+ hello: () => this.hello(),
1194
+ receive: (data) => this.receive(data),
1195
+ lost: () => this.lost(),
1196
+ status: (status) => this.events.emit("status", status)
1197
+ });
1198
+ this.link.start();
1199
+ }
1200
+ events = new Listeners();
1201
+ link;
1202
+ roster = new Roster();
1203
+ publisher = new ChannelPublisher();
1204
+ decoder;
1205
+ droppedChannels = /* @__PURE__ */ new Set();
1206
+ cancelState = null;
1207
+ stateSentAt = Number.NEGATIVE_INFINITY;
1208
+ currentCode;
1209
+ currentInstance;
1210
+ currentLimits = DEFAULT_ROOM_LIMITS;
1211
+ seatsWanted;
1212
+ locked = null;
1213
+ activity = null;
1214
+ copies = [];
1215
+ welcomed = null;
1216
+ on = this.events.on.bind(this.events);
1217
+ get status() {
1218
+ return this.link.status;
1219
+ }
1220
+ get code() {
1221
+ return this.currentCode;
1222
+ }
1223
+ /** The room instance; store it with the key to reclaim the room after a reload. */
1224
+ get instance() {
1225
+ return this.currentInstance;
1226
+ }
1227
+ get seats() {
1228
+ return this.roster.list();
1229
+ }
1230
+ get limits() {
1231
+ return this.currentLimits;
1232
+ }
1233
+ /**
1234
+ * Every channel the room held when it last welcomed this host, with its
1235
+ * fingerprint, so a reloading game can take its state back.
1236
+ */
1237
+ get roomCopies() {
1238
+ return this.copies;
1239
+ }
1240
+ /**
1241
+ * What the room looks like as this host wants it: its last welcome with
1242
+ * every change asked for since. Null before the first welcome.
1243
+ */
1244
+ get room() {
1245
+ const welcomed = this.welcomed;
1246
+ if (!welcomed) return null;
1247
+ return {
1248
+ seatsWanted: this.seatsWanted,
1249
+ locked: this.locked ?? welcomed.locked,
1250
+ activity: this.activity ? this.activity.value : welcomed.activity,
1251
+ features: welcomed.features
1252
+ };
1253
+ }
1254
+ /** Every channel's latest document as this host holds it, published or taken back from a welcome. */
1255
+ channels() {
1256
+ return this.publisher.latest();
1257
+ }
1258
+ /**
1259
+ * The channel's latest document. Frames go out paced to the room's state
1260
+ * rate, so documents published in one turn travel as one frame. Throws
1261
+ * when the room could not hold the document.
1262
+ */
1263
+ publish(channel, document2, options = {}) {
1264
+ this.publisher.publish(channel, document2, options, this.currentLimits);
1265
+ this.droppedChannels.delete(channel);
1266
+ this.pumpState();
1267
+ }
1268
+ drop(channel) {
1269
+ this.publisher.drop(channel);
1270
+ if (!this.send({ type: "drop", channel }))
1271
+ this.droppedChannels.add(channel);
1272
+ }
1273
+ respond(seat, id, result) {
1274
+ this.send({ type: "response", seat, id, result });
1275
+ }
1276
+ /** A one-shot message to one seat or every phone; lost while the link is down. */
1277
+ signal(kind, payload, seat) {
1278
+ this.send({ type: "signal", kind, payload, ...seat ? { seat } : {} });
1279
+ }
1280
+ configure(room) {
1281
+ if (room.seats !== void 0) this.seatsWanted = room.seats;
1282
+ if (room.locked !== void 0) this.locked = room.locked;
1283
+ this.send({ type: "room", ...room });
1284
+ }
1285
+ /** Frees a seat and closes its phone for good. */
1286
+ remove(seat) {
1287
+ this.send({ type: "remove", seat });
1288
+ }
1289
+ /** What is on screen; only rooms whose gate allows it accept a change. */
1290
+ setActivity(activity) {
1291
+ this.activity = { value: activity };
1292
+ this.send({ type: "activity", activity });
1293
+ }
1294
+ /** Closes the room for every device. */
1295
+ end() {
1296
+ if (!this.send({ type: "end" })) this.close();
1297
+ }
1298
+ /** Leaves the room to its host grace, as a closing page does. */
1299
+ close() {
1300
+ this.link.close();
1301
+ }
1302
+ send(frame) {
1303
+ return this.link.send(encodeFrame(frame));
1304
+ }
1305
+ hello() {
1306
+ const hello = {
1307
+ type: "hello",
1308
+ key: this.options.key,
1309
+ sdk: SESSION_SDK,
1310
+ seats: this.seatsWanted,
1311
+ ...this.currentInstance === void 0 ? {} : { instance: this.currentInstance }
1312
+ };
1313
+ const credential = this.options.credential;
1314
+ if (this.currentInstance !== void 0 || credential === void 0)
1315
+ return encodeFrame(hello);
1316
+ return credential().then(
1317
+ (value) => encodeFrame({ ...hello, credential: value })
1318
+ );
1319
+ }
1320
+ receive(data) {
1321
+ if (typeof data !== "string") {
1322
+ this.events.emit("inputFrame", data);
1323
+ for (const record of this.decoder?.decode(data) ?? [])
1324
+ this.events.emit("input", record);
1325
+ return;
1326
+ }
1327
+ const parsed = parseRoomToHostFrame(data);
1328
+ if (parsed.status === "unknown") return;
1329
+ if (parsed.status !== "frame") return this.link.fail();
1330
+ this.handle(parsed.frame);
1331
+ }
1332
+ handle(frame) {
1333
+ switch (frame.type) {
1334
+ case "welcome":
1335
+ return this.welcome(frame);
1336
+ case "wait":
1337
+ return this.link.waiting(frame.position);
1338
+ case "seat":
1339
+ this.roster.upsert(frame.seat);
1340
+ if (frame.inputBaseline) {
1341
+ this.decoder?.forget(frame.seat.id);
1342
+ this.events.emit("inputBaseline", frame.seat.id);
1343
+ }
1344
+ return this.events.emit("seats", this.roster.list());
1345
+ case "left":
1346
+ this.roster.remove(frame.seat);
1347
+ this.decoder?.forget(frame.seat);
1348
+ return this.events.emit("seats", this.roster.list());
1349
+ case "need":
1350
+ this.publisher.need(frame.channel);
1351
+ return this.pumpState();
1352
+ case "request":
1353
+ return this.events.emit("request", {
1354
+ seat: frame.seat,
1355
+ id: frame.id,
1356
+ channel: frame.channel,
1357
+ name: frame.name,
1358
+ payload: frame.payload
1359
+ });
1360
+ }
1361
+ }
1362
+ welcome(frame) {
1363
+ this.currentCode = frame.code;
1364
+ this.currentInstance = frame.instance;
1365
+ this.currentLimits = frame.limits;
1366
+ this.copies = frame.channels;
1367
+ this.welcomed = {
1368
+ seatsWanted: frame.seatsWanted,
1369
+ locked: frame.locked,
1370
+ activity: frame.activity,
1371
+ features: frame.features
1372
+ };
1373
+ const known = /* @__PURE__ */ new Set([
1374
+ ...this.roster.list().map((seat) => seat.id),
1375
+ ...frame.seats.map((seat) => seat.id)
1376
+ ]);
1377
+ this.roster.reset(frame.seats);
1378
+ for (const seat of known) {
1379
+ this.decoder?.forget(seat);
1380
+ this.events.emit("inputBaseline", seat);
1381
+ }
1382
+ this.publisher.rebase(
1383
+ frame.channels.filter((copy2) => !this.droppedChannels.has(copy2.channel))
1384
+ );
1385
+ this.link.markOpen();
1386
+ if (this.locked !== null && this.locked !== frame.locked)
1387
+ this.send({ type: "room", locked: this.locked });
1388
+ if (this.activity !== null && this.activity.value !== frame.activity)
1389
+ this.send({ type: "activity", activity: this.activity.value });
1390
+ for (const copy2 of frame.channels)
1391
+ if (this.droppedChannels.has(copy2.channel))
1392
+ this.send({ type: "drop", channel: copy2.channel });
1393
+ this.droppedChannels.clear();
1394
+ this.events.emit("seats", this.roster.list());
1395
+ this.pumpState();
1396
+ }
1397
+ lost() {
1398
+ this.cancelState?.();
1399
+ this.cancelState = null;
1400
+ }
1401
+ pumpState() {
1402
+ if (!this.link.open || this.cancelState || !this.publisher.hasDue()) return;
1403
+ const clock = this.link.clock;
1404
+ const at = Math.max(
1405
+ clock.now(),
1406
+ this.stateSentAt + spacingForRate(this.currentLimits.statesPerSecond)
1407
+ );
1408
+ this.cancelState = clock.at(at, () => {
1409
+ this.cancelState = null;
1410
+ const frame = this.publisher.take();
1411
+ if (frame && this.send(frame)) this.stateSentAt = clock.now();
1412
+ this.pumpState();
1413
+ });
1414
+ }
1415
+ };
1416
+
1417
+ // src/room-session/loopback-link.ts
1418
+ var copy = (data) => typeof data === "string" ? data : data.slice();
1419
+ var createLoopbackConnector = (acceptor) => (address, handlers) => {
1420
+ let server = null;
1421
+ let clientClosed = false;
1422
+ let serverClosed = false;
1423
+ const end = () => server?.closed();
1424
+ queueMicrotask(() => {
1425
+ if (clientClosed) return;
1426
+ server = acceptor.accept(address, null, {
1427
+ send: (data) => {
1428
+ if (serverClosed) return;
1429
+ const delivered = copy(data);
1430
+ queueMicrotask(() => {
1431
+ if (!clientClosed) handlers.message(delivered);
1432
+ });
1433
+ },
1434
+ close: (code) => {
1435
+ if (serverClosed || clientClosed) return;
1436
+ serverClosed = true;
1437
+ queueMicrotask(() => {
1438
+ if (!clientClosed) handlers.close(code);
1439
+ end();
1440
+ });
1441
+ }
1442
+ });
1443
+ handlers.open();
1444
+ });
1445
+ return {
1446
+ send: (data) => {
1447
+ const delivered = copy(data);
1448
+ queueMicrotask(() => {
1449
+ if (!serverClosed && !clientClosed) server?.receive(delivered);
1450
+ });
1451
+ },
1452
+ buffered: () => false,
1453
+ close: () => {
1454
+ if (clientClosed) return;
1455
+ clientClosed = true;
1456
+ if (!serverClosed) queueMicrotask(end);
1457
+ }
1458
+ };
1459
+ };
1460
+
1461
+ // src/room-session/room-key.ts
1462
+ var createRoomKey = () => Array.from(
1463
+ crypto.getRandomValues(new Uint8Array(16)),
1464
+ (byte) => byte.toString(16).padStart(2, "0")
1465
+ ).join("");
1466
+
1467
+ // src/room-session/phone-room-session.ts
1468
+ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
1469
+ var PhoneRoomSession = class {
1470
+ constructor(options) {
1471
+ this.options = options;
1472
+ this.profile = options.profile;
1473
+ this.currentInstance = options.instance;
1474
+ this.lane = options.input ? new PhoneInputLane(options.input) : null;
1475
+ this.link = new SessionLink(options, {
1476
+ address: () => ({ role: "phone", code: options.code }),
1477
+ hello: () => this.hello(),
1478
+ receive: (data) => this.receive(data),
1479
+ lost: () => this.lost(),
1480
+ status: (status) => {
1481
+ if (status.phase === "closed")
1482
+ for (const id of [...this.requests.keys()])
1483
+ this.settle(id, { status: "unconfirmed" });
1484
+ this.events.emit("status", status);
1485
+ }
1486
+ });
1487
+ this.link.start();
1488
+ }
1489
+ events = new Listeners();
1490
+ link;
1491
+ roster = new Roster();
1492
+ mirror = new ChannelMirror();
1493
+ lane;
1494
+ requests = /* @__PURE__ */ new Map();
1495
+ exclusive = /* @__PURE__ */ new Set();
1496
+ nextRequestId = 1;
1497
+ cancelInput = null;
1498
+ relayedInput = null;
1499
+ cancelRelayedInput = null;
1500
+ currentFeatures = [];
1501
+ profile;
1502
+ currentInstance;
1503
+ currentSeat = null;
1504
+ hostPresent = false;
1505
+ currentLimits = DEFAULT_ROOM_LIMITS;
1506
+ on = this.events.on.bind(this.events);
1507
+ get status() {
1508
+ return this.link.status;
1509
+ }
1510
+ get code() {
1511
+ return this.options.code;
1512
+ }
1513
+ /** The room instance this seat belongs to; store it with the key to resume after a reload. */
1514
+ get instance() {
1515
+ return this.currentInstance;
1516
+ }
1517
+ get seat() {
1518
+ return this.currentSeat;
1519
+ }
1520
+ get seats() {
1521
+ return this.roster.list();
1522
+ }
1523
+ get host() {
1524
+ return this.hostPresent;
1525
+ }
1526
+ get limits() {
1527
+ return this.currentLimits;
1528
+ }
1529
+ get features() {
1530
+ return this.currentFeatures;
1531
+ }
1532
+ channel(channel) {
1533
+ return this.mirror.document(channel);
1534
+ }
1535
+ /** Every channel this seat mirrors. */
1536
+ documents() {
1537
+ return this.mirror.documents();
1538
+ }
1539
+ /** The controls' whole state; the session decides when it travels. */
1540
+ sendInput(state) {
1541
+ if (!this.lane)
1542
+ throw new Error("This phone session was created without input controls.");
1543
+ this.lane.update(state);
1544
+ this.pumpInput();
1545
+ }
1546
+ /**
1547
+ * A whole phone input frame from a frame this page serves, whose own
1548
+ * session paced it. Behind a stalled link only the latest waits.
1549
+ */
1550
+ sendInputFrame(frame) {
1551
+ this.relayedInput = frame;
1552
+ this.pumpRelayedInput();
1553
+ }
1554
+ request(channel, name, payload, options = {}) {
1555
+ if (this.link.status.phase === "closed")
1556
+ return Promise.resolve({ status: "unconfirmed" });
1557
+ const exclusiveKey = options.exclusive ? `${channel}\0${name}` : null;
1558
+ if (exclusiveKey !== null && this.exclusive.has(exclusiveKey))
1559
+ return Promise.resolve({ status: "busy" });
1560
+ const id = this.nextRequestId;
1561
+ this.nextRequestId += 1;
1562
+ return new Promise((resolve) => {
1563
+ const clock = this.link.clock;
1564
+ const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1565
+ const pending = {
1566
+ frame: encodeFrame({ type: "request", id, channel, name, payload }),
1567
+ exclusiveKey,
1568
+ resolve,
1569
+ cancelTimeout: clock.at(
1570
+ clock.now() + timeoutMs,
1571
+ () => this.settle(id, { status: "unconfirmed" })
1572
+ ),
1573
+ sent: false
1574
+ };
1575
+ this.requests.set(id, pending);
1576
+ if (exclusiveKey !== null) this.exclusive.add(exclusiveKey);
1577
+ pending.sent = this.link.send(pending.frame);
1578
+ });
1579
+ }
1580
+ setProfile(profile) {
1581
+ this.profile = { ...this.profile, ...profile };
1582
+ this.link.send(encodeFrame({ type: "profile", ...profile }));
1583
+ }
1584
+ /**
1585
+ * Tells the host this seat's controls start again from zero, as when a
1586
+ * page serves a newly loaded controller frame its seat.
1587
+ */
1588
+ restartInput() {
1589
+ this.link.send(encodeFrame({ type: "baseline" }));
1590
+ }
1591
+ /** Gives the seat up for good. */
1592
+ leave() {
1593
+ if (!this.link.send(encodeFrame({ type: "leave" }))) this.close();
1594
+ }
1595
+ close() {
1596
+ this.link.close();
1597
+ }
1598
+ /** This page's id, the same in every hello it sends; see `PhoneHello.page`. */
1599
+ page = createRoomKey();
1600
+ hello() {
1601
+ const hello = {
1602
+ type: "hello",
1603
+ key: this.options.key,
1604
+ sdk: SESSION_SDK,
1605
+ kind: this.options.kind ?? "phone",
1606
+ page: this.page,
1607
+ ...this.currentInstance === void 0 ? {} : { instance: this.currentInstance },
1608
+ ...this.profile === void 0 ? {} : { profile: this.profile }
1609
+ };
1610
+ return encodeFrame(hello);
1611
+ }
1612
+ receive(data) {
1613
+ if (typeof data !== "string") return;
1614
+ const parsed = parseRoomToPhoneFrame(data);
1615
+ if (parsed.status === "unknown") return;
1616
+ if (parsed.status !== "frame") return this.link.fail();
1617
+ this.handle(parsed.frame);
1618
+ }
1619
+ handle(frame) {
1620
+ switch (frame.type) {
1621
+ case "welcome":
1622
+ this.currentInstance = frame.instance;
1623
+ this.currentSeat = frame.seat;
1624
+ this.currentLimits = frame.limits;
1625
+ this.currentFeatures = frame.features;
1626
+ this.hostPresent = frame.host;
1627
+ this.roster.reset(frame.seats);
1628
+ this.mirror.reset(frame.channels);
1629
+ this.link.markOpen();
1630
+ this.events.emit("seats", this.roster.list());
1631
+ this.events.emit("host", this.hostPresent);
1632
+ for (const [channel, document2] of this.mirror.documents())
1633
+ this.events.emit("state", { channel, document: document2 });
1634
+ for (const pending of this.requests.values())
1635
+ if (!pending.sent) pending.sent = this.link.send(pending.frame);
1636
+ return this.resendInput();
1637
+ case "seat":
1638
+ this.roster.upsert(frame.seat);
1639
+ return this.events.emit("seats", this.roster.list());
1640
+ case "left":
1641
+ this.roster.remove(frame.seat);
1642
+ return this.events.emit("seats", this.roster.list());
1643
+ case "host":
1644
+ this.hostPresent = frame.present;
1645
+ this.events.emit("host", frame.present);
1646
+ if (frame.present) this.resendInput();
1647
+ return;
1648
+ case "state": {
1649
+ const document2 = this.mirror.receive(frame);
1650
+ if (document2)
1651
+ this.events.emit("state", { channel: frame.channel, document: document2 });
1652
+ return;
1653
+ }
1654
+ case "drop":
1655
+ if (this.mirror.drop(frame.channel))
1656
+ this.events.emit("drop", { channel: frame.channel });
1657
+ return;
1658
+ case "response":
1659
+ return this.settle(
1660
+ frame.id,
1661
+ "refused" in frame ? { status: "refused", reason: frame.refused } : { status: "answered", result: frame.result }
1662
+ );
1663
+ case "signal":
1664
+ return this.events.emit("signal", {
1665
+ kind: frame.kind,
1666
+ payload: frame.payload
1667
+ });
1668
+ }
1669
+ }
1670
+ lost() {
1671
+ this.cancelInput?.();
1672
+ this.cancelInput = null;
1673
+ this.cancelRelayedInput?.();
1674
+ this.cancelRelayedInput = null;
1675
+ this.relayedInput = null;
1676
+ for (const [id, pending] of this.requests)
1677
+ if (pending.sent) this.settle(id, { status: "unconfirmed" });
1678
+ }
1679
+ settle(id, outcome) {
1680
+ const pending = this.requests.get(id);
1681
+ if (!pending) return;
1682
+ this.requests.delete(id);
1683
+ pending.cancelTimeout();
1684
+ if (pending.exclusiveKey !== null)
1685
+ this.exclusive.delete(pending.exclusiveKey);
1686
+ pending.resolve(outcome);
1687
+ }
1688
+ /** A phone re-sends its controls once after joining and when the host returns. */
1689
+ resendInput() {
1690
+ const frame = this.lane?.take(this.link.clock.now());
1691
+ if (frame) this.link.send(frame);
1692
+ this.pumpInput();
1693
+ }
1694
+ pumpRelayedInput() {
1695
+ if (!this.relayedInput || !this.link.open || this.cancelRelayedInput)
1696
+ return;
1697
+ const clock = this.link.clock;
1698
+ if (this.link.buffered) {
1699
+ this.cancelRelayedInput = clock.at(
1700
+ clock.now() + this.currentLimits.inputIntervalMs,
1701
+ () => {
1702
+ this.cancelRelayedInput = null;
1703
+ this.pumpRelayedInput();
1704
+ }
1705
+ );
1706
+ return;
1707
+ }
1708
+ this.link.send(this.relayedInput);
1709
+ this.relayedInput = null;
1710
+ }
1711
+ pumpInput() {
1712
+ const lane = this.lane;
1713
+ if (!lane || !this.link.open) return;
1714
+ this.cancelInput?.();
1715
+ this.cancelInput = null;
1716
+ const due = lane.due(
1717
+ this.currentLimits.inputIntervalMs,
1718
+ spacingForRate(this.currentLimits.inputsPerSecond)
1719
+ );
1720
+ if (due === null) return;
1721
+ const clock = this.link.clock;
1722
+ const ready = this.link.buffered ? clock.now() + this.currentLimits.inputIntervalMs : due;
1723
+ if (ready <= clock.now()) {
1724
+ const frame = lane.take(clock.now());
1725
+ if (frame) this.link.send(frame);
1726
+ return;
1727
+ }
1728
+ this.cancelInput = clock.at(ready, () => {
1729
+ this.cancelInput = null;
1730
+ this.pumpInput();
1731
+ });
1732
+ }
1733
+ };
1734
+
1735
+ // src/room-session/port-link.ts
1736
+ var import_zod6 = require("zod");
1737
+ var wireDataSchema = import_zod6.z.union([
1738
+ import_zod6.z.string(),
1739
+ import_zod6.z.custom((value) => value instanceof Uint8Array)
1740
+ ]);
1741
+ var linkIdSchema = import_zod6.z.number().int().positive();
1742
+ var addressSchema = import_zod6.z.discriminatedUnion("role", [
1743
+ import_zod6.z.object({ role: import_zod6.z.literal("host"), code: roomCodeSchema.nullable() }),
1744
+ import_zod6.z.object({ role: import_zod6.z.literal("phone"), code: roomCodeSchema })
1745
+ ]);
1746
+ var toParentSchema = import_zod6.z.union([
1747
+ import_zod6.z.object({ link: linkIdSchema, open: addressSchema }),
1748
+ import_zod6.z.object({ link: linkIdSchema, data: wireDataSchema }),
1749
+ import_zod6.z.object({ link: linkIdSchema, close: import_zod6.z.literal(true) })
1750
+ ]);
1751
+ var toFrameSchema = import_zod6.z.union([
1752
+ import_zod6.z.object({ link: linkIdSchema, opened: import_zod6.z.literal(true) }),
1753
+ import_zod6.z.object({ link: linkIdSchema, data: wireDataSchema }),
1754
+ import_zod6.z.object({ link: linkIdSchema, closed: import_zod6.z.number().int() })
1755
+ ]);
1756
+ var createPortConnector = (port) => {
1757
+ let nextLink = 1;
1758
+ const links = /* @__PURE__ */ new Map();
1759
+ port.addEventListener("message", (event) => {
1760
+ const parsed = toFrameSchema.safeParse(event.data);
1761
+ if (!parsed.success) return;
1762
+ const message = parsed.data;
1763
+ const handlers = links.get(message.link);
1764
+ if (!handlers) return;
1765
+ if ("opened" in message) handlers.open();
1766
+ else if ("data" in message) handlers.message(message.data);
1767
+ else {
1768
+ links.delete(message.link);
1769
+ handlers.close(message.closed);
1770
+ }
1771
+ });
1772
+ port.start();
1773
+ const post = (message) => port.postMessage(message);
1774
+ return (address, handlers) => {
1775
+ const link = nextLink;
1776
+ nextLink += 1;
1777
+ links.set(link, handlers);
1778
+ post({ link, open: address });
1779
+ return {
1780
+ send: (data) => {
1781
+ if (links.has(link)) post({ link, data });
1782
+ },
1783
+ buffered: () => false,
1784
+ close: () => {
1785
+ if (links.delete(link)) post({ link, close: true });
1786
+ }
1787
+ };
1788
+ };
1789
+ };
1790
+ var serveRoomPort = (port, connector) => {
1791
+ const links = /* @__PURE__ */ new Map();
1792
+ const post = (message) => port.postMessage(message);
1793
+ const onMessage = (event) => {
1794
+ const parsed = toParentSchema.safeParse(event.data);
1795
+ if (!parsed.success) return;
1796
+ const message = parsed.data;
1797
+ if ("open" in message) {
1798
+ if (links.has(message.link)) return;
1799
+ const id = message.link;
1800
+ links.set(
1801
+ id,
1802
+ connector(message.open, {
1803
+ open: () => post({ link: id, opened: true }),
1804
+ message: (data) => post({ link: id, data }),
1805
+ close: (code) => {
1806
+ links.delete(id);
1807
+ post({ link: id, closed: code });
1808
+ }
1809
+ })
1810
+ );
1811
+ } else if ("data" in message) links.get(message.link)?.send(message.data);
1812
+ else {
1813
+ links.get(message.link)?.close();
1814
+ links.delete(message.link);
1815
+ }
1816
+ };
1817
+ port.addEventListener("message", onMessage);
1818
+ port.start();
1819
+ return () => {
1820
+ port.removeEventListener("message", onMessage);
1821
+ for (const link of links.values()) link.close();
1822
+ links.clear();
1823
+ };
1824
+ };
1825
+
1826
+ // src/room-session/scoped-connector.ts
1827
+ var MAXIMUM_FORWARDED_REQUESTS = 1024;
1828
+ var closeCode = (reason) => roomCloseCodes[reason].code;
1829
+ var FrameLink = class {
1830
+ constructor(handlers) {
1831
+ this.handlers = handlers;
1832
+ queueMicrotask(() => {
1833
+ if (!this.clientClosed) handlers.open();
1834
+ });
1835
+ }
1836
+ clientClosed = false;
1837
+ serverClosed = false;
1838
+ welcomed = false;
1839
+ get live() {
1840
+ return !this.clientClosed && !this.serverClosed;
1841
+ }
1842
+ send(data) {
1843
+ if (!this.live) return;
1844
+ const delivered = typeof data === "string" ? data : data.slice();
1845
+ queueMicrotask(() => {
1846
+ if (!this.clientClosed) this.handlers.message(delivered);
1847
+ });
1848
+ }
1849
+ close(code) {
1850
+ if (!this.live) return;
1851
+ this.serverClosed = true;
1852
+ queueMicrotask(() => {
1853
+ if (!this.clientClosed) this.handlers.close(code);
1854
+ });
1855
+ }
1856
+ clientClose() {
1857
+ this.clientClosed = true;
1858
+ }
1859
+ };
1860
+ var FrameLinks = class {
1861
+ constructor(welcome) {
1862
+ this.welcome = welcome;
1863
+ }
1864
+ links = /* @__PURE__ */ new Set();
1865
+ stopped = false;
1866
+ add(link) {
1867
+ this.links.add(link);
1868
+ }
1869
+ remove(link) {
1870
+ this.links.delete(link);
1871
+ }
1872
+ welcomed() {
1873
+ return [...this.links].filter((link) => link.live && link.welcomed);
1874
+ }
1875
+ /**
1876
+ * A frame has one link at a time, as a host has one connection: welcoming
1877
+ * a link closes every other as `replaced`, which tells the frame it held
1878
+ * not to come back. A reloaded or slow-closing old frame then cannot
1879
+ * publish over the new one or send input for the same seat.
1880
+ */
1881
+ replaceOthers(link) {
1882
+ for (const other of [...this.links]) {
1883
+ if (other === link) continue;
1884
+ other.close(closeCode("replaced"));
1885
+ this.links.delete(other);
1886
+ }
1887
+ }
1888
+ /**
1889
+ * The page's session changed status. While it is away, welcomed links are
1890
+ * lost and reconnect, and hellos wait; when it is back, waiting hellos are
1891
+ * answered; when it closed for good, so does every link.
1892
+ */
1893
+ follow(status, waiting) {
1894
+ if (status.phase === "closed")
1895
+ return this.closeAll(
1896
+ closeCode(status.reason === "owner" ? "closed" : status.reason)
1897
+ );
1898
+ for (const link of [...this.links]) {
1899
+ if (!link.live) {
1900
+ this.links.delete(link);
1901
+ continue;
1902
+ }
1903
+ if (status.phase !== "open") {
1904
+ if (link.welcomed) {
1905
+ link.close(ABNORMAL_CLOSE_CODE);
1906
+ this.links.delete(link);
1907
+ }
1908
+ } else if (!link.welcomed && waiting(link)) this.welcome(link);
1909
+ }
1910
+ }
1911
+ closeAll(code) {
1912
+ this.stopped = true;
1913
+ for (const link of this.links) link.close(code);
1914
+ this.links.clear();
1915
+ }
1916
+ get closed() {
1917
+ return this.stopped;
1918
+ }
1919
+ };
1920
+ var rosterChanges = (told, seats) => {
1921
+ const frames = [];
1922
+ const current = /* @__PURE__ */ new Set();
1923
+ for (const seat of seats) {
1924
+ current.add(seat.id);
1925
+ if (JSON.stringify(told.get(seat.id)) === JSON.stringify(seat)) continue;
1926
+ told.set(seat.id, seat);
1927
+ frames.push({ type: "seat", seat });
1928
+ }
1929
+ for (const id of [...told.keys()])
1930
+ if (!current.has(id)) {
1931
+ told.delete(id);
1932
+ frames.push({ type: "left", seat: id });
1933
+ }
1934
+ return frames;
1935
+ };
1936
+ var rosterOf = (seats) => new Map(seats.map((seat) => [seat.id, seat]));
1937
+ var createScopedHostConnector = (parent, scope) => {
1938
+ const hellos = /* @__PURE__ */ new WeakMap();
1939
+ const mirrors = /* @__PURE__ */ new WeakMap();
1940
+ const toldSeats = /* @__PURE__ */ new WeakMap();
1941
+ const latestInput = /* @__PURE__ */ new Map();
1942
+ const forwarded = /* @__PURE__ */ new Set();
1943
+ const welcome = (link) => {
1944
+ const seats = hellos.get(link);
1945
+ const room = parent.room;
1946
+ const instance = parent.instance;
1947
+ const code = parent.code;
1948
+ if (seats === void 0 || !room || !instance || !code) return;
1949
+ if (seats !== room.seatsWanted) parent.configure({ seats });
1950
+ const channels = parent.channels().filter((copy2) => scope(copy2.channel)).map((copy2) => ({ ...copy2, revision: 0 }));
1951
+ const mirror = new ChannelMirror();
1952
+ mirror.reset(channels);
1953
+ mirrors.set(link, mirror);
1954
+ toldSeats.set(link, rosterOf(parent.seats));
1955
+ links.replaceOthers(link);
1956
+ link.welcomed = true;
1957
+ link.send(
1958
+ encodeFrame({
1959
+ type: "welcome",
1960
+ code,
1961
+ instance,
1962
+ seats: [...parent.seats],
1963
+ channels,
1964
+ limits: parent.limits,
1965
+ features: [...room.features],
1966
+ seatsWanted: seats,
1967
+ locked: room.locked,
1968
+ activity: room.activity
1969
+ })
1970
+ );
1971
+ if (latestInput.size > 0)
1972
+ link.send(
1973
+ joinHostInputFrames(
1974
+ [...latestInput].map(
1975
+ ([seat, payload]) => encodeHostInputFrame(seat, encodePhoneInputFrame(payload))
1976
+ )
1977
+ )
1978
+ );
1979
+ };
1980
+ const links = new FrameLinks(welcome);
1981
+ const forward = (frame) => {
1982
+ const data = encodeFrame(frame);
1983
+ for (const link of links.welcomed()) link.send(data);
1984
+ };
1985
+ const releases = [
1986
+ parent.on(
1987
+ "status",
1988
+ (status) => links.follow(status, (link) => hellos.has(link))
1989
+ ),
1990
+ parent.on("seats", (seats) => {
1991
+ const present = new Set(seats.map((seat) => seat.id));
1992
+ for (const seat of [...latestInput.keys()])
1993
+ if (!present.has(seat)) latestInput.delete(seat);
1994
+ for (const entry of [...forwarded])
1995
+ if (!present.has(entry.slice(0, entry.indexOf(":"))))
1996
+ forwarded.delete(entry);
1997
+ for (const link of links.welcomed()) {
1998
+ const told = toldSeats.get(link);
1999
+ if (!told) continue;
2000
+ for (const frame of rosterChanges(told, seats))
2001
+ link.send(encodeFrame(frame));
2002
+ }
2003
+ }),
2004
+ // A seat's new page restarts its controls: the frame decodes them afresh too.
2005
+ parent.on("inputBaseline", (seat) => {
2006
+ latestInput.delete(seat);
2007
+ const view = parent.seats.find((candidate) => candidate.id === seat);
2008
+ if (view) forward({ type: "seat", seat: view, inputBaseline: true });
2009
+ }),
2010
+ parent.on("inputFrame", (frame) => {
2011
+ let records;
2012
+ try {
2013
+ records = decodeHostInputFrame(frame);
2014
+ } catch {
2015
+ return;
2016
+ }
2017
+ for (const record of records)
2018
+ latestInput.set(record.seat, record.payload.slice());
2019
+ for (const link of links.welcomed()) link.send(frame);
2020
+ }),
2021
+ parent.on("request", (request) => {
2022
+ if (!scope(request.channel) || links.welcomed().length === 0) return;
2023
+ forwarded.add(`${request.seat}:${request.id}`);
2024
+ if (forwarded.size > MAXIMUM_FORWARDED_REQUESTS)
2025
+ forwarded.delete(forwarded.values().next().value);
2026
+ forward({ type: "request", ...request });
2027
+ })
2028
+ ];
2029
+ const close = () => {
2030
+ links.closeAll(closeCode("closed"));
2031
+ for (const release of releases.splice(0)) release();
2032
+ };
2033
+ const receive = (link, data) => {
2034
+ if (!link.live) return;
2035
+ if (!hellos.has(link)) {
2036
+ const hello = typeof data === "string" ? parseHostHello(data) : null;
2037
+ if (!hello) return link.close(closeCode("unsupported-version"));
2038
+ hellos.set(link, hello.seats);
2039
+ if (parent.status.phase === "open") welcome(link);
2040
+ return;
2041
+ }
2042
+ if (data === PING_FRAME) return link.send(PONG_FRAME);
2043
+ if (!link.welcomed) return;
2044
+ if (typeof data !== "string") return link.close(closeCode("unauthorised"));
2045
+ const parsed = parseHostToRoomFrame(data);
2046
+ if (parsed.status === "unknown") return;
2047
+ if (parsed.status !== "frame")
2048
+ return link.close(closeCode("limits-broken"));
2049
+ const frame = parsed.frame;
2050
+ switch (frame.type) {
2051
+ case "state": {
2052
+ if (!scope(frame.channel)) return link.close(closeCode("unauthorised"));
2053
+ const mirror = mirrors.get(link);
2054
+ const document2 = mirror?.receive(frame) ?? null;
2055
+ const copy2 = mirror?.copy(frame.channel);
2056
+ if (document2 === null || !copy2)
2057
+ return link.close(closeCode("limits-broken"));
2058
+ try {
2059
+ parent.publish(frame.channel, document2, {
2060
+ ...copy2.fingerprint === void 0 ? {} : { fingerprint: copy2.fingerprint },
2061
+ ...copy2.private === void 0 ? {} : { private: copy2.private }
2062
+ });
2063
+ } catch {
2064
+ link.close(closeCode("limits-broken"));
2065
+ }
2066
+ return;
2067
+ }
2068
+ case "response":
2069
+ if (forwarded.delete(`${frame.seat}:${frame.id}`))
2070
+ parent.respond(frame.seat, frame.id, frame.result);
2071
+ return;
2072
+ case "signal":
2073
+ return parent.signal(frame.kind, frame.payload, frame.seat);
2074
+ case "room":
2075
+ return parent.configure({
2076
+ ...frame.seats === void 0 ? {} : { seats: frame.seats },
2077
+ ...frame.locked === void 0 ? {} : { locked: frame.locked }
2078
+ });
2079
+ case "remove":
2080
+ return parent.remove(frame.seat);
2081
+ case "drop":
2082
+ if (!scope(frame.channel)) return link.close(closeCode("unauthorised"));
2083
+ mirrors.get(link)?.drop(frame.channel);
2084
+ return parent.drop(frame.channel);
2085
+ case "activity":
2086
+ case "end":
2087
+ return link.close(closeCode("unauthorised"));
2088
+ }
2089
+ };
2090
+ const connector = (address, handlers) => {
2091
+ const link = new FrameLink(handlers);
2092
+ if (address.role !== "host" || links.closed) {
2093
+ link.close(closeCode(links.closed ? "closed" : "unauthorised"));
2094
+ return { send: () => {
2095
+ }, buffered: () => false, close: () => {
2096
+ } };
2097
+ }
2098
+ links.add(link);
2099
+ if (parent.status.phase === "closed")
2100
+ links.follow(parent.status, () => false);
2101
+ return {
2102
+ send: (data) => receive(link, data),
2103
+ buffered: () => false,
2104
+ close: () => {
2105
+ link.clientClose();
2106
+ links.remove(link);
2107
+ }
2108
+ };
2109
+ };
2110
+ return {
2111
+ connector,
2112
+ close,
2113
+ end: () => {
2114
+ close();
2115
+ for (const copy2 of parent.channels())
2116
+ if (scope(copy2.channel)) parent.drop(copy2.channel);
2117
+ }
2118
+ };
2119
+ };
2120
+ var createScopedPhoneConnector = (parent, scope, options = {}) => {
2121
+ const hellos = /* @__PURE__ */ new WeakSet();
2122
+ const revisions = /* @__PURE__ */ new WeakMap();
2123
+ const restarted = /* @__PURE__ */ new WeakSet();
2124
+ const toldSeats = /* @__PURE__ */ new WeakMap();
2125
+ const welcome = (link) => {
2126
+ const instance = parent.instance;
2127
+ const seat = parent.seat;
2128
+ if (!hellos.has(link) || !instance || !seat) return;
2129
+ const channels = [...parent.documents()].filter(([channel]) => scope(channel)).map(([channel, document2]) => ({ channel, revision: 0, document: document2 }));
2130
+ revisions.set(
2131
+ link,
2132
+ new Map(channels.map((copy2) => [copy2.channel, copy2.revision]))
2133
+ );
2134
+ toldSeats.set(link, rosterOf(parent.seats));
2135
+ links.replaceOthers(link);
2136
+ if (!restarted.has(link)) {
2137
+ restarted.add(link);
2138
+ parent.restartInput();
2139
+ }
2140
+ link.welcomed = true;
2141
+ link.send(
2142
+ encodeFrame({
2143
+ type: "welcome",
2144
+ code: parent.code,
2145
+ instance,
2146
+ seat,
2147
+ seats: [...parent.seats],
2148
+ channels,
2149
+ limits: parent.limits,
2150
+ features: [...parent.features],
2151
+ host: parent.host
2152
+ })
2153
+ );
2154
+ };
2155
+ const links = new FrameLinks(welcome);
2156
+ const forward = (frame) => {
2157
+ const data = encodeFrame(frame);
2158
+ for (const link of links.welcomed()) link.send(data);
2159
+ };
2160
+ const releases = [
2161
+ parent.on(
2162
+ "status",
2163
+ (status) => links.follow(status, (link) => hellos.has(link))
2164
+ ),
2165
+ parent.on("seats", (seats) => {
2166
+ for (const link of links.welcomed()) {
2167
+ const told = toldSeats.get(link);
2168
+ if (!told) continue;
2169
+ for (const frame of rosterChanges(told, seats))
2170
+ link.send(encodeFrame(frame));
2171
+ }
2172
+ }),
2173
+ parent.on("host", (present) => forward({ type: "host", present })),
2174
+ parent.on("signal", (signal) => forward({ type: "signal", ...signal })),
2175
+ parent.on("state", ({ channel, document: document2 }) => {
2176
+ if (!scope(channel)) return;
2177
+ for (const link of links.welcomed()) {
2178
+ const held = revisions.get(link);
2179
+ if (!held) continue;
2180
+ const revision = (held.get(channel) ?? 0) + 1;
2181
+ held.set(channel, revision);
2182
+ link.send(encodeFrame({ type: "state", channel, revision, document: document2 }));
2183
+ }
2184
+ }),
2185
+ parent.on("drop", ({ channel }) => {
2186
+ if (!scope(channel)) return;
2187
+ for (const link of links.welcomed()) revisions.get(link)?.delete(channel);
2188
+ forward({ type: "drop", channel });
2189
+ })
2190
+ ];
2191
+ const receive = (link, data) => {
2192
+ if (!link.live) return;
2193
+ if (!hellos.has(link)) {
2194
+ const hello = typeof data === "string" ? parsePhoneHello(data) : null;
2195
+ if (!hello) return link.close(closeCode("unsupported-version"));
2196
+ hellos.add(link);
2197
+ if (parent.status.phase === "open") welcome(link);
2198
+ return;
2199
+ }
2200
+ if (data === PING_FRAME) return link.send(PONG_FRAME);
2201
+ if (!link.welcomed) return;
2202
+ if (typeof data !== "string") {
2203
+ if (data[0] !== INPUT_FRAME_KIND)
2204
+ return link.close(closeCode("limits-broken"));
2205
+ return parent.sendInputFrame(data.slice());
2206
+ }
2207
+ const parsed = parsePhoneToRoomFrame(data);
2208
+ if (parsed.status === "unknown") return;
2209
+ if (parsed.status !== "frame")
2210
+ return link.close(closeCode("limits-broken"));
2211
+ const frame = parsed.frame;
2212
+ switch (frame.type) {
2213
+ case "request": {
2214
+ if (!scope(frame.channel)) return link.close(closeCode("unauthorised"));
2215
+ const id = frame.id;
2216
+ void parent.request(frame.channel, frame.name, frame.payload).then((outcome) => {
2217
+ if (outcome.status === "answered")
2218
+ link.send(
2219
+ encodeFrame({ type: "response", id, result: outcome.result })
2220
+ );
2221
+ else if (outcome.status === "refused")
2222
+ link.send(
2223
+ encodeFrame({ type: "response", id, refused: outcome.reason })
2224
+ );
2225
+ });
2226
+ return;
2227
+ }
2228
+ case "profile": {
2229
+ const profile = {
2230
+ ...frame.label === void 0 ? {} : { label: frame.label },
2231
+ ...frame.avatarId === void 0 ? {} : { avatarId: frame.avatarId }
2232
+ };
2233
+ parent.setProfile(profile);
2234
+ options.onProfile?.(profile);
2235
+ return;
2236
+ }
2237
+ case "leave":
2238
+ return parent.leave();
2239
+ }
2240
+ };
2241
+ const connector = (address, handlers) => {
2242
+ const link = new FrameLink(handlers);
2243
+ if (address.role !== "phone" || links.closed) {
2244
+ link.close(closeCode(links.closed ? "closed" : "unauthorised"));
2245
+ return { send: () => {
2246
+ }, buffered: () => false, close: () => {
2247
+ } };
2248
+ }
2249
+ links.add(link);
2250
+ if (parent.status.phase === "closed")
2251
+ links.follow(parent.status, () => false);
2252
+ return {
2253
+ send: (data) => receive(link, data),
2254
+ buffered: () => false,
2255
+ close: () => {
2256
+ link.clientClose();
2257
+ links.remove(link);
2258
+ }
2259
+ };
2260
+ };
2261
+ return {
2262
+ connector,
2263
+ close: () => {
2264
+ links.closeAll(closeCode("closed"));
2265
+ for (const release of releases.splice(0)) release();
2266
+ }
2267
+ };
2268
+ };
2269
+
2270
+ // src/room-session/web-socket-link.ts
2271
+ var roomSocketUrls = (origin) => {
2272
+ const base = new URL(origin);
2273
+ if (base.protocol === "http:") base.protocol = "ws:";
2274
+ if (base.protocol === "https:") base.protocol = "wss:";
2275
+ if (base.protocol !== "ws:" && base.protocol !== "wss:")
2276
+ throw new Error(`"${origin}" is not a WebSocket or HTTP origin.`);
2277
+ const prefix = base.pathname.replace(/\/$/, "");
2278
+ return (address) => {
2279
+ const url = new URL(base);
2280
+ url.pathname = `${prefix}${roomPath(address)}`;
2281
+ return url;
2282
+ };
2283
+ };
2284
+ var createWebSocketConnector = (origin) => {
2285
+ const urlFor = roomSocketUrls(origin);
2286
+ return (address, handlers) => {
2287
+ const socket = new WebSocket(urlFor(address));
2288
+ socket.binaryType = "arraybuffer";
2289
+ let closedHere = false;
2290
+ socket.onopen = () => handlers.open();
2291
+ socket.onmessage = (event) => handlers.message(
2292
+ typeof event.data === "string" ? event.data : new Uint8Array(event.data)
2293
+ );
2294
+ socket.onclose = (event) => {
2295
+ if (!closedHere) handlers.close(event.code);
2296
+ };
2297
+ return {
2298
+ send: (data) => {
2299
+ if (socket.readyState === WebSocket.OPEN) socket.send(data);
2300
+ },
2301
+ buffered: () => socket.bufferedAmount > 0,
2302
+ close: () => {
2303
+ closedHere = true;
2304
+ socket.close(1e3);
2305
+ }
2306
+ };
2307
+ };
2308
+ };
2309
+ // Annotate the CommonJS export names for ESM import in node:
2310
+ 0 && (module.exports = {
2311
+ ChannelMirror,
2312
+ ChannelPublisher,
2313
+ DEFAULT_HEARTBEAT,
2314
+ DEFAULT_HELLO_ANSWER_WITHIN_MS,
2315
+ DEFAULT_REQUEST_TIMEOUT_MS,
2316
+ DEFAULT_RETRY,
2317
+ HostInputDecoder,
2318
+ HostRoomSession,
2319
+ PhoneInputLane,
2320
+ PhoneRoomSession,
2321
+ SESSION_SDK,
2322
+ STICK_CHANGE_HUNDREDTHS,
2323
+ SessionLink,
2324
+ browserDeviceWakeEvents,
2325
+ createLoopbackConnector,
2326
+ createPortConnector,
2327
+ createRoomKey,
2328
+ createScopedHostConnector,
2329
+ createScopedPhoneConnector,
2330
+ createWebSocketConnector,
2331
+ roomSocketUrls,
2332
+ serveRoomPort,
2333
+ spacingForRate,
2334
+ systemRoomClock
2335
+ });
2336
+ //# sourceMappingURL=room-session.cjs.map