gemi 0.136.0 → 0.138.0

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 (253) hide show
  1. package/dist/ai/Agent.d.ts +48 -5
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +42 -2
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/index.d.ts +3 -1
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +85 -18
  8. package/dist/ai/index.js.map +7 -6
  9. package/dist/ai/memory/AgentMemories.d.ts +226 -0
  10. package/dist/ai/memory/AgentMemories.d.ts.map +1 -0
  11. package/dist/ai/memory/AgentMemoryStore.d.ts +182 -0
  12. package/dist/ai/memory/AgentMemoryStore.d.ts.map +1 -0
  13. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts +76 -0
  14. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts.map +1 -0
  15. package/dist/ai/memory/contextBlock.d.ts +32 -0
  16. package/dist/ai/memory/contextBlock.d.ts.map +1 -0
  17. package/dist/ai/memory/index.d.ts +6 -0
  18. package/dist/ai/memory/index.d.ts.map +1 -0
  19. package/dist/ai/memory/runMemory.d.ts +355 -0
  20. package/dist/ai/memory/runMemory.d.ts.map +1 -0
  21. package/dist/ai/memory/safety.d.ts +34 -0
  22. package/dist/ai/memory/safety.d.ts.map +1 -0
  23. package/dist/ai/memory/search.d.ts +23 -0
  24. package/dist/ai/memory/search.d.ts.map +1 -0
  25. package/dist/ai/providers/errors.d.ts +9 -1
  26. package/dist/ai/providers/errors.d.ts.map +1 -1
  27. package/dist/ai/providers/http.d.ts.map +1 -1
  28. package/dist/ai/providers/images.d.ts +2 -0
  29. package/dist/ai/providers/images.d.ts.map +1 -1
  30. package/dist/ai/types.d.ts +10 -1
  31. package/dist/ai/types.d.ts.map +1 -1
  32. package/dist/app/index.js +1 -1
  33. package/dist/bun/plugin.js +1 -1
  34. package/dist/bun/preload.js +1 -1
  35. package/dist/{chunk-rnp5k8m3.js → chunk-038xtqpm.js} +2 -2
  36. package/dist/{chunk-rnp5k8m3.js.map → chunk-038xtqpm.js.map} +1 -1
  37. package/dist/{chunk-04tkpna8.js → chunk-1y6hxv30.js} +2 -2
  38. package/dist/{chunk-04tkpna8.js.map → chunk-1y6hxv30.js.map} +1 -1
  39. package/dist/{chunk-5pdgh9a1.js → chunk-26yghzet.js} +2 -2
  40. package/dist/{chunk-5pdgh9a1.js.map → chunk-26yghzet.js.map} +1 -1
  41. package/dist/{chunk-ha15x5ns.js → chunk-27xv8kty.js} +2 -2
  42. package/dist/{chunk-ha15x5ns.js.map → chunk-27xv8kty.js.map} +1 -1
  43. package/dist/{chunk-k2xeskp6.js → chunk-3jkem5gq.js} +2 -2
  44. package/dist/{chunk-k2xeskp6.js.map → chunk-3jkem5gq.js.map} +1 -1
  45. package/dist/{chunk-q15f5g86.js → chunk-46bwknb5.js} +3 -3
  46. package/dist/{chunk-q15f5g86.js.map → chunk-46bwknb5.js.map} +1 -1
  47. package/dist/{chunk-8sde8337.js → chunk-4jc7wbet.js} +2 -2
  48. package/dist/{chunk-8sde8337.js.map → chunk-4jc7wbet.js.map} +1 -1
  49. package/dist/chunk-4wyhf6j2.js +10 -0
  50. package/dist/{chunk-3gx7wcrt.js.map → chunk-4wyhf6j2.js.map} +3 -3
  51. package/dist/{chunk-feajsgns.js → chunk-5benn2ys.js} +3 -3
  52. package/dist/{chunk-feajsgns.js.map → chunk-5benn2ys.js.map} +1 -1
  53. package/dist/{chunk-rzqft8q8.js → chunk-6qzyq0g5.js} +2 -2
  54. package/dist/{chunk-rzqft8q8.js.map → chunk-6qzyq0g5.js.map} +1 -1
  55. package/dist/{chunk-6qty7at2.js → chunk-78zfqt54.js} +2 -2
  56. package/dist/{chunk-6qty7at2.js.map → chunk-78zfqt54.js.map} +1 -1
  57. package/dist/{chunk-ysc7ykss.js → chunk-7d26eqv1.js} +2 -2
  58. package/dist/{chunk-ysc7ykss.js.map → chunk-7d26eqv1.js.map} +1 -1
  59. package/dist/{chunk-6fr6j338.js → chunk-7t7jh8t2.js} +2 -2
  60. package/dist/{chunk-6fr6j338.js.map → chunk-7t7jh8t2.js.map} +1 -1
  61. package/dist/{chunk-xvvsc58s.js → chunk-7vxeqxxr.js} +2 -2
  62. package/dist/{chunk-xvvsc58s.js.map → chunk-7vxeqxxr.js.map} +1 -1
  63. package/dist/{chunk-zyhmn3hy.js → chunk-80fjsb26.js} +3 -3
  64. package/dist/{chunk-zyhmn3hy.js.map → chunk-80fjsb26.js.map} +1 -1
  65. package/dist/{chunk-xymr3asa.js → chunk-85k70cme.js} +3 -3
  66. package/dist/{chunk-xymr3asa.js.map → chunk-85k70cme.js.map} +1 -1
  67. package/dist/{chunk-ka991yx4.js → chunk-8dmhbj4m.js} +2 -2
  68. package/dist/{chunk-ka991yx4.js.map → chunk-8dmhbj4m.js.map} +1 -1
  69. package/dist/{chunk-8ryrjtn0.js → chunk-8ef5c93d.js} +2 -2
  70. package/dist/{chunk-8ryrjtn0.js.map → chunk-8ef5c93d.js.map} +1 -1
  71. package/dist/{chunk-t33yh84d.js → chunk-8p4t8x9c.js} +2 -2
  72. package/dist/{chunk-t33yh84d.js.map → chunk-8p4t8x9c.js.map} +1 -1
  73. package/dist/{chunk-7nxnyw7x.js → chunk-965gfa41.js} +2 -2
  74. package/dist/{chunk-7nxnyw7x.js.map → chunk-965gfa41.js.map} +1 -1
  75. package/dist/{chunk-swwkdm75.js → chunk-974p7em0.js} +2 -2
  76. package/dist/{chunk-swwkdm75.js.map → chunk-974p7em0.js.map} +1 -1
  77. package/dist/{chunk-krk880my.js → chunk-9s203ks3.js} +2 -2
  78. package/dist/{chunk-krk880my.js.map → chunk-9s203ks3.js.map} +1 -1
  79. package/dist/{chunk-0eamc2tr.js → chunk-9wc53ywv.js} +2 -2
  80. package/dist/{chunk-0eamc2tr.js.map → chunk-9wc53ywv.js.map} +1 -1
  81. package/dist/{chunk-hb9hm8za.js → chunk-a2fhbstt.js} +3 -3
  82. package/dist/{chunk-hb9hm8za.js.map → chunk-a2fhbstt.js.map} +1 -1
  83. package/dist/{chunk-cxsvzqd4.js → chunk-aj2sr77y.js} +2 -2
  84. package/dist/{chunk-cxsvzqd4.js.map → chunk-aj2sr77y.js.map} +1 -1
  85. package/dist/{chunk-0gg4e94v.js → chunk-an1nja68.js} +2 -2
  86. package/dist/{chunk-0gg4e94v.js.map → chunk-an1nja68.js.map} +1 -1
  87. package/dist/{chunk-jy9dkgt0.js → chunk-ant9ck0r.js} +2 -2
  88. package/dist/{chunk-jy9dkgt0.js.map → chunk-ant9ck0r.js.map} +1 -1
  89. package/dist/{chunk-sa6cxt3g.js → chunk-bg0e39dk.js} +2 -2
  90. package/dist/{chunk-sa6cxt3g.js.map → chunk-bg0e39dk.js.map} +1 -1
  91. package/dist/{chunk-1awxdnb6.js → chunk-c0m8pcbd.js} +1 -1
  92. package/dist/{chunk-65j32dtn.js → chunk-c6c7p43e.js} +2 -2
  93. package/dist/{chunk-65j32dtn.js.map → chunk-c6c7p43e.js.map} +1 -1
  94. package/dist/{chunk-x9bk5s21.js → chunk-c83e4ghx.js} +2 -2
  95. package/dist/{chunk-x9bk5s21.js.map → chunk-c83e4ghx.js.map} +1 -1
  96. package/dist/{chunk-jgx8ggbz.js → chunk-cedmppcy.js} +2 -2
  97. package/dist/{chunk-jgx8ggbz.js.map → chunk-cedmppcy.js.map} +1 -1
  98. package/dist/{chunk-wrsf2abe.js → chunk-chyt9th4.js} +2 -2
  99. package/dist/{chunk-wrsf2abe.js.map → chunk-chyt9th4.js.map} +1 -1
  100. package/dist/{chunk-qfra7gah.js → chunk-d368es1y.js} +2 -2
  101. package/dist/{chunk-qfra7gah.js.map → chunk-d368es1y.js.map} +1 -1
  102. package/dist/{chunk-dt95z6et.js → chunk-d492ae5e.js} +2 -2
  103. package/dist/{chunk-dt95z6et.js.map → chunk-d492ae5e.js.map} +1 -1
  104. package/dist/{chunk-beb265c9.js → chunk-e440f645.js} +2 -2
  105. package/dist/{chunk-beb265c9.js.map → chunk-e440f645.js.map} +1 -1
  106. package/dist/{chunk-njpnstck.js → chunk-eqzxvfvt.js} +2 -2
  107. package/dist/{chunk-njpnstck.js.map → chunk-eqzxvfvt.js.map} +1 -1
  108. package/dist/{chunk-t8xs9ptb.js → chunk-es3mah07.js} +2 -2
  109. package/dist/{chunk-t8xs9ptb.js.map → chunk-es3mah07.js.map} +1 -1
  110. package/dist/{chunk-99a4e6zf.js → chunk-f9w78tbd.js} +2 -2
  111. package/dist/{chunk-99a4e6zf.js.map → chunk-f9w78tbd.js.map} +1 -1
  112. package/dist/chunk-fs4ntgdr.js +5 -0
  113. package/dist/{chunk-47e7fbsp.js.map → chunk-fs4ntgdr.js.map} +1 -1
  114. package/dist/{chunk-gng5e7pd.js → chunk-fwmmy0jn.js} +1 -1
  115. package/dist/{chunk-mw7ft5bs.js → chunk-g22q8j2s.js} +2 -2
  116. package/dist/{chunk-mw7ft5bs.js.map → chunk-g22q8j2s.js.map} +1 -1
  117. package/dist/{chunk-z9xxthp1.js → chunk-ghbzre7k.js} +3 -3
  118. package/dist/{chunk-z9xxthp1.js.map → chunk-ghbzre7k.js.map} +1 -1
  119. package/dist/{chunk-x5hj0mqp.js → chunk-gq4fr0zn.js} +3 -3
  120. package/dist/{chunk-x5hj0mqp.js.map → chunk-gq4fr0zn.js.map} +1 -1
  121. package/dist/{chunk-x51tegk3.js → chunk-gqcmnyc8.js} +2 -2
  122. package/dist/{chunk-x51tegk3.js.map → chunk-gqcmnyc8.js.map} +1 -1
  123. package/dist/{chunk-x16ckgq1.js → chunk-h0ydk8cc.js} +2 -2
  124. package/dist/{chunk-x16ckgq1.js.map → chunk-h0ydk8cc.js.map} +1 -1
  125. package/dist/{chunk-m9vwg9j1.js → chunk-jys3n8xv.js} +3 -3
  126. package/dist/{chunk-m9vwg9j1.js.map → chunk-jys3n8xv.js.map} +1 -1
  127. package/dist/{chunk-3h37f124.js → chunk-kpb8xvrv.js} +2 -2
  128. package/dist/{chunk-3h37f124.js.map → chunk-kpb8xvrv.js.map} +1 -1
  129. package/dist/{chunk-mpqvmge4.js → chunk-kzdkpz04.js} +1 -1
  130. package/dist/{chunk-0rhf4g12.js → chunk-md6wfc1h.js} +3 -3
  131. package/dist/{chunk-0rhf4g12.js.map → chunk-md6wfc1h.js.map} +1 -1
  132. package/dist/chunk-n1n7qb34.js +117 -0
  133. package/dist/{chunk-541s0vkt.js.map → chunk-n1n7qb34.js.map} +6 -5
  134. package/dist/{chunk-s025aycr.js → chunk-n2czjpz9.js} +2 -2
  135. package/dist/{chunk-s025aycr.js.map → chunk-n2czjpz9.js.map} +1 -1
  136. package/dist/{chunk-ff60bzvf.js → chunk-n7576zsr.js} +3 -3
  137. package/dist/{chunk-ff60bzvf.js.map → chunk-n7576zsr.js.map} +1 -1
  138. package/dist/{chunk-s782bzeq.js → chunk-nbfksexg.js} +2 -2
  139. package/dist/{chunk-s782bzeq.js.map → chunk-nbfksexg.js.map} +1 -1
  140. package/dist/{chunk-p82868xx.js → chunk-p1y58p84.js} +2 -2
  141. package/dist/{chunk-p82868xx.js.map → chunk-p1y58p84.js.map} +1 -1
  142. package/dist/{chunk-zv5qyrqg.js → chunk-p2c7z2nr.js} +2 -2
  143. package/dist/{chunk-zv5qyrqg.js.map → chunk-p2c7z2nr.js.map} +1 -1
  144. package/dist/{chunk-vnw91fe1.js → chunk-pv2mtg8n.js} +2 -2
  145. package/dist/{chunk-vnw91fe1.js.map → chunk-pv2mtg8n.js.map} +1 -1
  146. package/dist/{chunk-jx5zx48j.js → chunk-qfhcec6q.js} +2 -2
  147. package/dist/{chunk-jx5zx48j.js.map → chunk-qfhcec6q.js.map} +1 -1
  148. package/dist/{chunk-6hz63ts4.js → chunk-qk6vmvr2.js} +4 -4
  149. package/dist/{chunk-6hz63ts4.js.map → chunk-qk6vmvr2.js.map} +1 -1
  150. package/dist/{chunk-w1cksc5z.js → chunk-qvx8473q.js} +3 -3
  151. package/dist/{chunk-w1cksc5z.js.map → chunk-qvx8473q.js.map} +1 -1
  152. package/dist/{chunk-4278e429.js → chunk-rqb52m93.js} +2 -2
  153. package/dist/{chunk-4278e429.js.map → chunk-rqb52m93.js.map} +1 -1
  154. package/dist/{chunk-py1twqh8.js → chunk-skmdmqv7.js} +2 -2
  155. package/dist/{chunk-py1twqh8.js.map → chunk-skmdmqv7.js.map} +1 -1
  156. package/dist/{chunk-53rr32zm.js → chunk-ted0qjps.js} +1 -1
  157. package/dist/{chunk-hj88dcss.js → chunk-v4dp93qv.js} +3 -3
  158. package/dist/{chunk-hj88dcss.js.map → chunk-v4dp93qv.js.map} +1 -1
  159. package/dist/{chunk-33hdxe7v.js → chunk-vmr4d6hc.js} +1 -1
  160. package/dist/{chunk-3dpmkxp7.js → chunk-vtc1khbm.js} +2 -2
  161. package/dist/{chunk-3dpmkxp7.js.map → chunk-vtc1khbm.js.map} +1 -1
  162. package/dist/{chunk-3g5q0cj5.js → chunk-vz5rrcnh.js} +2 -2
  163. package/dist/{chunk-3g5q0cj5.js.map → chunk-vz5rrcnh.js.map} +1 -1
  164. package/dist/{chunk-pm8wjatv.js → chunk-w17p2k8g.js} +3 -3
  165. package/dist/{chunk-pm8wjatv.js.map → chunk-w17p2k8g.js.map} +1 -1
  166. package/dist/{chunk-j5g7qc5f.js → chunk-wbvb1hcx.js} +2 -2
  167. package/dist/{chunk-j5g7qc5f.js.map → chunk-wbvb1hcx.js.map} +1 -1
  168. package/dist/{chunk-jx2mgvvt.js → chunk-xwmy6fby.js} +3 -3
  169. package/dist/{chunk-jx2mgvvt.js.map → chunk-xwmy6fby.js.map} +1 -1
  170. package/dist/{chunk-z61dj480.js → chunk-y6gr3stt.js} +3 -3
  171. package/dist/{chunk-z61dj480.js.map → chunk-y6gr3stt.js.map} +1 -1
  172. package/dist/{chunk-4t41m5f1.js → chunk-yhp70t40.js} +2 -2
  173. package/dist/{chunk-4t41m5f1.js.map → chunk-yhp70t40.js.map} +1 -1
  174. package/dist/{chunk-zypmy8yq.js → chunk-z0jazehw.js} +2 -2
  175. package/dist/{chunk-zypmy8yq.js.map → chunk-z0jazehw.js.map} +1 -1
  176. package/dist/chunk-z88axcxg.js +28 -0
  177. package/dist/chunk-z88axcxg.js.map +27 -0
  178. package/dist/{chunk-gqgpwb88.js → chunk-z969a4nt.js} +2 -2
  179. package/dist/{chunk-gqgpwb88.js.map → chunk-z969a4nt.js.map} +1 -1
  180. package/dist/{chunk-hf492gg2.js → chunk-zj8y4ak5.js} +1 -1
  181. package/dist/{chunk-qpwb3gnh.js → chunk-zvzvgrrn.js} +2 -2
  182. package/dist/{chunk-qpwb3gnh.js.map → chunk-zvzvgrrn.js.map} +1 -1
  183. package/dist/chunks/{RealtimeClient-DsWbFRC7.js → RealtimeClient-B345JtXu.js} +2 -2
  184. package/dist/chunks/{RealtimeClient-DsWbFRC7.js.map → RealtimeClient-B345JtXu.js.map} +1 -1
  185. package/dist/chunks/{ThemeProvider-gWqXjGh-.js → ThemeProvider-BwlMubvu.js} +97 -30
  186. package/dist/chunks/ThemeProvider-BwlMubvu.js.map +1 -0
  187. package/dist/chunks/{fetchFileRequest-BSrgYnAy.js → fetchFileRequest-DKKdn8Yp.js} +2 -2
  188. package/dist/chunks/{fetchFileRequest-BSrgYnAy.js.map → fetchFileRequest-DKKdn8Yp.js.map} +1 -1
  189. package/dist/chunks/{live-CUdMhXHL.js → live-Cq65lqVg.js} +3 -3
  190. package/dist/chunks/{live-CUdMhXHL.js.map → live-Cq65lqVg.js.map} +1 -1
  191. package/dist/chunks/{mutationExtras-CtY-X9m7.js → mutationExtras-KMQj-GZD.js} +2 -2
  192. package/dist/chunks/{mutationExtras-CtY-X9m7.js.map → mutationExtras-KMQj-GZD.js.map} +1 -1
  193. package/dist/client/ServerDataProvider.d.ts +3 -0
  194. package/dist/client/ServerDataProvider.d.ts.map +1 -1
  195. package/dist/client/ThemeProvider.d.ts +23 -8
  196. package/dist/client/ThemeProvider.d.ts.map +1 -1
  197. package/dist/client/index.d.ts +1 -0
  198. package/dist/client/index.d.ts.map +1 -1
  199. package/dist/client/index.js +3 -3
  200. package/dist/client/theme.d.ts +47 -0
  201. package/dist/client/theme.d.ts.map +1 -0
  202. package/dist/config/index.js +1 -1
  203. package/dist/console/run.js +2 -2
  204. package/dist/console/run.js.map +1 -1
  205. package/dist/container/index.js +2 -2
  206. package/dist/container/index.js.map +1 -1
  207. package/dist/database/index.js +2 -2
  208. package/dist/database/index.js.map +1 -1
  209. package/dist/email/index.js +2 -2
  210. package/dist/email/index.js.map +1 -1
  211. package/dist/facades/index.js +2 -2
  212. package/dist/facades/index.js.map +1 -1
  213. package/dist/foundation/index.js +2 -2
  214. package/dist/foundation/index.js.map +1 -1
  215. package/dist/http/index.js +2 -2
  216. package/dist/http/index.js.map +1 -1
  217. package/dist/i18n/dictionaryRuntime.js +2 -2
  218. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  219. package/dist/i18n/index.js +2 -2
  220. package/dist/i18n/index.js.map +1 -1
  221. package/dist/kernel/index.js +2 -2
  222. package/dist/kernel/index.js.map +1 -1
  223. package/dist/orm/index.js +2 -2
  224. package/dist/orm/index.js.map +1 -1
  225. package/dist/server/index.js +2 -2
  226. package/dist/server/index.js.map +1 -1
  227. package/dist/services/index.js +2 -2
  228. package/dist/services/index.js.map +1 -1
  229. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  230. package/dist/services/queue/work.js +2 -2
  231. package/dist/services/queue/work.js.map +1 -1
  232. package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
  233. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  234. package/dist/services/router/config.d.ts +27 -0
  235. package/dist/services/router/config.d.ts.map +1 -1
  236. package/dist/stats/route-table.js +1 -1
  237. package/dist/support/index.js +2 -2
  238. package/dist/support/index.js.map +1 -1
  239. package/dist/testing/index.js +2 -2
  240. package/dist/vitest/index.js +1 -1
  241. package/package.json +1 -1
  242. package/dist/chunk-2cnawkke.js +0 -22
  243. package/dist/chunk-2cnawkke.js.map +0 -21
  244. package/dist/chunk-3gx7wcrt.js +0 -10
  245. package/dist/chunk-47e7fbsp.js +0 -5
  246. package/dist/chunk-541s0vkt.js +0 -122
  247. package/dist/chunks/ThemeProvider-gWqXjGh-.js.map +0 -1
  248. /package/dist/{chunk-1awxdnb6.js.map → chunk-c0m8pcbd.js.map} +0 -0
  249. /package/dist/{chunk-gng5e7pd.js.map → chunk-fwmmy0jn.js.map} +0 -0
  250. /package/dist/{chunk-mpqvmge4.js.map → chunk-kzdkpz04.js.map} +0 -0
  251. /package/dist/{chunk-53rr32zm.js.map → chunk-ted0qjps.js.map} +0 -0
  252. /package/dist/{chunk-33hdxe7v.js.map → chunk-vmr4d6hc.js.map} +0 -0
  253. /package/dist/{chunk-hf492gg2.js.map → chunk-zj8y4ak5.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  class m{name;cron;withoutOverlapping=!1;onOneServer=!1;shouldRun(){return!0}callback(f){}onTick(){}onComplete(){}static exp(f){return f}}
3
- export{m as pd};
3
+ export{m as Bd};
4
4
 
5
- //# debugId=ADF306CF090B8A8064756E2164756E21
5
+ //# debugId=CA191E394274AEC064756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "// A cron expression accepted by `Bun.cron`: a 5-field expression\n// (`minute hour day-of-month month day-of-week`, interpreted in UTC) or one of\n// the nicknames below. The `string & {}` member keeps arbitrary expressions\n// assignable while still surfacing the nicknames in editor autocomplete.\nexport type CronExpression =\n | \"@yearly\"\n | \"@annually\"\n | \"@monthly\"\n | \"@weekly\"\n | \"@daily\"\n | \"@midnight\"\n | \"@hourly\"\n | (string & {});\n\nimport type { HeldLock } from \"../lock/LockManager\";\n\nexport type WithoutOverlapping =\n | boolean\n | {\n /**\n * The lock's lease, in milliseconds: how long it outlives an instance\n * that died holding it. Renewed every third of this while the tick\n * runs, so it does not limit how long a tick may take. Default five\n * minutes.\n */\n expiresAfter?: number;\n };\n\nexport class CronJob {\n name: string;\n cron: CronExpression;\n\n /**\n * Skips a tick while an earlier tick of this job is still running, on this\n * instance or any other sharing the queue's storage. With the database\n * queue driver that is a lock row in `gemi_locks`; with the memory driver\n * it only covers this process.\n *\n * The lock is held across `onTick`, `callback` and `onComplete`, and handed\n * to `callback` as its argument. If its lease is lost while the tick runs\n * (the instance stalled past `expiresAfter`), `lock.lost` aborts and the\n * scheduler logs it. Writes that must not land after that go through\n * `lock.fence(...)`.\n *\n * It does not stop a second instance from running the same tick after the\n * first one finished; `onOneServer` does.\n */\n withoutOverlapping: WithoutOverlapping = false;\n\n /**\n * Runs each tick on one instance only, across every instance sharing the\n * queue's storage: the first to claim the tick's minute runs it, the others\n * skip it. Assumes the instances' clocks agree to well within a minute.\n */\n onOneServer = false;\n\n /**\n * Decides whether this tick happens at all. Evaluated once per tick, before\n * anything else; returning `false` skips `onTick`, `callback` and\n * `onComplete` alike.\n *\n * ### Why this is a member and not a line the job writes for itself\n *\n * A job that reports outward — mails a digest, opens a Sentry issue, pings a\n * channel — must not fire from a laptop, and the guard for that has to cover\n * the whole tick. There was nowhere to write it. gemi calls `onTick` and\n * `onComplete` *outside* `callback`, so a guard placed in a lifecycle hook\n * only stops the hook it lives in: an early `return` at the top of `callback`\n * leaves the job still announcing that it started and still announcing that\n * it finished, which for an outward-reporting job is most of the damage.\n *\n * The only construct that covered every hook was an abstract base class that\n * shadowed `callback` with the guard and renamed the real body to `run()` —\n * and that costs the app the framework's own vocabulary. A job then reads\n * `async run()` while every page of the documentation reads `async\n * callback()`, so the next person to follow the docs writes a `callback` the\n * base class never calls: no error, no output, a job that silently does\n * nothing. Forgetting *this* member fails the other way round — the job runs,\n * which is what it did before anyone asked for a gate.\n *\n * ### What it gates\n *\n * Work, not registration. A job whose gate returns `false` is still\n * scheduled, still holds its `Bun.cron` handle, and still appears in\n * `app(Scheduler).jobs` — \"is it scheduled\" and \"will it do anything\" are\n * different questions and the second one is answered per tick. That is also\n * why this is a method: a field would be read once, when the scheduler\n * constructs the job at boot, and would freeze whatever it saw then.\n *\n * A gate that throws is logged and treated as `false`. Cron work recurs, so\n * a skipped tick is recovered by the next one, while an email sent from the\n * wrong machine is not recovered at all.\n *\n * ### Composing with a base class\n *\n * Nothing here calls `super` for you. A subclass that overrides `shouldRun`\n * for its own reason silently replaces whatever its base was gating on, so\n * narrow rather than redefine:\n *\n * ```typescript\n * async shouldRun() {\n * return (await super.shouldRun()) && this.hasSubscribers();\n * }\n * ```\n *\n * A shared base should annotate its return type as written here rather than\n * let it be inferred: a base returning a plain `boolean` narrows the\n * signature its subclasses inherit, and the `await super` above then does not\n * typecheck against it.\n */\n shouldRun(): Promise<boolean> | boolean {\n return true;\n }\n\n /**\n * The tick's work. `lock` is the `withoutOverlapping` lock when the job\n * declares one.\n */\n callback(_lock?: HeldLock): Promise<void> | void {}\n onTick(): Promise<void> | void {}\n onComplete(): Promise<void> | void {}\n\n static exp(expression: CronExpression) {\n return expression;\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";AA4BO,MAAM,CAAQ,CACnB,KACA,KAiBA,mBAAyC,GAOzC,YAAc,GAwDd,SAAS,EAA+B,CACtC,MAAO,GAOT,QAAQ,CAAC,EAAwC,EACjD,MAAM,EAAyB,EAC/B,UAAU,EAAyB,QAE5B,IAAG,CAAC,EAA4B,CACrC,OAAO,EAEX",
8
- "debugId": "ADF306CF090B8A8064756E2164756E21",
8
+ "debugId": "CA191E394274AEC064756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,4 +1,4 @@
1
- import { H as realtime } from "./ThemeProvider-gWqXjGh-.js";
1
+ import { H as realtime } from "./ThemeProvider-BwlMubvu.js";
2
2
  import { t as channelKey } from "./channelKey-CIhHpX6x.js";
3
3
  //#region services/broadcast/protocol.ts
4
4
  /**
@@ -550,4 +550,4 @@ function tabClient() {
550
550
  //#endregion
551
551
  export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay, tabClient };
552
552
 
553
- //# sourceMappingURL=RealtimeClient-DsWbFRC7.js.map
553
+ //# sourceMappingURL=RealtimeClient-B345JtXu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"RealtimeClient-DsWbFRC7.js","names":[],"sources":["../../services/broadcast/protocol.ts","../../client/realtime/RealtimeClient.ts"],"sourcesContent":["/**\n * The `gemi.v1` WebSocket protocol, shared by the server transport\n * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).\n * Types and constants only: this module is imported by the browser bundle, so\n * it must never import a server module.\n *\n * Every frame is a JSON text frame. Binary frames are refused.\n *\n * From the client:\n *\n * - `{op:\"sub\", id, ch, p?}`: subscribe `id` (chosen by the client, unique per\n * socket) to the channel pattern `ch` with params `p`. The server builds\n * the topic and authorizes it.\n * - `{op:\"unsub\", id}`\n * - `{op:\"ping\"}`: answered with `pong`. The client sends one every\n * `heartbeatMs` and reconnects when it hears nothing for twice that.\n *\n * From the server:\n *\n * - `{op:\"hello\", socketId, tag, heartbeatMs}`: the first frame. `socketId`\n * goes in the `X-Gemi-Socket` header of the client's own requests (for\n * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what\n * an event frame's `x` carries when it skips this socket.\n * - `{op:\"subscribed\", id, t}`: `id` joined topic `t`. Sent only once this\n * process receives the topic's events, so the resync the client runs on it\n * cannot miss one.\n * - `{op:\"denied\", id, code}`: `id` was refused, or later revoked.\n * - `{op:\"ev\", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket\n * whose `tag` is `x`.\n * - `{op:\"gap\"}`: events may have been lost for this socket; resync all.\n * - `{op:\"pong\"}`\n * - `{op:\"bye\", code, retryAfter}`: the server is going away (a restart).\n * Reconnect after `retryAfter` ms.\n */\n\n/** The WebSocket subprotocol. */\nexport const BROADCAST_PROTOCOL = \"gemi.v1\";\n\n/** The default endpoint, `defineBroadcastConfig({ path })`. */\nexport const DEFAULT_SOCKET_PATH = \"/__gemi/socket\";\n\nexport { SOCKET_ID_HEADER } from \"./socketHeader\";\n\n/** What a subscription id may look like. */\nexport const SUBSCRIPTION_ID = /^[A-Za-z0-9_-]{1,32}$/;\n\n/**\n * Close codes the server uses. 1012 and 1013 are the standard \"restart\" and\n * \"try again later\"; the 4xxx ones are gemi's own.\n */\nexport const CloseCode = {\n /** The client went away (tab closed, socket released). */\n Normal: 1000,\n /** A frame that was not JSON text, or not a known op. */\n UnsupportedData: 1003,\n /** Too many frames, or a frame over the size limit. */\n PolicyViolation: 1008,\n /** The server is restarting; `bye` said when to come back. */\n Restart: 1012,\n /** The socket fell too far behind; reconnect and resync. */\n TryAgainLater: 1013,\n /** The socket's user was signed out or its access revoked. */\n Revoked: 4001,\n} as const;\n\n/** Why a subscription was refused. */\nexport type DeniedCode =\n /** No channel with that pattern. Permanent. */\n | \"unknown_channel\"\n /** Missing, extra or malformed params. Permanent. */\n | \"invalid_params\"\n /** The channel's authorization said no. */\n | \"denied\"\n /** Authorization failed (a session store outage, a bug). Retryable. */\n | \"error\"\n /** The socket has `maxChannelsPerSocket` subscriptions already. */\n | \"limit\"\n /** Too many `sub`/`unsub` frames; retry later. */\n | \"rate_limited\"\n /** The subscription was revoked by `Broadcast.revoke`. */\n | \"revoked\"\n /** The frame was malformed, or the id is already in use. */\n | \"invalid\";\n\nexport type ClientFrame =\n | { op: \"sub\"; id: string; ch: string; p?: Record<string, string | number> }\n | { op: \"unsub\"; id: string }\n | { op: \"ping\" };\n\nexport type ServerFrame =\n | { op: \"hello\"; socketId: string; tag: string; heartbeatMs: number }\n | { op: \"subscribed\"; id: string; t: string }\n | { op: \"denied\"; id: string; code: DeniedCode }\n | { op: \"ev\"; t: string; ev: string; d?: unknown; x?: string }\n | { op: \"gap\" }\n | { op: \"pong\" }\n | { op: \"bye\"; code: number; retryAfter: number };\n\n/**\n * Whether a refusal is final for this socket's session: resubscribing will\n * get the same answer, so the client does not retry it on its own.\n */\nexport function isPermanentDenial(code: DeniedCode): boolean {\n return code === \"unknown_channel\" || code === \"invalid_params\" || code === \"invalid\";\n}\n","import {\n BROADCAST_PROTOCOL,\n CloseCode,\n DEFAULT_SOCKET_PATH,\n isPermanentDenial,\n type ClientFrame,\n type DeniedCode,\n type ServerFrame,\n} from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport { realtime } from \"./loader\";\n\n/**\n * Where a channel subscription stands, as the hooks report it.\n *\n * - `idle`: the hook is disabled (`enabled: false`).\n * - `connecting`: the socket is opening, or the `sub` awaits its answer.\n * - `open`: subscribed; events arrive.\n * - `denied`: the server refused (or revoked) it; `code` says why.\n * - `closed`: no socket, on the server, before the first effect, or while\n * waiting to reconnect.\n */\nexport type ChannelStatus = \"idle\" | \"connecting\" | \"open\" | \"denied\" | \"closed\";\n\nexport type ChannelParamValues = Record<string, string | number>;\n\n/** What a hook hands the socket for one channel. */\nexport interface ChannelListener {\n onEvent?(event: string, data: unknown): void;\n /** Events may have been missed: refetch what the channel describes. */\n onResync?(): void;\n onStatus?(status: ChannelStatus, code: DeniedCode | null): void;\n}\n\n/**\n * What the hooks subscribe through: the tab's `RealtimeClient`, or a\n * `FakeSocket` in tests. Returns the release function.\n */\nexport interface RealtimeSocket {\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void;\n}\n\nexport interface RealtimeOptions {\n /** The socket endpoint, `defineBroadcastConfig({ path })`. Default `/__gemi/socket`. */\n path?: string;\n /**\n * How long a hidden tab keeps its socket, in ms, before disconnecting. On\n * becoming visible again it reconnects and resyncs. Default 60 000.\n */\n hiddenDisconnectMs?: number;\n}\n\ninterface ClientInternals {\n /** Test seam: the WebSocket class. */\n WebSocket?: typeof WebSocket;\n /** Test seam: the full URL, instead of the page's origin + `path`. */\n url?: string;\n random?: () => number;\n}\n\n/** The minimum gap between two resyncs of one subscription. */\nexport const RESYNC_COALESCE_MS = 2_000;\n/** How long the socket stays open after its last subscription goes. */\nexport const IDLE_CLOSE_MS = 5_000;\n/**\n * How long a subscription outlives its last listener. A hook that remounts\n * within it (StrictMode's double mount, a route change back, a list that\n * re-renders its rows) picks the same subscription up again: no `unsub`, no\n * new `sub`, nothing counted against the server's rate limit.\n */\nexport const RELEASE_LINGER_MS = 1_500;\n/** The least wait before resending a `sub` denied with `rate_limited`. */\nconst RATE_LIMITED_RETRY_MS = 5_000;\n/**\n * How often a `sub` denied with `limit` is resent on one socket. The socket\n * holds as many channels as the server allows, so only a released one makes\n * room: worth a few tries with backoff, not a retry for as long as the socket\n * lives. Past it the subscription waits for the next connection.\n */\nexport const MAX_LIMIT_RETRIES = 5;\nconst MIN_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 30_000;\nconst DEFAULT_HEARTBEAT_MS = 25_000;\nconst DEFAULT_HIDDEN_DISCONNECT_MS = 60_000;\n\ninterface Entry {\n key: string;\n id: string;\n pattern: string;\n params: ChannelParamValues;\n listeners: Set<ChannelListener>;\n status: ChannelStatus;\n code: DeniedCode | null;\n /** Refused for good: not resent on a reconnect. */\n permanent: boolean;\n topic: string | null;\n lastResyncAt: number;\n resyncTimer: ReturnType<typeof setTimeout> | null;\n /** Set while the entry outlives its last listener; see `RELEASE_LINGER_MS`. */\n lingerTimer: ReturnType<typeof setTimeout> | null;\n /** A transient denial's resend, on the same socket. */\n retryTimer: ReturnType<typeof setTimeout> | null;\n retries: number;\n}\n\n/**\n * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel\n * the mounted hooks subscribe to.\n *\n * Opened by the first subscription and closed a few seconds after the last\n * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the\n * server's `bye.retryAfter`, at once on `online`; resubscribes everything\n * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects\n * when shown. Every `subscribed` ack and every `gap` resyncs the\n * subscription (coalesced to one per 2 s), because events are volatile: a\n * client that may have missed one refetches over HTTP.\n *\n * Loaded on first use (#891): import this module as a type only, and reach\n * the tab's instance through `./loader`, or it lands in every route's entry\n * chunk.\n */\nexport class RealtimeClient implements RealtimeSocket {\n private options: Required<RealtimeOptions>;\n private readonly internals: ClientInternals;\n private ws: WebSocket | null = null;\n private entries = new Map<string, Entry>();\n private byId = new Map<string, Entry>();\n private topics = new Map<string, Set<string>>();\n private nextId = 1;\n private attempt = 0;\n private tag: string | null = null;\n private socketIdValue: string | null = null;\n private heartbeatMs = DEFAULT_HEARTBEAT_MS;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private hiddenTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private livenessTimer: ReturnType<typeof setTimeout> | null = null;\n private retryAfter: number | null = null;\n private revoked = false;\n private pausedWhileHidden = false;\n private listening = false;\n\n constructor(options: RealtimeOptions = {}, internals: ClientInternals = {}) {\n this.options = withDefaults(options);\n this.internals = internals;\n }\n\n configure(options: RealtimeOptions) {\n this.options = withDefaults({ ...this.options, ...options });\n }\n\n /** The id to send as `X-Gemi-Socket`, while the socket is open. */\n get socketId(): string | null {\n return this.socketIdValue;\n }\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n id: String(this.nextId++),\n pattern,\n params: { ...params },\n listeners: new Set(),\n status: \"closed\",\n code: null,\n permanent: false,\n topic: null,\n lastResyncAt: 0,\n resyncTimer: null,\n lingerTimer: null,\n retryTimer: null,\n retries: 0,\n };\n this.entries.set(key, entry);\n this.byId.set(entry.id, entry);\n if (this.isOpen()) {\n this.sendSub(entry);\n }\n }\n if (entry.lingerTimer) {\n clearTimeout(entry.lingerTimer);\n entry.lingerTimer = null;\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n this.cancelIdleClose();\n this.listen();\n if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) {\n this.connect();\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.release(entry!, listener);\n };\n }\n\n private release(entry: Entry, listener: ChannelListener) {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || entry.lingerTimer) return;\n entry.lingerTimer = setTimeout(() => {\n entry.lingerTimer = null;\n if (entry.listeners.size === 0) this.drop(entry);\n }, RELEASE_LINGER_MS);\n }\n\n private drop(entry: Entry) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n this.clearRetry(entry);\n this.entries.delete(entry.key);\n this.byId.delete(entry.id);\n this.dropTopic(entry);\n if (this.isOpen() && (entry.status === \"open\" || entry.status === \"connecting\")) {\n this.send({ op: \"unsub\", id: entry.id });\n }\n if (this.entries.size === 0) this.scheduleIdleClose();\n }\n\n private isOpen() {\n return this.ws !== null && this.ws.readyState === 1;\n }\n\n private connect() {\n if (typeof window === \"undefined\") return;\n if (this.entries.size === 0) return;\n const Impl = this.internals.WebSocket ?? globalThis.WebSocket;\n if (!Impl) return;\n this.clearReconnect();\n let ws: WebSocket;\n try {\n ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n for (const entry of this.entries.values()) {\n if (!entry.permanent) this.setStatus(entry, \"connecting\", null);\n }\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.touch();\n for (const entry of this.entries.values()) {\n if (entry.permanent) continue;\n // A new socket starts every transient denial's count over.\n entry.retries = 0;\n this.sendSub(entry);\n }\n };\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n this.touch();\n let frame: ServerFrame;\n try {\n frame = JSON.parse(String(event.data));\n } catch {\n return;\n }\n this.handle(frame);\n };\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.onClosed(event.code);\n };\n ws.onerror = () => {\n // A `close` follows.\n };\n }\n\n private url(): string {\n if (this.internals.url) return this.internals.url;\n const { protocol, host } = window.location;\n return `${protocol === \"https:\" ? \"wss:\" : \"ws:\"}//${host}${this.options.path}`;\n }\n\n private sendSub(entry: Entry) {\n this.setStatus(entry, \"connecting\", null);\n const frame: ClientFrame = { op: \"sub\", id: entry.id, ch: entry.pattern };\n if (Object.keys(entry.params).length > 0) frame.p = entry.params;\n this.send(frame);\n }\n\n private send(frame: ClientFrame) {\n if (!this.isOpen()) return;\n try {\n this.ws!.send(JSON.stringify(frame));\n } catch {\n // The close handler takes over.\n }\n }\n\n private handle(frame: ServerFrame) {\n switch (frame.op) {\n case \"hello\":\n this.socketIdValue = frame.socketId;\n this.tag = frame.tag;\n this.attempt = 0;\n this.revoked = false;\n if (frame.heartbeatMs > 0) {\n this.heartbeatMs = frame.heartbeatMs;\n }\n this.startHeartbeat();\n return;\n case \"subscribed\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.topic = frame.t;\n let ids = this.topics.get(frame.t);\n if (!ids) this.topics.set(frame.t, (ids = new Set()));\n ids.add(entry.id);\n this.clearRetry(entry);\n entry.retries = 0;\n this.setStatus(entry, \"open\", null);\n // The window between the view rendering and this ack, or the time\n // the socket was down, may have carried events this tab missed.\n this.resync(entry);\n return;\n }\n case \"denied\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.permanent = isPermanentDenial(frame.code);\n this.setStatus(entry, \"denied\", frame.code);\n this.scheduleRetry(entry, frame.code);\n return;\n }\n case \"ev\": {\n if (frame.x !== undefined && frame.x === this.tag) return;\n const ids = this.topics.get(frame.t);\n if (!ids) return;\n for (const id of Array.from(ids)) {\n const entry = this.byId.get(id);\n if (!entry) continue;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onEvent?.(frame.ev, frame.d);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n return;\n }\n case \"gap\":\n for (const entry of this.entries.values()) {\n if (entry.status === \"open\") this.resync(entry);\n }\n return;\n case \"bye\":\n this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);\n return;\n case \"pong\":\n return;\n }\n }\n\n private onClosed(code: number) {\n this.ws = null;\n this.socketIdValue = null;\n this.tag = null;\n this.stopHeartbeat();\n this.topics.clear();\n for (const entry of this.entries.values()) {\n entry.topic = null;\n // The reconnect resends it.\n this.clearRetry(entry);\n if (!entry.permanent) this.setStatus(entry, \"closed\", null);\n }\n if (code === CloseCode.Revoked) this.revoked = true;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();\n }\n\n private scheduleReconnect() {\n this.clearReconnect();\n let delay: number;\n if (this.retryAfter !== null) {\n delay = this.retryAfter;\n this.retryAfter = null;\n } else if (this.revoked) {\n // Signed out or access revoked: come back promptly, as whoever we are now.\n this.revoked = false;\n delay = Math.floor(this.random() * 500);\n } else {\n delay = backoffDelay(this.attempt, this.random());\n }\n this.attempt++;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, delay);\n }\n\n private clearReconnect() {\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n private random() {\n return (this.internals.random ?? Math.random)();\n }\n\n private startHeartbeat() {\n this.stopHeartbeat();\n this.pingTimer = setInterval(() => this.send({ op: \"ping\" }), this.heartbeatMs);\n this.touch();\n }\n\n private stopHeartbeat() {\n if (this.pingTimer) clearInterval(this.pingTimer);\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n this.pingTimer = null;\n this.livenessTimer = null;\n }\n\n /** Anything from the server proves the socket alive. */\n private touch() {\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n const ws = this.ws;\n this.livenessTimer = setTimeout(() => {\n if (this.ws !== ws || !ws) return;\n // Silent for two heartbeats: a dead connection a proxy never closed.\n try {\n ws.close();\n } catch {}\n this.onClosed(1006);\n }, this.heartbeatMs * 2);\n }\n\n private setStatus(entry: Entry, status: ChannelStatus, code: DeniedCode | null) {\n if (entry.status === status && entry.code === code) return;\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onStatus?.(status, code);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n\n /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */\n private resync(entry: Entry) {\n if (entry.resyncTimer) return;\n const now = Date.now();\n const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;\n const fire = () => {\n entry.resyncTimer = null;\n entry.lastResyncAt = Date.now();\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onResync?.();\n } catch (error) {\n reportListenerError(error);\n }\n }\n };\n if (entry.lastResyncAt === 0 || wait <= 0) fire();\n else entry.resyncTimer = setTimeout(fire, wait);\n }\n\n /**\n * A transient denial (`rate_limited`, `error`, `limit`) is retried on the\n * same socket, with backoff: a healthy socket may never reconnect. `denied`\n * and `revoked` are the channel's answer for this session, so they wait for\n * the next connection (a sign-in reconnects), and a permanent one is never\n * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.\n */\n private scheduleRetry(entry: Entry, code: DeniedCode) {\n if (code !== \"rate_limited\" && code !== \"error\" && code !== \"limit\") return;\n if (code === \"limit\" && entry.retries >= MAX_LIMIT_RETRIES) return;\n this.clearRetry(entry);\n const floor = code === \"rate_limited\" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS;\n const delay = Math.max(floor, backoffDelay(entry.retries, this.random()));\n entry.retries++;\n entry.retryTimer = setTimeout(() => {\n entry.retryTimer = null;\n if (this.entries.get(entry.key) !== entry || entry.status !== \"denied\") return;\n if (this.isOpen()) this.sendSub(entry);\n }, delay);\n }\n\n private clearRetry(entry: Entry) {\n if (entry.retryTimer) clearTimeout(entry.retryTimer);\n entry.retryTimer = null;\n }\n\n private dropTopic(entry: Entry) {\n if (!entry.topic) return;\n const ids = this.topics.get(entry.topic);\n ids?.delete(entry.id);\n if (ids && ids.size === 0) this.topics.delete(entry.topic);\n entry.topic = null;\n }\n\n private scheduleIdleClose() {\n this.cancelIdleClose();\n this.idleTimer = setTimeout(() => {\n this.idleTimer = null;\n if (this.entries.size > 0) return;\n this.clearReconnect();\n this.close();\n }, IDLE_CLOSE_MS);\n }\n\n private cancelIdleClose() {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n\n /** Closes the socket without reconnecting. */\n private close() {\n const ws = this.ws;\n if (!ws) return;\n this.ws = null;\n try {\n ws.close(CloseCode.Normal);\n } catch {}\n this.onClosed(CloseCode.Normal);\n }\n\n private listen() {\n if (this.listening || typeof window === \"undefined\") return;\n this.listening = true;\n window.addEventListener(\"online\", this.onOnline);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n }\n }\n\n private onOnline = () => {\n if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;\n this.attempt = 0;\n this.connect();\n };\n\n private onVisibility = () => {\n if (document.visibilityState === \"hidden\") {\n if (this.hiddenTimer) return;\n this.hiddenTimer = setTimeout(() => {\n this.hiddenTimer = null;\n if (document.visibilityState !== \"hidden\") return;\n this.pausedWhileHidden = true;\n this.clearReconnect();\n this.close();\n }, this.options.hiddenDisconnectMs);\n return;\n }\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n this.hiddenTimer = null;\n if (this.pausedWhileHidden) {\n this.pausedWhileHidden = false;\n this.attempt = 0;\n // The `subscribed` acks resync every subscription.\n this.connect();\n }\n };\n\n /**\n * Drops the socket and opens a new one at once, when anything is\n * subscribed. A socket keeps the session it was opened with (the upgrade's\n * cookies), so signing in or out in this tab reconnects it: every channel\n * is then authorized as the new session, and the acks resync.\n */\n reconnect() {\n this.close();\n this.clearReconnect();\n this.attempt = 0;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();\n }\n\n /** For tests: drops the socket, timers and listeners. */\n dispose() {\n this.clearReconnect();\n this.cancelIdleClose();\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n for (const entry of this.entries.values()) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n if (entry.lingerTimer) clearTimeout(entry.lingerTimer);\n this.clearRetry(entry);\n }\n this.entries.clear();\n this.byId.clear();\n this.close();\n if (this.listening && typeof window !== \"undefined\") {\n window.removeEventListener(\"online\", this.onOnline);\n document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.listening = false;\n }\n }\n}\n\n/** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */\nexport function backoffDelay(attempt: number, random: number): number {\n const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));\n return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));\n}\n\nfunction withDefaults(options: RealtimeOptions): Required<RealtimeOptions> {\n return {\n path: options.path ?? DEFAULT_SOCKET_PATH,\n hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS,\n };\n}\n\nfunction reportListenerError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n\n/**\n * The tab's client, created on first use with the options `configureRealtime`\n * set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.\n */\nexport function tabClient(): RealtimeClient {\n return (realtime.client ??= new RealtimeClient(realtime.options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB;;;;;AAclC,IAAa,YAAY;;CAEvB,QAAQ;;CAER,iBAAiB;;CAEjB,iBAAiB;;CAEjB,SAAS;;CAET,eAAe;;CAEf,SAAS;AACX;;;;;AAuCA,SAAgB,kBAAkB,MAA2B;CAC3D,OAAO,SAAS,qBAAqB,SAAS,oBAAoB,SAAS;AAC7E;;;;AC3CA,IAAa,qBAAqB;;AAElC,IAAa,gBAAgB;;;;;;;AAO7B,IAAa,oBAAoB;;AAEjC,IAAM,wBAAwB;;;;;;;AAO9B,IAAa,oBAAoB;AACjC,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,uBAAuB;AAC7B,IAAM,+BAA+B;;;;;;;;;;;;;;;;;AAsCrC,IAAa,iBAAb,MAAsD;CACpD;CACA;CACA,KAA+B;CAC/B,0BAAkB,IAAI,IAAmB;CACzC,uBAAe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a,SAAqD;CACzE,OAAO;EACL,MAAM,QAAQ,QAAA;EACd,oBAAoB,QAAQ,sBAAsB;CACpD;AACF;AAEA,SAAS,oBAAoB,OAAgB;CAC3C,iBAAiB;EACf,MAAM;CACR,CAAC;AACH;;;;;AAMA,SAAgB,YAA4B;CAC1C,OAAQ,SAAS,WAAW,IAAI,eAAe,SAAS,OAAO;AACjE"}
1
+ {"version":3,"file":"RealtimeClient-B345JtXu.js","names":[],"sources":["../../services/broadcast/protocol.ts","../../client/realtime/RealtimeClient.ts"],"sourcesContent":["/**\n * The `gemi.v1` WebSocket protocol, shared by the server transport\n * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).\n * Types and constants only: this module is imported by the browser bundle, so\n * it must never import a server module.\n *\n * Every frame is a JSON text frame. Binary frames are refused.\n *\n * From the client:\n *\n * - `{op:\"sub\", id, ch, p?}`: subscribe `id` (chosen by the client, unique per\n * socket) to the channel pattern `ch` with params `p`. The server builds\n * the topic and authorizes it.\n * - `{op:\"unsub\", id}`\n * - `{op:\"ping\"}`: answered with `pong`. The client sends one every\n * `heartbeatMs` and reconnects when it hears nothing for twice that.\n *\n * From the server:\n *\n * - `{op:\"hello\", socketId, tag, heartbeatMs}`: the first frame. `socketId`\n * goes in the `X-Gemi-Socket` header of the client's own requests (for\n * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what\n * an event frame's `x` carries when it skips this socket.\n * - `{op:\"subscribed\", id, t}`: `id` joined topic `t`. Sent only once this\n * process receives the topic's events, so the resync the client runs on it\n * cannot miss one.\n * - `{op:\"denied\", id, code}`: `id` was refused, or later revoked.\n * - `{op:\"ev\", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket\n * whose `tag` is `x`.\n * - `{op:\"gap\"}`: events may have been lost for this socket; resync all.\n * - `{op:\"pong\"}`\n * - `{op:\"bye\", code, retryAfter}`: the server is going away (a restart).\n * Reconnect after `retryAfter` ms.\n */\n\n/** The WebSocket subprotocol. */\nexport const BROADCAST_PROTOCOL = \"gemi.v1\";\n\n/** The default endpoint, `defineBroadcastConfig({ path })`. */\nexport const DEFAULT_SOCKET_PATH = \"/__gemi/socket\";\n\nexport { SOCKET_ID_HEADER } from \"./socketHeader\";\n\n/** What a subscription id may look like. */\nexport const SUBSCRIPTION_ID = /^[A-Za-z0-9_-]{1,32}$/;\n\n/**\n * Close codes the server uses. 1012 and 1013 are the standard \"restart\" and\n * \"try again later\"; the 4xxx ones are gemi's own.\n */\nexport const CloseCode = {\n /** The client went away (tab closed, socket released). */\n Normal: 1000,\n /** A frame that was not JSON text, or not a known op. */\n UnsupportedData: 1003,\n /** Too many frames, or a frame over the size limit. */\n PolicyViolation: 1008,\n /** The server is restarting; `bye` said when to come back. */\n Restart: 1012,\n /** The socket fell too far behind; reconnect and resync. */\n TryAgainLater: 1013,\n /** The socket's user was signed out or its access revoked. */\n Revoked: 4001,\n} as const;\n\n/** Why a subscription was refused. */\nexport type DeniedCode =\n /** No channel with that pattern. Permanent. */\n | \"unknown_channel\"\n /** Missing, extra or malformed params. Permanent. */\n | \"invalid_params\"\n /** The channel's authorization said no. */\n | \"denied\"\n /** Authorization failed (a session store outage, a bug). Retryable. */\n | \"error\"\n /** The socket has `maxChannelsPerSocket` subscriptions already. */\n | \"limit\"\n /** Too many `sub`/`unsub` frames; retry later. */\n | \"rate_limited\"\n /** The subscription was revoked by `Broadcast.revoke`. */\n | \"revoked\"\n /** The frame was malformed, or the id is already in use. */\n | \"invalid\";\n\nexport type ClientFrame =\n | { op: \"sub\"; id: string; ch: string; p?: Record<string, string | number> }\n | { op: \"unsub\"; id: string }\n | { op: \"ping\" };\n\nexport type ServerFrame =\n | { op: \"hello\"; socketId: string; tag: string; heartbeatMs: number }\n | { op: \"subscribed\"; id: string; t: string }\n | { op: \"denied\"; id: string; code: DeniedCode }\n | { op: \"ev\"; t: string; ev: string; d?: unknown; x?: string }\n | { op: \"gap\" }\n | { op: \"pong\" }\n | { op: \"bye\"; code: number; retryAfter: number };\n\n/**\n * Whether a refusal is final for this socket's session: resubscribing will\n * get the same answer, so the client does not retry it on its own.\n */\nexport function isPermanentDenial(code: DeniedCode): boolean {\n return code === \"unknown_channel\" || code === \"invalid_params\" || code === \"invalid\";\n}\n","import {\n BROADCAST_PROTOCOL,\n CloseCode,\n DEFAULT_SOCKET_PATH,\n isPermanentDenial,\n type ClientFrame,\n type DeniedCode,\n type ServerFrame,\n} from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport { realtime } from \"./loader\";\n\n/**\n * Where a channel subscription stands, as the hooks report it.\n *\n * - `idle`: the hook is disabled (`enabled: false`).\n * - `connecting`: the socket is opening, or the `sub` awaits its answer.\n * - `open`: subscribed; events arrive.\n * - `denied`: the server refused (or revoked) it; `code` says why.\n * - `closed`: no socket, on the server, before the first effect, or while\n * waiting to reconnect.\n */\nexport type ChannelStatus = \"idle\" | \"connecting\" | \"open\" | \"denied\" | \"closed\";\n\nexport type ChannelParamValues = Record<string, string | number>;\n\n/** What a hook hands the socket for one channel. */\nexport interface ChannelListener {\n onEvent?(event: string, data: unknown): void;\n /** Events may have been missed: refetch what the channel describes. */\n onResync?(): void;\n onStatus?(status: ChannelStatus, code: DeniedCode | null): void;\n}\n\n/**\n * What the hooks subscribe through: the tab's `RealtimeClient`, or a\n * `FakeSocket` in tests. Returns the release function.\n */\nexport interface RealtimeSocket {\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void;\n}\n\nexport interface RealtimeOptions {\n /** The socket endpoint, `defineBroadcastConfig({ path })`. Default `/__gemi/socket`. */\n path?: string;\n /**\n * How long a hidden tab keeps its socket, in ms, before disconnecting. On\n * becoming visible again it reconnects and resyncs. Default 60 000.\n */\n hiddenDisconnectMs?: number;\n}\n\ninterface ClientInternals {\n /** Test seam: the WebSocket class. */\n WebSocket?: typeof WebSocket;\n /** Test seam: the full URL, instead of the page's origin + `path`. */\n url?: string;\n random?: () => number;\n}\n\n/** The minimum gap between two resyncs of one subscription. */\nexport const RESYNC_COALESCE_MS = 2_000;\n/** How long the socket stays open after its last subscription goes. */\nexport const IDLE_CLOSE_MS = 5_000;\n/**\n * How long a subscription outlives its last listener. A hook that remounts\n * within it (StrictMode's double mount, a route change back, a list that\n * re-renders its rows) picks the same subscription up again: no `unsub`, no\n * new `sub`, nothing counted against the server's rate limit.\n */\nexport const RELEASE_LINGER_MS = 1_500;\n/** The least wait before resending a `sub` denied with `rate_limited`. */\nconst RATE_LIMITED_RETRY_MS = 5_000;\n/**\n * How often a `sub` denied with `limit` is resent on one socket. The socket\n * holds as many channels as the server allows, so only a released one makes\n * room: worth a few tries with backoff, not a retry for as long as the socket\n * lives. Past it the subscription waits for the next connection.\n */\nexport const MAX_LIMIT_RETRIES = 5;\nconst MIN_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 30_000;\nconst DEFAULT_HEARTBEAT_MS = 25_000;\nconst DEFAULT_HIDDEN_DISCONNECT_MS = 60_000;\n\ninterface Entry {\n key: string;\n id: string;\n pattern: string;\n params: ChannelParamValues;\n listeners: Set<ChannelListener>;\n status: ChannelStatus;\n code: DeniedCode | null;\n /** Refused for good: not resent on a reconnect. */\n permanent: boolean;\n topic: string | null;\n lastResyncAt: number;\n resyncTimer: ReturnType<typeof setTimeout> | null;\n /** Set while the entry outlives its last listener; see `RELEASE_LINGER_MS`. */\n lingerTimer: ReturnType<typeof setTimeout> | null;\n /** A transient denial's resend, on the same socket. */\n retryTimer: ReturnType<typeof setTimeout> | null;\n retries: number;\n}\n\n/**\n * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel\n * the mounted hooks subscribe to.\n *\n * Opened by the first subscription and closed a few seconds after the last\n * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the\n * server's `bye.retryAfter`, at once on `online`; resubscribes everything\n * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects\n * when shown. Every `subscribed` ack and every `gap` resyncs the\n * subscription (coalesced to one per 2 s), because events are volatile: a\n * client that may have missed one refetches over HTTP.\n *\n * Loaded on first use (#891): import this module as a type only, and reach\n * the tab's instance through `./loader`, or it lands in every route's entry\n * chunk.\n */\nexport class RealtimeClient implements RealtimeSocket {\n private options: Required<RealtimeOptions>;\n private readonly internals: ClientInternals;\n private ws: WebSocket | null = null;\n private entries = new Map<string, Entry>();\n private byId = new Map<string, Entry>();\n private topics = new Map<string, Set<string>>();\n private nextId = 1;\n private attempt = 0;\n private tag: string | null = null;\n private socketIdValue: string | null = null;\n private heartbeatMs = DEFAULT_HEARTBEAT_MS;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private hiddenTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private livenessTimer: ReturnType<typeof setTimeout> | null = null;\n private retryAfter: number | null = null;\n private revoked = false;\n private pausedWhileHidden = false;\n private listening = false;\n\n constructor(options: RealtimeOptions = {}, internals: ClientInternals = {}) {\n this.options = withDefaults(options);\n this.internals = internals;\n }\n\n configure(options: RealtimeOptions) {\n this.options = withDefaults({ ...this.options, ...options });\n }\n\n /** The id to send as `X-Gemi-Socket`, while the socket is open. */\n get socketId(): string | null {\n return this.socketIdValue;\n }\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n id: String(this.nextId++),\n pattern,\n params: { ...params },\n listeners: new Set(),\n status: \"closed\",\n code: null,\n permanent: false,\n topic: null,\n lastResyncAt: 0,\n resyncTimer: null,\n lingerTimer: null,\n retryTimer: null,\n retries: 0,\n };\n this.entries.set(key, entry);\n this.byId.set(entry.id, entry);\n if (this.isOpen()) {\n this.sendSub(entry);\n }\n }\n if (entry.lingerTimer) {\n clearTimeout(entry.lingerTimer);\n entry.lingerTimer = null;\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n this.cancelIdleClose();\n this.listen();\n if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) {\n this.connect();\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.release(entry!, listener);\n };\n }\n\n private release(entry: Entry, listener: ChannelListener) {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || entry.lingerTimer) return;\n entry.lingerTimer = setTimeout(() => {\n entry.lingerTimer = null;\n if (entry.listeners.size === 0) this.drop(entry);\n }, RELEASE_LINGER_MS);\n }\n\n private drop(entry: Entry) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n this.clearRetry(entry);\n this.entries.delete(entry.key);\n this.byId.delete(entry.id);\n this.dropTopic(entry);\n if (this.isOpen() && (entry.status === \"open\" || entry.status === \"connecting\")) {\n this.send({ op: \"unsub\", id: entry.id });\n }\n if (this.entries.size === 0) this.scheduleIdleClose();\n }\n\n private isOpen() {\n return this.ws !== null && this.ws.readyState === 1;\n }\n\n private connect() {\n if (typeof window === \"undefined\") return;\n if (this.entries.size === 0) return;\n const Impl = this.internals.WebSocket ?? globalThis.WebSocket;\n if (!Impl) return;\n this.clearReconnect();\n let ws: WebSocket;\n try {\n ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n for (const entry of this.entries.values()) {\n if (!entry.permanent) this.setStatus(entry, \"connecting\", null);\n }\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.touch();\n for (const entry of this.entries.values()) {\n if (entry.permanent) continue;\n // A new socket starts every transient denial's count over.\n entry.retries = 0;\n this.sendSub(entry);\n }\n };\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n this.touch();\n let frame: ServerFrame;\n try {\n frame = JSON.parse(String(event.data));\n } catch {\n return;\n }\n this.handle(frame);\n };\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.onClosed(event.code);\n };\n ws.onerror = () => {\n // A `close` follows.\n };\n }\n\n private url(): string {\n if (this.internals.url) return this.internals.url;\n const { protocol, host } = window.location;\n return `${protocol === \"https:\" ? \"wss:\" : \"ws:\"}//${host}${this.options.path}`;\n }\n\n private sendSub(entry: Entry) {\n this.setStatus(entry, \"connecting\", null);\n const frame: ClientFrame = { op: \"sub\", id: entry.id, ch: entry.pattern };\n if (Object.keys(entry.params).length > 0) frame.p = entry.params;\n this.send(frame);\n }\n\n private send(frame: ClientFrame) {\n if (!this.isOpen()) return;\n try {\n this.ws!.send(JSON.stringify(frame));\n } catch {\n // The close handler takes over.\n }\n }\n\n private handle(frame: ServerFrame) {\n switch (frame.op) {\n case \"hello\":\n this.socketIdValue = frame.socketId;\n this.tag = frame.tag;\n this.attempt = 0;\n this.revoked = false;\n if (frame.heartbeatMs > 0) {\n this.heartbeatMs = frame.heartbeatMs;\n }\n this.startHeartbeat();\n return;\n case \"subscribed\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.topic = frame.t;\n let ids = this.topics.get(frame.t);\n if (!ids) this.topics.set(frame.t, (ids = new Set()));\n ids.add(entry.id);\n this.clearRetry(entry);\n entry.retries = 0;\n this.setStatus(entry, \"open\", null);\n // The window between the view rendering and this ack, or the time\n // the socket was down, may have carried events this tab missed.\n this.resync(entry);\n return;\n }\n case \"denied\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.permanent = isPermanentDenial(frame.code);\n this.setStatus(entry, \"denied\", frame.code);\n this.scheduleRetry(entry, frame.code);\n return;\n }\n case \"ev\": {\n if (frame.x !== undefined && frame.x === this.tag) return;\n const ids = this.topics.get(frame.t);\n if (!ids) return;\n for (const id of Array.from(ids)) {\n const entry = this.byId.get(id);\n if (!entry) continue;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onEvent?.(frame.ev, frame.d);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n return;\n }\n case \"gap\":\n for (const entry of this.entries.values()) {\n if (entry.status === \"open\") this.resync(entry);\n }\n return;\n case \"bye\":\n this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);\n return;\n case \"pong\":\n return;\n }\n }\n\n private onClosed(code: number) {\n this.ws = null;\n this.socketIdValue = null;\n this.tag = null;\n this.stopHeartbeat();\n this.topics.clear();\n for (const entry of this.entries.values()) {\n entry.topic = null;\n // The reconnect resends it.\n this.clearRetry(entry);\n if (!entry.permanent) this.setStatus(entry, \"closed\", null);\n }\n if (code === CloseCode.Revoked) this.revoked = true;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();\n }\n\n private scheduleReconnect() {\n this.clearReconnect();\n let delay: number;\n if (this.retryAfter !== null) {\n delay = this.retryAfter;\n this.retryAfter = null;\n } else if (this.revoked) {\n // Signed out or access revoked: come back promptly, as whoever we are now.\n this.revoked = false;\n delay = Math.floor(this.random() * 500);\n } else {\n delay = backoffDelay(this.attempt, this.random());\n }\n this.attempt++;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, delay);\n }\n\n private clearReconnect() {\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n private random() {\n return (this.internals.random ?? Math.random)();\n }\n\n private startHeartbeat() {\n this.stopHeartbeat();\n this.pingTimer = setInterval(() => this.send({ op: \"ping\" }), this.heartbeatMs);\n this.touch();\n }\n\n private stopHeartbeat() {\n if (this.pingTimer) clearInterval(this.pingTimer);\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n this.pingTimer = null;\n this.livenessTimer = null;\n }\n\n /** Anything from the server proves the socket alive. */\n private touch() {\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n const ws = this.ws;\n this.livenessTimer = setTimeout(() => {\n if (this.ws !== ws || !ws) return;\n // Silent for two heartbeats: a dead connection a proxy never closed.\n try {\n ws.close();\n } catch {}\n this.onClosed(1006);\n }, this.heartbeatMs * 2);\n }\n\n private setStatus(entry: Entry, status: ChannelStatus, code: DeniedCode | null) {\n if (entry.status === status && entry.code === code) return;\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onStatus?.(status, code);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n\n /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */\n private resync(entry: Entry) {\n if (entry.resyncTimer) return;\n const now = Date.now();\n const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;\n const fire = () => {\n entry.resyncTimer = null;\n entry.lastResyncAt = Date.now();\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onResync?.();\n } catch (error) {\n reportListenerError(error);\n }\n }\n };\n if (entry.lastResyncAt === 0 || wait <= 0) fire();\n else entry.resyncTimer = setTimeout(fire, wait);\n }\n\n /**\n * A transient denial (`rate_limited`, `error`, `limit`) is retried on the\n * same socket, with backoff: a healthy socket may never reconnect. `denied`\n * and `revoked` are the channel's answer for this session, so they wait for\n * the next connection (a sign-in reconnects), and a permanent one is never\n * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.\n */\n private scheduleRetry(entry: Entry, code: DeniedCode) {\n if (code !== \"rate_limited\" && code !== \"error\" && code !== \"limit\") return;\n if (code === \"limit\" && entry.retries >= MAX_LIMIT_RETRIES) return;\n this.clearRetry(entry);\n const floor = code === \"rate_limited\" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS;\n const delay = Math.max(floor, backoffDelay(entry.retries, this.random()));\n entry.retries++;\n entry.retryTimer = setTimeout(() => {\n entry.retryTimer = null;\n if (this.entries.get(entry.key) !== entry || entry.status !== \"denied\") return;\n if (this.isOpen()) this.sendSub(entry);\n }, delay);\n }\n\n private clearRetry(entry: Entry) {\n if (entry.retryTimer) clearTimeout(entry.retryTimer);\n entry.retryTimer = null;\n }\n\n private dropTopic(entry: Entry) {\n if (!entry.topic) return;\n const ids = this.topics.get(entry.topic);\n ids?.delete(entry.id);\n if (ids && ids.size === 0) this.topics.delete(entry.topic);\n entry.topic = null;\n }\n\n private scheduleIdleClose() {\n this.cancelIdleClose();\n this.idleTimer = setTimeout(() => {\n this.idleTimer = null;\n if (this.entries.size > 0) return;\n this.clearReconnect();\n this.close();\n }, IDLE_CLOSE_MS);\n }\n\n private cancelIdleClose() {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n\n /** Closes the socket without reconnecting. */\n private close() {\n const ws = this.ws;\n if (!ws) return;\n this.ws = null;\n try {\n ws.close(CloseCode.Normal);\n } catch {}\n this.onClosed(CloseCode.Normal);\n }\n\n private listen() {\n if (this.listening || typeof window === \"undefined\") return;\n this.listening = true;\n window.addEventListener(\"online\", this.onOnline);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n }\n }\n\n private onOnline = () => {\n if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;\n this.attempt = 0;\n this.connect();\n };\n\n private onVisibility = () => {\n if (document.visibilityState === \"hidden\") {\n if (this.hiddenTimer) return;\n this.hiddenTimer = setTimeout(() => {\n this.hiddenTimer = null;\n if (document.visibilityState !== \"hidden\") return;\n this.pausedWhileHidden = true;\n this.clearReconnect();\n this.close();\n }, this.options.hiddenDisconnectMs);\n return;\n }\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n this.hiddenTimer = null;\n if (this.pausedWhileHidden) {\n this.pausedWhileHidden = false;\n this.attempt = 0;\n // The `subscribed` acks resync every subscription.\n this.connect();\n }\n };\n\n /**\n * Drops the socket and opens a new one at once, when anything is\n * subscribed. A socket keeps the session it was opened with (the upgrade's\n * cookies), so signing in or out in this tab reconnects it: every channel\n * is then authorized as the new session, and the acks resync.\n */\n reconnect() {\n this.close();\n this.clearReconnect();\n this.attempt = 0;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();\n }\n\n /** For tests: drops the socket, timers and listeners. */\n dispose() {\n this.clearReconnect();\n this.cancelIdleClose();\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n for (const entry of this.entries.values()) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n if (entry.lingerTimer) clearTimeout(entry.lingerTimer);\n this.clearRetry(entry);\n }\n this.entries.clear();\n this.byId.clear();\n this.close();\n if (this.listening && typeof window !== \"undefined\") {\n window.removeEventListener(\"online\", this.onOnline);\n document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.listening = false;\n }\n }\n}\n\n/** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */\nexport function backoffDelay(attempt: number, random: number): number {\n const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));\n return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));\n}\n\nfunction withDefaults(options: RealtimeOptions): Required<RealtimeOptions> {\n return {\n path: options.path ?? DEFAULT_SOCKET_PATH,\n hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS,\n };\n}\n\nfunction reportListenerError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n\n/**\n * The tab's client, created on first use with the options `configureRealtime`\n * set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.\n */\nexport function tabClient(): RealtimeClient {\n return (realtime.client ??= new RealtimeClient(realtime.options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB;;;;;AAclC,IAAa,YAAY;;CAEvB,QAAQ;;CAER,iBAAiB;;CAEjB,iBAAiB;;CAEjB,SAAS;;CAET,eAAe;;CAEf,SAAS;AACX;;;;;AAuCA,SAAgB,kBAAkB,MAA2B;CAC3D,OAAO,SAAS,qBAAqB,SAAS,oBAAoB,SAAS;AAC7E;;;;AC3CA,IAAa,qBAAqB;;AAElC,IAAa,gBAAgB;;;;;;;AAO7B,IAAa,oBAAoB;;AAEjC,IAAM,wBAAwB;;;;;;;AAO9B,IAAa,oBAAoB;AACjC,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,uBAAuB;AAC7B,IAAM,+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AK,KAAK,IAAI,SAAS,EAAE,CAAC;CAChF,OAAO,KAAK,IAAI,gBAAgB,KAAK,MAAM,SAAS,GAAG,CAAC;AAC1D;AAEA,SAAS,aAAa,SAAqD;CACzE,OAAO;EACL,MAAM,QAAQ,QAAA;EACd,oBAAoB,QAAQ,sBAAsB;CACpD;AACF;AAEA,SAAS,oBAAoB,OAAgB;CAC3C,iBAAiB;EACf,MAAM;CACR,CAAC;AACH;;;;;AAMA,SAAgB,YAA4B;CAC1C,OAAQ,SAAS,WAAW,IAAI,eAAe,SAAS,OAAO;AACjE"}
@@ -779,7 +779,7 @@ function loadedRealtimeClient() {
779
779
  }
780
780
  var loading = null;
781
781
  /** The lazily loaded client. Replaceable in tests, to simulate a failed load. */
782
- var lazyModules = { client: () => import("./RealtimeClient-DsWbFRC7.js") };
782
+ var lazyModules = { client: () => import("./RealtimeClient-B345JtXu.js") };
783
783
  /**
784
784
  * `./live`, loaded by the first live query. `<Page>` in `gemi/testing` sets
785
785
  * `current` up front, so a live query on a provided socket subscribes during
@@ -787,7 +787,7 @@ var lazyModules = { client: () => import("./RealtimeClient-DsWbFRC7.js") };
787
787
  */
788
788
  var liveModule = {
789
789
  current: null,
790
- load: () => import("./live-CUdMhXHL.js").then((n) => n.n)
790
+ load: () => import("./live-Cq65lqVg.js").then((n) => n.n)
791
791
  };
792
792
  /**
793
793
  * The tab's client, loading its module and creating it on first use. `null`
@@ -3563,51 +3563,118 @@ function C(r = [], e = []) {
3563
3563
  return r.length !== e.length || r.some((t, o) => !Object.is(t, e[o]));
3564
3564
  }
3565
3565
  //#endregion
3566
+ //#region client/theme.ts
3567
+ /** The cookie gemi stores the choice in unless `theme.cookie` names another. */
3568
+ var DEFAULT_THEME_COOKIE = "theme";
3569
+ function isTheme(value) {
3570
+ return value === "light" || value === "dark" || value === "system";
3571
+ }
3572
+ /** `"system"` asks the browser; the other two are already resolved. */
3573
+ function resolveTheme(theme, prefersDark) {
3574
+ if (theme === "system") return prefersDark ? "dark" : "light";
3575
+ return theme;
3576
+ }
3577
+ /**
3578
+ * Puts `resolved` on `<html>`: the class, and `color-scheme` for the browser's
3579
+ * own widgets. Removes only the other theme class, never anything else.
3580
+ */
3581
+ function applyTheme(root, resolved) {
3582
+ root.classList.remove(resolved === "dark" ? "light" : "dark");
3583
+ root.classList.add(resolved);
3584
+ root.style.colorScheme = resolved;
3585
+ }
3586
+ /** One year: the choice should outlive the session, as `localStorage` did. */
3587
+ var COOKIE_MAX_AGE = 3600 * 24 * 365;
3588
+ /**
3589
+ * Stores the choice where both the server and the inline script read it: the
3590
+ * cookie. `localStorage` is still written, so a page from an older build that
3591
+ * only reads storage agrees with this one.
3592
+ */
3593
+ function storeTheme(theme, cookie = DEFAULT_THEME_COOKIE) {
3594
+ try {
3595
+ document.cookie = `${cookie}=${theme}; path=/; max-age=${COOKIE_MAX_AGE}; samesite=lax`;
3596
+ } catch {}
3597
+ try {
3598
+ localStorage.setItem("theme", theme);
3599
+ } catch {}
3600
+ }
3601
+ /** The stored choice in the browser: the cookie, else the legacy `localStorage` key. */
3602
+ function readStoredTheme(cookie = DEFAULT_THEME_COOKIE) {
3603
+ try {
3604
+ for (const part of document.cookie.split(";")) {
3605
+ const eq = part.indexOf("=");
3606
+ if (eq < 0 || part.slice(0, eq).trim() !== cookie) continue;
3607
+ const value = decodeURIComponent(part.slice(eq + 1).trim());
3608
+ if (isTheme(value)) return value;
3609
+ }
3610
+ } catch {}
3611
+ try {
3612
+ const value = localStorage.getItem("theme");
3613
+ if (isTheme(value)) return value;
3614
+ } catch {}
3615
+ return null;
3616
+ }
3617
+ //#endregion
3566
3618
  //#region client/ThemeProvider.tsx
3619
+ var DARK_QUERY = "(prefers-color-scheme: dark)";
3567
3620
  var ThemeContext = createContext({
3568
3621
  theme: "light",
3569
- setTheme: (theme) => {}
3622
+ resolved: "light",
3623
+ setTheme: () => {}
3570
3624
  });
3571
- function storeTheme(theme) {
3572
- try {
3573
- localStorage.setItem("theme", theme);
3574
- } catch (error) {
3575
- console.error("Failed to store theme in localStorage:", error);
3576
- }
3625
+ function initialResolved(theme) {
3626
+ return theme === "system" ? null : theme;
3577
3627
  }
3578
3628
  var ThemeProvider = (props) => {
3579
- const [theme, setTheme] = useState(() => {
3580
- if (props.theme) return props.theme;
3581
- if (typeof window === "undefined") return "light";
3582
- return localStorage.getItem("theme") || "light";
3583
- });
3629
+ const data = useContext(ServerDataContext)?.theme;
3630
+ const cookie = data?.cookie ?? "theme";
3631
+ const [theme, setThemeState] = useState(() => props.theme ?? data?.value ?? data?.default ?? "light");
3632
+ const [resolved, setResolved] = useState(() => initialResolved(theme));
3584
3633
  useEffect(() => {
3585
- if (theme === "system") window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", ({ matches }) => {
3586
- document.documentElement.classList.remove("light", "dark");
3587
- document.documentElement.classList.add(matches ? "dark" : "light");
3588
- });
3634
+ if (props.theme || data?.value) return;
3635
+ const stored = readStoredTheme(cookie);
3636
+ if (stored && stored !== theme) {
3637
+ setThemeState(stored);
3638
+ setResolved(initialResolved(stored));
3639
+ }
3640
+ }, []);
3641
+ useEffect(() => {
3642
+ if (theme !== "system" || typeof window.matchMedia !== "function") return;
3643
+ const media = window.matchMedia(DARK_QUERY);
3644
+ setResolved(resolveTheme("system", media.matches));
3645
+ const onChange = ({ matches }) => {
3646
+ const next = resolveTheme("system", matches);
3647
+ setResolved(next);
3648
+ applyTheme(document.documentElement, next);
3649
+ };
3650
+ media.addEventListener("change", onChange);
3651
+ return () => media.removeEventListener("change", onChange);
3589
3652
  }, [theme]);
3653
+ const setTheme = (next) => {
3654
+ const nextResolved = resolveTheme(next, typeof window.matchMedia === "function" && window.matchMedia(DARK_QUERY).matches);
3655
+ setThemeState(next);
3656
+ setResolved(nextResolved);
3657
+ storeTheme(next, cookie);
3658
+ applyTheme(document.documentElement, nextResolved);
3659
+ };
3590
3660
  return /* @__PURE__ */ jsx(ThemeContext.Provider, {
3591
3661
  value: {
3592
3662
  theme,
3593
- setTheme: (newTheme) => {
3594
- setTheme(newTheme);
3595
- storeTheme(newTheme);
3596
- let documentTheme = newTheme;
3597
- if (newTheme === "system") documentTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
3598
- document.documentElement.classList.remove("light", "dark");
3599
- document.documentElement.classList.add(documentTheme);
3600
- }
3663
+ resolved,
3664
+ setTheme
3601
3665
  },
3602
3666
  children: props.children
3603
3667
  });
3604
3668
  };
3669
+ /**
3670
+ * The visitor's theme: `theme` (their choice), `resolved` (`"light"` or
3671
+ * `"dark"`, `null` until `"system"` is known) and `setTheme`, which applies it
3672
+ * to `<html>` and stores it in the theme cookie the server reads.
3673
+ */
3605
3674
  function useTheme() {
3606
- const context = useContext(ThemeContext);
3607
- if (!context) throw new Error("useTheme must be used within a ThemeProvider");
3608
- return context;
3675
+ return useContext(ThemeContext);
3609
3676
  }
3610
3677
  //#endregion
3611
3678
  export { DEFAULT_STALE_TIME as $, ServerDataContext as A, followLive as B, readRoutePayload as C, useNavigate as D, useSearchParams as E, ProgressManager as F, loadedModule as G, realtime as H, Action as I, QueryConfigContext as J, toVariantKey as K, createMemoryHistory as L, useLocation as M, domainUrl as N, I18nContext as O, isAbsoluteUrl as P, pickDefined as Q, RealtimeContext as R, setActiveLocale as S, useRoute as T, reconnectRealtime as U, liveModule as V, loadLazy as W, QueryManagerProvider as X, QueryManagerContext as Y, USER_QUERY_CONFIG_KEYS as Z, isChunkLoadError as _, useRouteTransition as a, Subject as at, loadDictionaryForRender as b, ClientRouterContext as c, ComponentsProvider as d, isRetryableQueryError as et, initialViewModulesReady as f, configureChunkLoadRecovery as g, CHUNK_RELOAD_MARKER as h, RouteTransitionProvider as i, QueryError as it, ServerDataProvider as j, I18nProvider as k, ClientRouterProvider as l, subscribeViewModules as m, useTheme as n, retryDelayFor as nt, useChannelSubscription as o, loadViewModule as p, applyParams as q, m as r, shouldRetryQuery as rt, useCoalesced as s, ThemeProvider as t, parseRetryAfter as tt, ComponentsContext as u, recoverFromChunkLoadError as v, routeDataUrl as w, registerDictionary as x, loadDictionary as y, configureRealtime as z };
3612
3679
 
3613
- //# sourceMappingURL=ThemeProvider-gWqXjGh-.js.map
3680
+ //# sourceMappingURL=ThemeProvider-BwlMubvu.js.map