gemi 0.129.0 → 0.131.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 (266) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/App.d.ts +9 -0
  4. package/dist/app/App.d.ts.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/bin/gemi.js +182 -128
  7. package/dist/bin/gemi.js.map +7 -6
  8. package/dist/bun/plugin.js +1 -1
  9. package/dist/bun/preload.js +1 -1
  10. package/dist/{chunk-t7gvgz20.js → chunk-0g5f8ymy.js} +2 -2
  11. package/dist/{chunk-t7gvgz20.js.map → chunk-0g5f8ymy.js.map} +1 -1
  12. package/dist/{chunk-peng31np.js → chunk-0q68t71d.js} +3 -3
  13. package/dist/{chunk-peng31np.js.map → chunk-0q68t71d.js.map} +1 -1
  14. package/dist/{chunk-vc5kpxdk.js → chunk-2senwsdq.js} +2 -2
  15. package/dist/{chunk-vc5kpxdk.js.map → chunk-2senwsdq.js.map} +1 -1
  16. package/dist/{chunk-2869cbhd.js → chunk-2tda49mv.js} +3 -3
  17. package/dist/{chunk-2869cbhd.js.map → chunk-2tda49mv.js.map} +1 -1
  18. package/dist/{chunk-1z311hyj.js → chunk-2x0n3ze1.js} +2 -2
  19. package/dist/{chunk-1z311hyj.js.map → chunk-2x0n3ze1.js.map} +1 -1
  20. package/dist/{chunk-cp84b0ev.js → chunk-35zw2s61.js} +3 -3
  21. package/dist/{chunk-cp84b0ev.js.map → chunk-35zw2s61.js.map} +1 -1
  22. package/dist/{chunk-zw5z1k84.js → chunk-3wnczt5w.js} +3 -3
  23. package/dist/{chunk-zw5z1k84.js.map → chunk-3wnczt5w.js.map} +3 -3
  24. package/dist/{chunk-v09w6pr2.js → chunk-3xy41vc0.js} +3 -3
  25. package/dist/{chunk-v09w6pr2.js.map → chunk-3xy41vc0.js.map} +1 -1
  26. package/dist/{chunk-fezaxj28.js → chunk-47eav3ex.js} +2 -2
  27. package/dist/{chunk-fezaxj28.js.map → chunk-47eav3ex.js.map} +1 -1
  28. package/dist/{chunk-ww86zqbw.js → chunk-4gmhx2ba.js} +2 -2
  29. package/dist/{chunk-ww86zqbw.js.map → chunk-4gmhx2ba.js.map} +1 -1
  30. package/dist/{chunk-k10vbrjx.js → chunk-4wda9teq.js} +3 -3
  31. package/dist/{chunk-k10vbrjx.js.map → chunk-4wda9teq.js.map} +1 -1
  32. package/dist/{chunk-ja41ts8v.js → chunk-4z0rt6ws.js} +2 -2
  33. package/dist/{chunk-ja41ts8v.js.map → chunk-4z0rt6ws.js.map} +1 -1
  34. package/dist/{chunk-sbdm4enk.js → chunk-539w9yt3.js} +2 -2
  35. package/dist/{chunk-sbdm4enk.js.map → chunk-539w9yt3.js.map} +1 -1
  36. package/dist/{chunk-9122838b.js → chunk-58mg4rpd.js} +2 -2
  37. package/dist/{chunk-9122838b.js.map → chunk-58mg4rpd.js.map} +1 -1
  38. package/dist/{chunk-0m2fyw7g.js → chunk-63xekerg.js} +2 -2
  39. package/dist/{chunk-0m2fyw7g.js.map → chunk-63xekerg.js.map} +1 -1
  40. package/dist/{chunk-qv8sj2z3.js → chunk-65fq5a9d.js} +2 -2
  41. package/dist/{chunk-qv8sj2z3.js.map → chunk-65fq5a9d.js.map} +1 -1
  42. package/dist/{chunk-bg5qb9hm.js → chunk-65s63bdh.js} +2 -2
  43. package/dist/{chunk-bg5qb9hm.js.map → chunk-65s63bdh.js.map} +1 -1
  44. package/dist/chunk-77ymcf7q.js +4 -0
  45. package/dist/chunk-77ymcf7q.js.map +10 -0
  46. package/dist/{chunk-wn437678.js → chunk-7j48ymk1.js} +2 -2
  47. package/dist/{chunk-wn437678.js.map → chunk-7j48ymk1.js.map} +1 -1
  48. package/dist/{chunk-dak8txaw.js → chunk-7n0zn5h4.js} +2 -2
  49. package/dist/{chunk-dak8txaw.js.map → chunk-7n0zn5h4.js.map} +1 -1
  50. package/dist/{chunk-p528pvmm.js → chunk-822p54vc.js} +2 -2
  51. package/dist/{chunk-p528pvmm.js.map → chunk-822p54vc.js.map} +1 -1
  52. package/dist/{chunk-qjmcn5m5.js → chunk-838cdh6v.js} +2 -2
  53. package/dist/{chunk-qjmcn5m5.js.map → chunk-838cdh6v.js.map} +1 -1
  54. package/dist/{chunk-h55c9bdf.js → chunk-8fvt7kys.js} +1 -1
  55. package/dist/{chunk-xtnbcbkf.js → chunk-aprjvzrz.js} +2 -2
  56. package/dist/{chunk-nvfhx9d1.js.map → chunk-aprjvzrz.js.map} +1 -1
  57. package/dist/{chunk-sh39q44t.js → chunk-asmszzkp.js} +3 -3
  58. package/dist/{chunk-sh39q44t.js.map → chunk-asmszzkp.js.map} +1 -1
  59. package/dist/{chunk-nvfhx9d1.js → chunk-ayjfs5mm.js} +2 -2
  60. package/dist/{chunk-xtnbcbkf.js.map → chunk-ayjfs5mm.js.map} +1 -1
  61. package/dist/{chunk-kmcnfk2s.js → chunk-b00z33zg.js} +1 -1
  62. package/dist/{chunk-pgddb43b.js → chunk-c1gq2ttb.js} +2 -2
  63. package/dist/{chunk-pgddb43b.js.map → chunk-c1gq2ttb.js.map} +1 -1
  64. package/dist/{chunk-0vxwrc4t.js → chunk-cggywjzz.js} +2 -2
  65. package/dist/{chunk-0vxwrc4t.js.map → chunk-cggywjzz.js.map} +1 -1
  66. package/dist/{chunk-n1t4ea9g.js → chunk-d5g1caxb.js} +3 -3
  67. package/dist/{chunk-n1t4ea9g.js.map → chunk-d5g1caxb.js.map} +1 -1
  68. package/dist/{chunk-f8ce6e9c.js → chunk-dp2yz8bj.js} +2 -2
  69. package/dist/{chunk-f8ce6e9c.js.map → chunk-dp2yz8bj.js.map} +1 -1
  70. package/dist/{chunk-43vjbd6n.js → chunk-dxm5gxqk.js} +1 -1
  71. package/dist/{chunk-9701fx4z.js → chunk-dz76qhx8.js} +2 -2
  72. package/dist/{chunk-9701fx4z.js.map → chunk-dz76qhx8.js.map} +1 -1
  73. package/dist/{chunk-fv53h1q2.js → chunk-e1fhy2h5.js} +2 -2
  74. package/dist/{chunk-fv53h1q2.js.map → chunk-e1fhy2h5.js.map} +1 -1
  75. package/dist/{chunk-1yttk239.js → chunk-e4ay1vg9.js} +2 -2
  76. package/dist/{chunk-1yttk239.js.map → chunk-e4ay1vg9.js.map} +1 -1
  77. package/dist/{chunk-5nkvpc0a.js → chunk-f21v4n2v.js} +1 -1
  78. package/dist/{chunk-wv3nnq8c.js → chunk-fgtr9cds.js} +3 -3
  79. package/dist/{chunk-wv3nnq8c.js.map → chunk-fgtr9cds.js.map} +1 -1
  80. package/dist/chunk-fx7r6pdf.js +122 -0
  81. package/dist/{chunk-0ryswty9.js.map → chunk-fx7r6pdf.js.map} +9 -8
  82. package/dist/{chunk-nh9ewam0.js → chunk-fxm8fqh9.js} +1 -1
  83. package/dist/{chunk-tn3y2qkj.js → chunk-fzs7g6mc.js} +2 -2
  84. package/dist/{chunk-tn3y2qkj.js.map → chunk-fzs7g6mc.js.map} +1 -1
  85. package/dist/{chunk-1rq53cb0.js → chunk-gnaxedwh.js} +2 -2
  86. package/dist/{chunk-1rq53cb0.js.map → chunk-gnaxedwh.js.map} +1 -1
  87. package/dist/{chunk-njaxnv6c.js → chunk-h0xye69a.js} +2 -2
  88. package/dist/{chunk-njaxnv6c.js.map → chunk-h0xye69a.js.map} +1 -1
  89. package/dist/{chunk-ty5sp1ym.js → chunk-hdgbh8hn.js} +2 -2
  90. package/dist/{chunk-ty5sp1ym.js.map → chunk-hdgbh8hn.js.map} +1 -1
  91. package/dist/{chunk-jcps2gpp.js → chunk-hnf11jhc.js} +2 -2
  92. package/dist/{chunk-jcps2gpp.js.map → chunk-hnf11jhc.js.map} +1 -1
  93. package/dist/{chunk-vjpby5sf.js → chunk-hr8annr1.js} +3 -3
  94. package/dist/{chunk-vjpby5sf.js.map → chunk-hr8annr1.js.map} +1 -1
  95. package/dist/{chunk-k107vw69.js → chunk-j1wc4afr.js} +2 -2
  96. package/dist/{chunk-k107vw69.js.map → chunk-j1wc4afr.js.map} +1 -1
  97. package/dist/{chunk-2z1gd231.js → chunk-j4y0sjdc.js} +2 -2
  98. package/dist/{chunk-2z1gd231.js.map → chunk-j4y0sjdc.js.map} +1 -1
  99. package/dist/{chunk-er5ed5pg.js → chunk-jbd723h1.js} +3 -3
  100. package/dist/{chunk-er5ed5pg.js.map → chunk-jbd723h1.js.map} +1 -1
  101. package/dist/{chunk-5ym464xx.js → chunk-jd1afbrs.js} +4 -4
  102. package/dist/{chunk-5ym464xx.js.map → chunk-jd1afbrs.js.map} +1 -1
  103. package/dist/{chunk-xhm5wgfe.js → chunk-jxmc33m9.js} +2 -2
  104. package/dist/{chunk-xhm5wgfe.js.map → chunk-jxmc33m9.js.map} +1 -1
  105. package/dist/{chunk-pxsq9841.js → chunk-jxvec7jc.js} +2 -2
  106. package/dist/{chunk-pxsq9841.js.map → chunk-jxvec7jc.js.map} +1 -1
  107. package/dist/chunk-mvka90rq.js +5 -0
  108. package/dist/{chunk-pqn9j5s8.js.map → chunk-mvka90rq.js.map} +1 -1
  109. package/dist/{chunk-mc8mxx2a.js → chunk-mym7egdq.js} +2 -2
  110. package/dist/{chunk-mc8mxx2a.js.map → chunk-mym7egdq.js.map} +1 -1
  111. package/dist/{chunk-np73p641.js → chunk-mz73066c.js} +2 -2
  112. package/dist/{chunk-np73p641.js.map → chunk-mz73066c.js.map} +1 -1
  113. package/dist/{chunk-3dyd4z06.js → chunk-n7sbwpce.js} +2 -2
  114. package/dist/{chunk-3dyd4z06.js.map → chunk-n7sbwpce.js.map} +1 -1
  115. package/dist/{chunk-gpdsxwkt.js → chunk-p320fd3g.js} +2 -2
  116. package/dist/{chunk-gpdsxwkt.js.map → chunk-p320fd3g.js.map} +1 -1
  117. package/dist/{chunk-nwzsgzvy.js → chunk-p462p2xe.js} +2 -2
  118. package/dist/{chunk-nwzsgzvy.js.map → chunk-p462p2xe.js.map} +1 -1
  119. package/dist/{chunk-2bmk0fzm.js → chunk-p642ja42.js} +3 -3
  120. package/dist/{chunk-2bmk0fzm.js.map → chunk-p642ja42.js.map} +1 -1
  121. package/dist/{chunk-jj1ppnnk.js → chunk-p6b0cyf8.js} +2 -2
  122. package/dist/{chunk-jj1ppnnk.js.map → chunk-p6b0cyf8.js.map} +1 -1
  123. package/dist/{chunk-8jqve5dr.js → chunk-pahr13xg.js} +2 -2
  124. package/dist/{chunk-8jqve5dr.js.map → chunk-pahr13xg.js.map} +1 -1
  125. package/dist/{chunk-wf3qe12c.js → chunk-pzb3agv9.js} +2 -2
  126. package/dist/{chunk-wf3qe12c.js.map → chunk-pzb3agv9.js.map} +1 -1
  127. package/dist/{chunk-87rtxv9n.js → chunk-qspam5cf.js} +2 -2
  128. package/dist/{chunk-87rtxv9n.js.map → chunk-qspam5cf.js.map} +1 -1
  129. package/dist/{chunk-n4dk0dc9.js → chunk-qz89m7ss.js} +2 -2
  130. package/dist/{chunk-n4dk0dc9.js.map → chunk-qz89m7ss.js.map} +1 -1
  131. package/dist/{chunk-gzaaspe7.js → chunk-rjyw1thg.js} +2 -2
  132. package/dist/{chunk-gzaaspe7.js.map → chunk-rjyw1thg.js.map} +1 -1
  133. package/dist/{chunk-2epj17ac.js → chunk-t227jn4b.js} +2 -2
  134. package/dist/{chunk-2epj17ac.js.map → chunk-t227jn4b.js.map} +1 -1
  135. package/dist/{chunk-x92g4x4w.js → chunk-v5esvs66.js} +2 -2
  136. package/dist/{chunk-x92g4x4w.js.map → chunk-v5esvs66.js.map} +1 -1
  137. package/dist/{chunk-4yp84g2y.js → chunk-w26cw41m.js} +2 -2
  138. package/dist/{chunk-4yp84g2y.js.map → chunk-w26cw41m.js.map} +1 -1
  139. package/dist/{chunk-03wc6em7.js → chunk-x07rp3fc.js} +1 -1
  140. package/dist/{chunk-7321qjgb.js → chunk-x4yq0c9v.js} +3 -3
  141. package/dist/{chunk-7321qjgb.js.map → chunk-x4yq0c9v.js.map} +1 -1
  142. package/dist/{chunk-5bk7767a.js → chunk-xhvknqvn.js} +2 -2
  143. package/dist/{chunk-5bk7767a.js.map → chunk-xhvknqvn.js.map} +1 -1
  144. package/dist/{chunk-1gdzajwb.js → chunk-xjs72pb0.js} +2 -2
  145. package/dist/{chunk-1gdzajwb.js.map → chunk-xjs72pb0.js.map} +1 -1
  146. package/dist/{chunk-wmkrb1qv.js → chunk-y14weak4.js} +4 -4
  147. package/dist/{chunk-wmkrb1qv.js.map → chunk-y14weak4.js.map} +3 -3
  148. package/dist/{chunk-pgh7gsag.js → chunk-z1gjgr1c.js} +2 -2
  149. package/dist/{chunk-pgh7gsag.js.map → chunk-z1gjgr1c.js.map} +1 -1
  150. package/dist/{chunk-jm1f9cas.js → chunk-zc5962gh.js} +2 -2
  151. package/dist/{chunk-jm1f9cas.js.map → chunk-zc5962gh.js.map} +1 -1
  152. package/dist/{chunk-b7wmssj5.js → chunk-zzgt759n.js} +2 -2
  153. package/dist/{chunk-b7wmssj5.js.map → chunk-zzgt759n.js.map} +1 -1
  154. package/dist/chunks/MutationError-DuKqBW8o.js +199 -0
  155. package/dist/chunks/MutationError-DuKqBW8o.js.map +1 -0
  156. package/dist/chunks/{RealtimeClient-CqGve6h8.js → RealtimeClient-DsWbFRC7.js} +11 -3
  157. package/dist/chunks/RealtimeClient-DsWbFRC7.js.map +1 -0
  158. package/dist/chunks/{ThemeProvider-DaX0eyqs.js → ThemeProvider-gWqXjGh-.js} +70 -91
  159. package/dist/chunks/ThemeProvider-gWqXjGh-.js.map +1 -0
  160. package/dist/chunks/channelKey-CIhHpX6x.js +10 -0
  161. package/dist/chunks/channelKey-CIhHpX6x.js.map +1 -0
  162. package/dist/chunks/fetchFileRequest-BSrgYnAy.js +57 -0
  163. package/dist/chunks/fetchFileRequest-BSrgYnAy.js.map +1 -0
  164. package/dist/chunks/{live-DIUDdLrA.js → live-CUdMhXHL.js} +22 -3
  165. package/dist/chunks/live-CUdMhXHL.js.map +1 -0
  166. package/dist/chunks/mutationExtras-CtY-X9m7.js +115 -0
  167. package/dist/chunks/mutationExtras-CtY-X9m7.js.map +1 -0
  168. package/dist/client/MutationError.d.ts +7 -9
  169. package/dist/client/MutationError.d.ts.map +1 -1
  170. package/dist/client/QueryResource.d.ts +3 -11
  171. package/dist/client/QueryResource.d.ts.map +1 -1
  172. package/dist/client/fetchFile.d.ts +4 -7
  173. package/dist/client/fetchFile.d.ts.map +1 -1
  174. package/dist/client/fetchFileRequest.d.ts +14 -0
  175. package/dist/client/fetchFileRequest.d.ts.map +1 -0
  176. package/dist/client/index.js +88 -339
  177. package/dist/client/index.js.map +1 -1
  178. package/dist/client/lazyModule.d.ts +32 -0
  179. package/dist/client/lazyModule.d.ts.map +1 -0
  180. package/dist/client/mutationErrorHelpers.d.ts +11 -0
  181. package/dist/client/mutationErrorHelpers.d.ts.map +1 -0
  182. package/dist/client/mutationExtras.d.ts +3 -0
  183. package/dist/client/mutationExtras.d.ts.map +1 -0
  184. package/dist/client/mutationModules.d.ts +17 -0
  185. package/dist/client/mutationModules.d.ts.map +1 -0
  186. package/dist/client/queryUpdates.d.ts +22 -0
  187. package/dist/client/queryUpdates.d.ts.map +1 -0
  188. package/dist/client/realtime/RealtimeClient.d.ts +5 -0
  189. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
  190. package/dist/client/realtime/channelKey.d.ts +4 -0
  191. package/dist/client/realtime/channelKey.d.ts.map +1 -0
  192. package/dist/client/realtime/live.d.ts +6 -0
  193. package/dist/client/realtime/live.d.ts.map +1 -1
  194. package/dist/client/realtime/loader.d.ts +20 -23
  195. package/dist/client/realtime/loader.d.ts.map +1 -1
  196. package/dist/client/realtime/useChannelSubscription.d.ts.map +1 -1
  197. package/dist/client/useMutation.d.ts +1 -1
  198. package/dist/client/useMutation.d.ts.map +1 -1
  199. package/dist/client/useSetQueryData.d.ts +4 -17
  200. package/dist/client/useSetQueryData.d.ts.map +1 -1
  201. package/dist/config/index.js +1 -1
  202. package/dist/console/run.js +2 -2
  203. package/dist/console/run.js.map +1 -1
  204. package/dist/container/index.js +2 -2
  205. package/dist/container/index.js.map +1 -1
  206. package/dist/database/index.js +2 -2
  207. package/dist/database/index.js.map +1 -1
  208. package/dist/email/index.js +2 -2
  209. package/dist/email/index.js.map +1 -1
  210. package/dist/facades/index.js +2 -2
  211. package/dist/facades/index.js.map +1 -1
  212. package/dist/foundation/index.js +2 -2
  213. package/dist/foundation/index.js.map +1 -1
  214. package/dist/http/ViewRouter.d.ts +17 -0
  215. package/dist/http/ViewRouter.d.ts.map +1 -1
  216. package/dist/http/index.js +2 -2
  217. package/dist/http/index.js.map +1 -1
  218. package/dist/i18n/dictionaryRuntime.js +2 -2
  219. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  220. package/dist/i18n/index.js +2 -2
  221. package/dist/i18n/index.js.map +1 -1
  222. package/dist/kernel/index.js +2 -2
  223. package/dist/kernel/index.js.map +1 -1
  224. package/dist/orm/index.js +2 -2
  225. package/dist/orm/index.js.map +1 -1
  226. package/dist/server/httpDev.d.ts.map +1 -1
  227. package/dist/server/httpProd.d.ts.map +1 -1
  228. package/dist/server/index.js +2 -2
  229. package/dist/server/index.js.map +1 -1
  230. package/dist/services/index.d.ts +1 -0
  231. package/dist/services/index.d.ts.map +1 -1
  232. package/dist/services/index.js +3 -3
  233. package/dist/services/index.js.map +2 -2
  234. package/dist/services/queue/work.js +2 -2
  235. package/dist/services/queue/work.js.map +1 -1
  236. package/dist/services/router/DomainResolver.d.ts +12 -0
  237. package/dist/services/router/DomainResolver.d.ts.map +1 -1
  238. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  239. package/dist/services/router/config.d.ts +21 -5
  240. package/dist/services/router/config.d.ts.map +1 -1
  241. package/dist/services/router/documentScript.d.ts +46 -0
  242. package/dist/services/router/documentScript.d.ts.map +1 -0
  243. package/dist/services/router/staticDocument.d.ts +11 -1
  244. package/dist/services/router/staticDocument.d.ts.map +1 -1
  245. package/dist/stats/route-table.js +1 -1
  246. package/dist/support/index.js +2 -2
  247. package/dist/support/index.js.map +1 -1
  248. package/dist/testing/index.js +8 -5
  249. package/dist/testing/index.js.map +1 -1
  250. package/dist/testing/staticDocument.d.ts +8 -2
  251. package/dist/testing/staticDocument.d.ts.map +1 -1
  252. package/dist/vitest/index.js +1 -1
  253. package/package.json +1 -1
  254. package/dist/chunk-0ryswty9.js +0 -120
  255. package/dist/chunk-bnp6wpzd.js +0 -4
  256. package/dist/chunk-bnp6wpzd.js.map +0 -10
  257. package/dist/chunk-pqn9j5s8.js +0 -5
  258. package/dist/chunks/RealtimeClient-CqGve6h8.js.map +0 -1
  259. package/dist/chunks/ThemeProvider-DaX0eyqs.js.map +0 -1
  260. package/dist/chunks/live-DIUDdLrA.js.map +0 -1
  261. /package/dist/{chunk-h55c9bdf.js.map → chunk-8fvt7kys.js.map} +0 -0
  262. /package/dist/{chunk-kmcnfk2s.js.map → chunk-b00z33zg.js.map} +0 -0
  263. /package/dist/{chunk-43vjbd6n.js.map → chunk-dxm5gxqk.js.map} +0 -0
  264. /package/dist/{chunk-5nkvpc0a.js.map → chunk-f21v4n2v.js.map} +0 -0
  265. /package/dist/{chunk-nh9ewam0.js.map → chunk-fxm8fqh9.js.map} +0 -0
  266. /package/dist/{chunk-03wc6em7.js.map → chunk-x07rp3fc.js.map} +0 -0
@@ -0,0 +1,199 @@
1
+ //#region http/refusal.ts
2
+ /**
3
+ * The kind a status stands for, for a refusal that does not name one: an app's
4
+ * own `RequestBreakerError`, or an older server's `{ message }`. Any other 4xx
5
+ * is a `form_error`, a message about this request for `<FormError>` to show.
6
+ */
7
+ function refusalKindForStatus(status) {
8
+ if (status === 401) return "authentication";
9
+ if (status === 403) return "permission";
10
+ if (status === 404) return "not_found";
11
+ if (status === 416) return "range_not_satisfiable";
12
+ if (status === 429) return "rate_limit";
13
+ if (status >= 500) return "server_error";
14
+ return "form_error";
15
+ }
16
+ //#endregion
17
+ //#region client/MutationError.ts
18
+ var LEGACY_MESSAGES = {
19
+ "Authentication error": "authentication",
20
+ "Not authorized": "authorization",
21
+ "Insufficient permissions": "permission",
22
+ "Invalid CSRF token": "csrf",
23
+ "Internal Server Error": "server_error",
24
+ Forbidden: "permission",
25
+ "Not found": "not_found",
26
+ "Rate limit exceeded": "rate_limit"
27
+ };
28
+ /** @internal */
29
+ function isObject(error) {
30
+ return typeof error === "object" && error !== null;
31
+ }
32
+ function legacyKind(message, status) {
33
+ return LEGACY_MESSAGES[message] ?? (status === 401 ? "authorization" : refusalKindForStatus(status));
34
+ }
35
+ /**
36
+ * The `MutationError` a non-2xx response's parsed body stands for.
37
+ *
38
+ * gemi's own error bodies are `{ error }`, and the value under `error` is what
39
+ * is handed over. An app's body without one —
40
+ * `HttpResponse.json({ message: "Taken" }, { status: 409 })` — is handed over
41
+ * whole. A body with no content (`null`) becomes a refusal naming the status.
42
+ *
43
+ * What is handed over carries `status`, and a `kind` when it has a `message`:
44
+ * a bare string, which servers before 0.88 sent for most refusals, becomes
45
+ * `{ kind, message, status }`, and so does a `{ message }` without a kind.
46
+ *
47
+ * @internal
48
+ */
49
+ function mutationErrorFromBody(body, status) {
50
+ const error = isObject(body) && "error" in body && body.error != null ? body.error : body;
51
+ if (error == null) return {
52
+ kind: refusalKindForStatus(status),
53
+ message: `Request failed with status ${status}`,
54
+ status
55
+ };
56
+ if (typeof error === "string") return {
57
+ kind: legacyKind(error, status),
58
+ message: error,
59
+ status
60
+ };
61
+ if (!isObject(error) || error instanceof Error) return error;
62
+ const withStatus = {
63
+ ...error,
64
+ status: typeof error.status === "number" ? error.status : status
65
+ };
66
+ if (typeof error.kind !== "string" && typeof error.message === "string") return {
67
+ ...withStatus,
68
+ kind: refusalKindForStatus(withStatus.status)
69
+ };
70
+ return withStatus;
71
+ }
72
+ function kindOf(error) {
73
+ if (typeof error === "string") return LEGACY_MESSAGES[error];
74
+ if (!isObject(error) || error instanceof Error) return void 0;
75
+ if (typeof error.kind === "string") return error.kind;
76
+ if (typeof error.status === "number") return refusalKindForStatus(error.status);
77
+ return typeof error.message === "string" ? LEGACY_MESSAGES[error.message] : void 0;
78
+ }
79
+ /** Field messages, as `<ValidationErrors>` renders them. */
80
+ function isValidationError(error) {
81
+ return isObject(error) && error.kind === "validation_error";
82
+ }
83
+ /** A form-level message, as `<FormError>` renders it. */
84
+ function isFormError(error) {
85
+ return isObject(error) && error.kind === "form_error";
86
+ }
87
+ /** No signed-in user: `AuthenticationError` (401). */
88
+ function isAuthenticationError(error) {
89
+ return kindOf(error) === "authentication";
90
+ }
91
+ /**
92
+ * A signed-in user who may not do this: `InsufficientPermissionsError` (403),
93
+ * `AuthorizationError` (401) or a policy denial (403), whatever message it was
94
+ * thrown with.
95
+ */
96
+ function isPermissionError(error) {
97
+ const kind = kindOf(error);
98
+ return kind === "permission" || kind === "authorization";
99
+ }
100
+ /** The CSRF cookie is missing or stale (403). A reload fixes it. */
101
+ function isCsrfError(error) {
102
+ return kindOf(error) === "csrf";
103
+ }
104
+ /** A missing record, file or route (404). */
105
+ function isNotFoundError(error) {
106
+ return kindOf(error) === "not_found";
107
+ }
108
+ /**
109
+ * `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429).
110
+ * `retryAfter` (ms) says when to try again, when the server sent it.
111
+ */
112
+ function isRateLimitError(error) {
113
+ return kindOf(error) === "rate_limit";
114
+ }
115
+ /**
116
+ * The server failed (a 500, under `gemi dev` too), or answered something that
117
+ * is not JSON.
118
+ */
119
+ function isServerError(error) {
120
+ return kindOf(error) === "server_error" || error instanceof SyntaxError;
121
+ }
122
+ /** The request got no answer: offline, DNS, CORS, a dropped connection. */
123
+ function isNetworkError(error) {
124
+ return error instanceof TypeError;
125
+ }
126
+ /**
127
+ * Which of the guards above `error` passes, for a `switch` over all of them.
128
+ * `"unknown"` is everything else: a 416, an error body of the app's own shape.
129
+ */
130
+ function mutationErrorKind(error) {
131
+ if (isValidationError(error)) return "validation";
132
+ if (isFormError(error)) return "form";
133
+ if (isAuthenticationError(error)) return "authentication";
134
+ if (isPermissionError(error)) return "permission";
135
+ if (isCsrfError(error)) return "csrf";
136
+ if (isNotFoundError(error)) return "not_found";
137
+ if (isRateLimitError(error)) return "rate_limit";
138
+ if (isServerError(error)) return "server";
139
+ if (isNetworkError(error)) return "network";
140
+ return "unknown";
141
+ }
142
+ /**
143
+ * An error answered with `status`: a route's typed error from
144
+ * `HttpResponse.error(status, body)` / `httpError`, narrowed to the members
145
+ * of `error`'s type with that status.
146
+ *
147
+ * ```ts
148
+ * onError: (error) => {
149
+ * if (isHttpError(error, 410)) toast(error.message);
150
+ * }
151
+ * ```
152
+ *
153
+ * At run time it checks the status alone, so gemi's own refusals with the
154
+ * same status (a 404 `not_found`, a 429 `rate_limit`) pass it too; pick a
155
+ * status gemi does not use for its own errors, or check `kind` after it.
156
+ */
157
+ function isHttpError(error, status) {
158
+ return isObject(error) && !(error instanceof Error) && error.status === status;
159
+ }
160
+ var FALLBACK_MESSAGE = "Something went wrong. Try again.";
161
+ function unwrapQueryError(error) {
162
+ if (error instanceof Error && error.name === "QueryError" && "body" in error) {
163
+ const { body, status } = error;
164
+ return body == null ? error : mutationErrorFromBody(body, status);
165
+ }
166
+ return error;
167
+ }
168
+ /**
169
+ * `error.list(fallback)` for any value: an error kept from a mutation, a
170
+ * `useQuery` `QueryError` (its body is read), or anything else.
171
+ *
172
+ * Kept in step with `list` in `./mutationErrorHelpers`, which the mutation
173
+ * hooks load on first use (#915) and so cannot share this code: an app's
174
+ * bundler would put it back in the entry chunk. `MutationError.helpers.test`
175
+ * runs the same cases through both.
176
+ */
177
+ function mutationErrorList(error, fallback = FALLBACK_MESSAGE) {
178
+ const value = unwrapQueryError(error);
179
+ if (isValidationError(value)) {
180
+ const messages = Object.values(value.messages ?? {}).flat().filter((message) => typeof message === "string" && message !== "");
181
+ return messages.length > 0 ? messages : [fallback];
182
+ }
183
+ if (isObject(value) && !(value instanceof Error) && value.kind !== "server_error" && typeof value.message === "string" && value.message !== "") return [value.message];
184
+ return [fallback];
185
+ }
186
+ /**
187
+ * `error.field(name)` for any value: a validation error's messages for
188
+ * `name` (a `QueryError`'s body is read), `[]` for anything else.
189
+ */
190
+ function mutationErrorField(error, name) {
191
+ const value = unwrapQueryError(error);
192
+ if (!isValidationError(value)) return [];
193
+ const messages = value.messages?.[name];
194
+ return Array.isArray(messages) ? [...messages] : [];
195
+ }
196
+ //#endregion
197
+ export { isNetworkError as a, isPermissionError as c, isValidationError as d, mutationErrorField as f, mutationErrorList as h, isHttpError as i, isRateLimitError as l, mutationErrorKind as m, isCsrfError as n, isNotFoundError as o, mutationErrorFromBody as p, isFormError as r, isObject as s, isAuthenticationError as t, isServerError as u };
198
+
199
+ //# sourceMappingURL=MutationError-DuKqBW8o.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MutationError-DuKqBW8o.js","names":[],"sources":["../../http/refusal.ts","../../client/MutationError.ts"],"sourcesContent":["/**\n * The shape of a refusal on the wire: the `error` field of a non-2xx `/api`\n * answer, for every refusal gemi sends.\n *\n * It was a bare string for most of them (`\"Not authorized\"`, `\"Invalid CSRF\n * token\"`, a 500's message) and `{ message }` for the rest. A string carries no\n * status, so a client could only classify the framework's default messages: an\n * `AuthorizationError` thrown with a message of its own, the rule the skill\n * teaches, was `\"unknown\"`, and apps compared strings (issue #673).\n *\n * Shared by the server, which builds it, and the client, which reads it and\n * wraps an older server's bare strings into it, so this module imports nothing.\n */\n\n/**\n * Which refusal this is. `validation_error` and `form_error` predate the rest\n * and keep their spelling, and `server_error` is the kind `useUpload` already\n * reported for a failed upload, so a 500 has one name wherever it comes from.\n */\nexport type RefusalKind =\n /** No signed-in user: `AuthenticationError` (401). */\n | \"authentication\"\n /** `AuthorizationError` (401): a known user refused this action. */\n | \"authorization\"\n /** `InsufficientPermissionsError` (403) or a policy denial (403). */\n | \"permission\"\n /** `InvalidCSRFTokenError` (403): the CSRF cookie is missing or stale. */\n | \"csrf\"\n /** A missing record, file or route (404). */\n | \"not_found\"\n /** A `Range` the object cannot satisfy (416). */\n | \"range_not_satisfiable\"\n /** `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429). */\n | \"rate_limit\"\n /** An unhandled exception (500). */\n | \"server_error\"\n /** A single form-level message, which `<FormError>` renders. */\n | \"form_error\"\n /** `ValidationError` (400). Carries `messages` instead of `message`. */\n | \"validation_error\";\n\n/** A refusal's `error`, apart from `validation_error`, which has `messages`. */\nexport type Refusal<K extends RefusalKind = Exclude<RefusalKind, \"validation_error\">> = {\n kind: K;\n message: string;\n status: number;\n /**\n * `rate_limit` only: milliseconds until a retry can succeed, when the\n * limiter knew (the `rate-limit` middleware, `RateLimiter.enforce`).\n */\n retryAfter?: number;\n};\n\n/**\n * The kind a status stands for, for a refusal that does not name one: an app's\n * own `RequestBreakerError`, or an older server's `{ message }`. Any other 4xx\n * is a `form_error`, a message about this request for `<FormError>` to show.\n */\nexport function refusalKindForStatus(status: number): Exclude<RefusalKind, \"validation_error\"> {\n if (status === 401) return \"authentication\";\n if (status === 403) return \"permission\";\n if (status === 404) return \"not_found\";\n if (status === 416) return \"range_not_satisfiable\";\n if (status === 429) return \"rate_limit\";\n if (status >= 500) return \"server_error\";\n return \"form_error\";\n}\n","import { refusalKindForStatus, type RefusalKind } from \"../http/refusal\";\n\n/**\n * What a failed mutation hands `onError` and puts in `error` — `useMutation`\n * and its `usePost`/`usePut`/`usePatch`/`useDelete` shorthands, `useUpload`,\n * and `<Form onError>`.\n *\n * It was typed `any` on `<Form>` and on the hooks' `error`, and as a union of\n * `kind`s the server never sent (`not_authorized`, `insufficient_permissions`)\n * on the hooks' `onError`. Apps sniffed the shape themselves, and got it wrong\n * as easily as right. This is the shape the framework actually produces,\n * member by member, read off the server's error payloads and the client's\n * fetch code (issue #626).\n *\n * Since 0.88 every refusal is an object with a `kind`, its `message` and the\n * `status` it came with (issue #673). Most refusals were a bare string before,\n * which carried no status, so a refusal thrown with a message of its own could\n * not be told apart from any other string. A server older than 0.85 still sends\n * those strings; the client wraps them into the same object, so the guards and\n * `error.message` work against either.\n */\n\n/** A server-side `ValidationError` (400): messages keyed by field. */\nexport interface MutationValidationError {\n kind: \"validation_error\";\n messages: Record<string, string[]>;\n status?: number;\n}\n\n/**\n * A single form-level message, which `<FormError>` renders: a\n * `RequestBreakerError` of the app's own, or any other 4xx that answered a\n * message without a kind of its own.\n */\nexport interface MutationFormError {\n kind: \"form_error\";\n message: string;\n status?: number;\n}\n\n/**\n * The server failed: an unhandled exception (500; under `gemi dev` the message\n * is the exception's), or a failed `useUpload` whose body was not JSON.\n */\nexport interface MutationServerError {\n kind: \"server_error\";\n message: string;\n status?: number;\n}\n\n/** The refusals other than the three above. */\nexport type MutationRefusalKind = Exclude<\n RefusalKind,\n \"validation_error\" | \"form_error\" | \"server_error\"\n>;\n\n/**\n * A refusal: `authentication` (401), `authorization` (`AuthorizationError`,\n * 401), `permission` (`InsufficientPermissionsError` or a policy, 403), `csrf`\n * (403), `not_found` (404), `range_not_satisfiable` (416) or `rate_limit`\n * (429). `message` is the one it was thrown with.\n */\nexport interface MutationRefusal<K extends MutationRefusalKind = MutationRefusalKind> {\n kind: K;\n message: string;\n status: number;\n /**\n * `rate_limit` only: milliseconds until a retry can succeed, when the\n * server's limiter knew (the `rate-limit` middleware, `RateLimiter.enforce`).\n */\n retryAfter?: number;\n}\n\n/**\n * @deprecated A `{ message }` body is wrapped into a `MutationRefusal` or\n * `MutationFormError` since 0.88, and `MutationError` no longer includes this.\n */\nexport interface MutationMessageError {\n kind?: undefined;\n message: string;\n}\n\n/**\n * Every value `onError` receives and `error` holds for a request gemi's server\n * answered, or failed to reach:\n *\n * - `MutationValidationError`, `MutationFormError`, `MutationServerError`,\n * `MutationRefusal` — tagged with `kind`, and (from the server) `status`.\n * - `Error` — raised in the browser: a `TypeError` when the request never got\n * an answer (offline, DNS, CORS), a `SyntaxError` when the answer was not\n * JSON (a proxy's HTML error page, say). A throw from an `onSuccess` of\n * yours is reported through `onError` as well, as whatever it threw.\n *\n * Never a string since 0.88. A cancelled request is not an error: `onCanceled`\n * runs and `error` stays `null`. A route's typed errors — the bodies its\n * handler answers with `HttpResponse.error(status, body)` / `httpError` — are\n * added to this union on its hooks and `<Form>` (`MutationError | E`). Any\n * other error body of the route's own shape is outside this type: a body with an `error` field\n * (`HttpResponse.json({ error }, { status: 409 })`) hands over that field, as\n * gemi's own errors do, and any other body is handed over whole. Either is\n * given a `kind` (from the status) and the `status` when it is an object with\n * a string `message` and no `kind`, and becomes one when it is a string.\n */\nexport type MutationError =\n | MutationValidationError\n | MutationFormError\n | MutationServerError\n | MutationRefusal\n | Error;\n\n/** What `mutationErrorKind` answers, one per guard below. */\nexport type MutationErrorKind =\n | \"validation\"\n | \"form\"\n | \"authentication\"\n | \"permission\"\n | \"csrf\"\n | \"not_found\"\n | \"rate_limit\"\n | \"server\"\n | \"network\"\n | \"unknown\";\n\n// What a server before 0.88 sent: the framework's own messages, as bare\n// strings, or as `{ message }`. Read so a client on 0.85 classifies an older\n// server's refusals during a rolling deploy. Remove in 0.86.\nconst LEGACY_MESSAGES: Record<string, RefusalKind> = {\n \"Authentication error\": \"authentication\",\n \"Not authorized\": \"authorization\",\n \"Insufficient permissions\": \"permission\",\n \"Invalid CSRF token\": \"csrf\",\n \"Internal Server Error\": \"server_error\",\n Forbidden: \"permission\",\n \"Not found\": \"not_found\",\n \"Rate limit exceeded\": \"rate_limit\",\n};\n\n/** @internal */\nexport function isObject(error: unknown): error is Record<string, unknown> {\n return typeof error === \"object\" && error !== null;\n}\n\n// A bare string from a server before 0.88. Its own message names the kind when\n// it is one of the framework's; otherwise the status does, and a 401 with a\n// message of its own can only be an `AuthorizationError` — an\n// `AuthenticationError` always says \"Authentication error\".\nfunction legacyKind(message: string, status: number): RefusalKind {\n return (\n LEGACY_MESSAGES[message] ?? (status === 401 ? \"authorization\" : refusalKindForStatus(status))\n );\n}\n\n/**\n * The `MutationError` a non-2xx response's parsed body stands for.\n *\n * gemi's own error bodies are `{ error }`, and the value under `error` is what\n * is handed over. An app's body without one —\n * `HttpResponse.json({ message: \"Taken\" }, { status: 409 })` — is handed over\n * whole. A body with no content (`null`) becomes a refusal naming the status.\n *\n * What is handed over carries `status`, and a `kind` when it has a `message`:\n * a bare string, which servers before 0.88 sent for most refusals, becomes\n * `{ kind, message, status }`, and so does a `{ message }` without a kind.\n *\n * @internal\n */\nexport function mutationErrorFromBody(body: unknown, status: number): MutationError {\n const error = isObject(body) && \"error\" in body && body.error != null ? body.error : body;\n if (error == null) {\n return {\n kind: refusalKindForStatus(status),\n message: `Request failed with status ${status}`,\n status,\n } as MutationError;\n }\n if (typeof error === \"string\") {\n return { kind: legacyKind(error, status), message: error, status } as MutationError;\n }\n if (!isObject(error) || error instanceof Error) {\n return error as MutationError;\n }\n const withStatus = { ...error, status: typeof error.status === \"number\" ? error.status : status };\n if (typeof error.kind !== \"string\" && typeof error.message === \"string\") {\n return {\n ...withStatus,\n // The status alone places an older server's `{ message }` bodies (403\n // \"Forbidden\", 404, 429), and it is what an app's own body means.\n kind: refusalKindForStatus(withStatus.status),\n } as MutationError;\n }\n return withStatus as MutationError;\n}\n\n// The kind a value stands for: its `kind`; else, for an object that has none,\n// its `status`; else one of the framework's old messages, as a bare string or\n// `{ message }`, for a body handed to a guard straight off an older server.\nfunction kindOf(error: unknown): string | undefined {\n if (typeof error === \"string\") return LEGACY_MESSAGES[error];\n if (!isObject(error) || error instanceof Error) return undefined;\n if (typeof error.kind === \"string\") return error.kind;\n if (typeof error.status === \"number\") return refusalKindForStatus(error.status);\n return typeof error.message === \"string\" ? LEGACY_MESSAGES[error.message] : undefined;\n}\n\n// The guards read `kind`, falling back to `status`, and accept the bare\n// strings and `{ message }` bodies of a server before 0.88 for one minor. What\n// the hooks hand over is already wrapped, so those fallbacks only matter for a\n// body passed in by hand.\n\n/** Field messages, as `<ValidationErrors>` renders them. */\nexport function isValidationError(\n error: unknown,\n): error is MutationValidationError {\n return isObject(error) && error.kind === \"validation_error\";\n}\n\n/** A form-level message, as `<FormError>` renders it. */\nexport function isFormError(error: unknown): error is MutationFormError {\n return isObject(error) && error.kind === \"form_error\";\n}\n\n/** No signed-in user: `AuthenticationError` (401). */\nexport function isAuthenticationError(\n error: unknown,\n): error is MutationRefusal<\"authentication\"> {\n return kindOf(error) === \"authentication\";\n}\n\n/**\n * A signed-in user who may not do this: `InsufficientPermissionsError` (403),\n * `AuthorizationError` (401) or a policy denial (403), whatever message it was\n * thrown with.\n */\nexport function isPermissionError(\n error: unknown,\n): error is MutationRefusal<\"permission\" | \"authorization\"> {\n const kind = kindOf(error);\n return kind === \"permission\" || kind === \"authorization\";\n}\n\n/** The CSRF cookie is missing or stale (403). A reload fixes it. */\nexport function isCsrfError(error: unknown): error is MutationRefusal<\"csrf\"> {\n return kindOf(error) === \"csrf\";\n}\n\n/** A missing record, file or route (404). */\nexport function isNotFoundError(\n error: unknown,\n): error is MutationRefusal<\"not_found\"> {\n return kindOf(error) === \"not_found\";\n}\n\n/**\n * `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429).\n * `retryAfter` (ms) says when to try again, when the server sent it.\n */\nexport function isRateLimitError(\n error: unknown,\n): error is MutationRefusal<\"rate_limit\"> {\n return kindOf(error) === \"rate_limit\";\n}\n\n/**\n * The server failed (a 500, under `gemi dev` too), or answered something that\n * is not JSON.\n */\nexport function isServerError(\n error: unknown,\n): error is MutationServerError | SyntaxError {\n return kindOf(error) === \"server_error\" || error instanceof SyntaxError;\n}\n\n/** The request got no answer: offline, DNS, CORS, a dropped connection. */\nexport function isNetworkError(error: unknown): error is TypeError {\n return error instanceof TypeError;\n}\n\n/**\n * Which of the guards above `error` passes, for a `switch` over all of them.\n * `\"unknown\"` is everything else: a 416, an error body of the app's own shape.\n */\nexport function mutationErrorKind(error: unknown): MutationErrorKind {\n if (isValidationError(error)) return \"validation\";\n if (isFormError(error)) return \"form\";\n if (isAuthenticationError(error)) return \"authentication\";\n if (isPermissionError(error)) return \"permission\";\n if (isCsrfError(error)) return \"csrf\";\n if (isNotFoundError(error)) return \"not_found\";\n if (isRateLimitError(error)) return \"rate_limit\";\n if (isServerError(error)) return \"server\";\n if (isNetworkError(error)) return \"network\";\n return \"unknown\";\n}\n\n/**\n * The members of `E` answered with status `S`. When none of them names it — an\n * `unknown`, or a `MutationError` alone — `E` with that status, rather than\n * `never`.\n */\nexport type HttpErrorWithStatus<E, S extends number> = [Extract<E, { status: S }>] extends [never]\n ? E & { status: S }\n : Extract<E, { status: S }>;\n\n/**\n * An error answered with `status`: a route's typed error from\n * `HttpResponse.error(status, body)` / `httpError`, narrowed to the members\n * of `error`'s type with that status.\n *\n * ```ts\n * onError: (error) => {\n * if (isHttpError(error, 410)) toast(error.message);\n * }\n * ```\n *\n * At run time it checks the status alone, so gemi's own refusals with the\n * same status (a 404 `not_found`, a 429 `rate_limit`) pass it too; pick a\n * status gemi does not use for its own errors, or check `kind` after it.\n */\nexport function isHttpError<E, S extends number>(\n error: E,\n status: S,\n): error is HttpErrorWithStatus<E, S> {\n return isObject(error) && !(error instanceof Error) && error.status === status;\n}\n\n/**\n * What every error the mutation hooks hand over carries (issue #890): the\n * messages to show a person, without flattening `messages` by hand.\n */\nexport interface MutationErrorHelpers {\n /**\n * The failure in words, as a flat list that is never empty: a validation\n * error's messages, every field's in the order the server sent them; the\n * `message` of any other error the server meant for a person (a form error,\n * a refusal, a route's typed error); else `[fallback]` — for a server error,\n * whose message is an exception's under `gemi dev`, and for the browser's\n * own errors (no answer, an answer that was not JSON).\n *\n * `fallback` defaults to `\"Something went wrong. Try again.\"`.\n */\n list(fallback?: string): string[];\n /** A validation error's messages for the field `name`; `[]` otherwise. */\n field(name: string): string[];\n}\n\n/**\n * `T` with the helpers, member by member. A member that has a `list` or\n * `field` of its own — a route's typed error body with a `field` key — keeps\n * it, and does not get that helper.\n */\nexport type WithMutationErrorHelpers<T> = T extends object\n ? T & Omit<MutationErrorHelpers, keyof T>\n : T;\n\nconst FALLBACK_MESSAGE = \"Something went wrong. Try again.\";\n\n// A `QueryError`'s refusal, read as the mutation hooks read a body. Read by\n// shape, not `instanceof`, so a copy of the class from another bundle works.\nfunction unwrapQueryError(error: unknown): unknown {\n if (error instanceof Error && error.name === \"QueryError\" && \"body\" in error) {\n const { body, status } = error as Error & { body: unknown; status: number };\n return body == null ? error : mutationErrorFromBody(body, status);\n }\n return error;\n}\n\n/**\n * `error.list(fallback)` for any value: an error kept from a mutation, a\n * `useQuery` `QueryError` (its body is read), or anything else.\n *\n * Kept in step with `list` in `./mutationErrorHelpers`, which the mutation\n * hooks load on first use (#915) and so cannot share this code: an app's\n * bundler would put it back in the entry chunk. `MutationError.helpers.test`\n * runs the same cases through both.\n */\nexport function mutationErrorList(\n error: unknown,\n fallback: string = FALLBACK_MESSAGE,\n): string[] {\n const value = unwrapQueryError(error);\n if (isValidationError(value)) {\n const messages = Object.values(value.messages ?? {})\n .flat()\n .filter((message) => typeof message === \"string\" && message !== \"\");\n return messages.length > 0 ? messages : [fallback];\n }\n if (\n isObject(value) &&\n !(value instanceof Error) &&\n value.kind !== \"server_error\" &&\n typeof value.message === \"string\" &&\n value.message !== \"\"\n ) {\n return [value.message];\n }\n return [fallback];\n}\n\n/**\n * `error.field(name)` for any value: a validation error's messages for\n * `name` (a `QueryError`'s body is read), `[]` for anything else.\n */\nexport function mutationErrorField(error: unknown, name: string): string[] {\n const value = unwrapQueryError(error);\n if (!isValidationError(value)) return [];\n const messages = value.messages?.[name];\n return Array.isArray(messages) ? [...messages] : [];\n}\n"],"mappings":";;;;;;AA0DA,SAAgB,qBAAqB,QAA0D;CAC7F,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,UAAU,KAAK,OAAO;CAC1B,OAAO;AACT;;;AC4DA,IAAM,kBAA+C;CACnD,wBAAwB;CACxB,kBAAkB;CAClB,4BAA4B;CAC5B,sBAAsB;CACtB,yBAAyB;CACzB,WAAW;CACX,aAAa;CACb,uBAAuB;AACzB;;AAGA,SAAg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B,kBACd,OACA,WAAmB,kBACT;CACV,MAAM,QAAQ,iBAAiB,KAAK;CACpC,IAAI,kBAAkB,KAAK,GAAG;EAC5B,MAAM,WAAW,OAAO,OAAO,MAAM,YAAY,CAAC,CAAC,CAAC,CACjD,KAAK,CAAC,CACN,QAAQ,YAAY,OAAO,YAAY,YAAY,YAAY,EAAE;EACpE,OAAO,SAAS,SAAS,IAAI,WAAW,CAAC,QAAQ;CACnD;CACA,IACE,SAAS,KAAK,KACd,EAAE,iBAAiB,UACnB,MAAM,SAAS,kBACf,OAAO,MAAM,YAAY,YACzB,MAAM,YAAY,IAElB,OAAO,CAAC,MAAM,OAAO;CAEvB,OAAO,CAAC,QAAQ;AAClB;;;;;AAMA,SAAgB,mBAAmB,OAAgB,MAAwB;CACzE,MAAM,QAAQ,iBAAiB,KAAK;CACpC,IAAI,CAAC,kBAAkB,KAAK,GAAG,OAAO,CAAC;CACvC,MAAM,WAAW,MAAM,WAAW;CAClC,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,IAAI,CAAC;AACpD"}
@@ -1,4 +1,5 @@
1
- import { z as channelKey } from "./ThemeProvider-DaX0eyqs.js";
1
+ import { H as realtime } from "./ThemeProvider-gWqXjGh-.js";
2
+ import { t as channelKey } from "./channelKey-CIhHpX6x.js";
2
3
  //#region services/broadcast/protocol.ts
3
4
  /**
4
5
  * The `gemi.v1` WebSocket protocol, shared by the server transport
@@ -539,7 +540,14 @@ function reportListenerError(error) {
539
540
  throw error;
540
541
  });
541
542
  }
543
+ /**
544
+ * The tab's client, created on first use with the options `configureRealtime`
545
+ * set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.
546
+ */
547
+ function tabClient() {
548
+ return realtime.client ??= new RealtimeClient(realtime.options);
549
+ }
542
550
  //#endregion
543
- export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay };
551
+ export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay, tabClient };
544
552
 
545
- //# sourceMappingURL=RealtimeClient-CqGve6h8.js.map
553
+ //# sourceMappingURL=RealtimeClient-DsWbFRC7.js.map
@@ -0,0 +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,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AK,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"}
@@ -178,18 +178,7 @@ var QueryResource = class {
178
178
  const current = store.get(variantKey);
179
179
  if (current?.loading) continue;
180
180
  if (current?.hasData && current.data === data) continue;
181
- store.set(variantKey, {
182
- loading: false,
183
- data,
184
- hasData: true,
185
- error: null,
186
- version: now
187
- });
188
- this.staleVariants.delete(variantKey);
189
- this.lastFetchRecord.set(variantKey, now);
190
- this.failures.delete(variantKey);
191
- this.cancelRetry(variantKey);
192
- this.settle(variantKey);
181
+ this.fill(store, variantKey, data, now);
193
182
  changed = true;
194
183
  }
195
184
  if (changed) this.store.next(store);
@@ -463,30 +452,18 @@ var QueryResource = class {
463
452
  }));
464
453
  this.resolveVariant(variantKey, false, false);
465
454
  }
466
- /**
467
- * Write data the server just produced (a mutation's answer) into a
468
- * variant, with no refetch: unlike `mutate`, the value is not a guess to
469
- * reconcile. The variant counts as freshly fetched, so its `staleTime`
470
- * starts again, and a GET already on the wire for it is dropped when it
471
- * lands, since it may carry the data from before the write. A reader
472
- * suspended on the variant wakes up with it (#897).
473
- */
474
- set(variantKey, data) {
475
- this.dropHttpCache(variantKey);
476
- const now = Date.now();
477
- this.markApplied(variantKey);
478
- this.staleVariants.delete(variantKey);
479
- this.lastFetchRecord.set(variantKey, now);
480
- this.failures.delete(variantKey);
481
- this.cancelRetry(variantKey);
482
- const store = this.store.getValue();
483
- this.store.next(store.set(variantKey, {
455
+ fill(store, variantKey, data, now) {
456
+ store.set(variantKey, {
484
457
  loading: false,
485
458
  data,
486
459
  hasData: true,
487
460
  error: null,
488
461
  version: now
489
- }));
462
+ });
463
+ this.staleVariants.delete(variantKey);
464
+ this.lastFetchRecord.set(variantKey, now);
465
+ this.failures.delete(variantKey);
466
+ this.cancelRetry(variantKey);
490
467
  this.settle(variantKey);
491
468
  }
492
469
  refetch(variantKey) {
@@ -752,44 +729,65 @@ function toVariantKey(search) {
752
729
  return searchParams.toString();
753
730
  }
754
731
  //#endregion
755
- //#region client/realtime/loader.ts
756
- /** `pattern` and its params, canonical: two hooks on one channel share a `sub`. */
757
- function channelKey(pattern, params) {
758
- const sorted = Object.keys(params).sort().map((key) => [key, String(params[key])]);
759
- return `${pattern}\u0000${JSON.stringify(sorted)}`;
732
+ //#region client/lazyModule.ts
733
+ /**
734
+ * What a lazy `import()` resolved to, or a thrown error when it is missing.
735
+ * Vite's preload helper resolves the `import()` to `undefined` instead of
736
+ * rejecting when a `vite:preloadError` listener handled the failure (`init`'s
737
+ * chunk-load recovery does, as it starts a reload): treated as a failed load.
738
+ */
739
+ function loadedModule(module) {
740
+ if (!module) throw new Error("[gemi] A lazily loaded chunk is unavailable.");
741
+ return module;
760
742
  }
761
- var configured = {};
762
- var instance = null;
763
- var loading = null;
743
+ /**
744
+ * The module, loading it if it is not there yet. Callers while it loads share
745
+ * one load, so their callbacks run in call order. A failed load is not kept:
746
+ * the next call runs `import()` again.
747
+ */
748
+ function loadLazy(lazy) {
749
+ if (lazy.current) return Promise.resolve(lazy.current);
750
+ return lazy.loading ??= lazy.load().then((module) => {
751
+ lazy.loading = null;
752
+ return lazy.current = loadedModule(module);
753
+ }, (error) => {
754
+ lazy.loading = null;
755
+ throw error;
756
+ });
757
+ }
758
+ //#endregion
759
+ //#region client/realtime/loader.ts
760
+ /**
761
+ * The tab's client, once loaded and created (`tabClient` in
762
+ * `./RealtimeClient` creates it), and the options it is created with.
763
+ */
764
+ var realtime = {
765
+ client: null,
766
+ options: {}
767
+ };
764
768
  /**
765
769
  * Sets the socket options (`init({ realtime })` calls it). Takes effect on
766
770
  * the next connection.
767
771
  */
768
772
  function configureRealtime(options = {}) {
769
- configured = {
770
- ...configured,
771
- ...options
772
- };
773
- instance?.configure(configured);
773
+ Object.assign(realtime.options, options);
774
+ realtime.client?.configure(realtime.options);
774
775
  }
775
776
  /** The tab's client if it is already loaded, else `null`. Never loads it. */
776
777
  function loadedRealtimeClient() {
777
- return instance;
778
+ return realtime.client;
778
779
  }
780
+ var loading = null;
781
+ /** The lazily loaded client. Replaceable in tests, to simulate a failed load. */
782
+ var lazyModules = { client: () => import("./RealtimeClient-DsWbFRC7.js") };
779
783
  /**
780
- * What a lazy `import()` resolved to, or a thrown error when it is missing.
781
- * Vite's preload helper resolves the `import()` to `undefined` instead of
782
- * rejecting when a `vite:preloadError` listener handled the failure (`init`'s
783
- * chunk-load recovery does, as it starts a reload): treated as a failed load.
784
+ * `./live`, loaded by the first live query. `<Page>` in `gemi/testing` sets
785
+ * `current` up front, so a live query on a provided socket subscribes during
786
+ * its effect, as it did before the module was split out.
784
787
  */
785
- function loadedModule(module) {
786
- if (!module) throw new Error("[gemi] A lazily loaded chunk is unavailable.");
787
- return module;
788
- }
789
- /** The lazily loaded modules. Replaceable in tests, to simulate a failed load. */
790
- var lazyModules = {
791
- client: () => import("./RealtimeClient-CqGve6h8.js"),
792
- live: () => import("./live-DIUDdLrA.js").then((n) => n.t)
788
+ var liveModule = {
789
+ current: null,
790
+ load: () => import("./live-CUdMhXHL.js").then((n) => n.n)
793
791
  };
794
792
  /**
795
793
  * The tab's client, loading its module and creating it on first use. `null`
@@ -800,41 +798,29 @@ var lazyModules = {
800
798
  */
801
799
  function loadRealtimeClient() {
802
800
  if (typeof window === "undefined") return null;
803
- if (instance) return Promise.resolve(instance);
804
- loading ??= lazyModules.client().then((module) => instance ??= new (loadedModule(module)).RealtimeClient(configured)).catch((error) => {
801
+ if (realtime.client) return Promise.resolve(realtime.client);
802
+ loading ??= lazyModules.client().then((module) => loadedModule(module).tabClient()).catch((error) => {
805
803
  loading = null;
806
804
  throw error;
807
805
  });
808
806
  return loading;
809
807
  }
810
- var liveModule = null;
811
- /**
812
- * Makes `./live` available without loading it: `<Page>` in `gemi/testing`
813
- * passes it, so a live query on a provided socket subscribes during its
814
- * effect, as it did before the module was split out.
815
- */
816
- function provideLiveModule(module) {
817
- liveModule = module;
818
- }
819
808
  /**
820
809
  * Follows `useQuery`'s `live` channel until the returned function is called.
821
- * `./live` and the socket client are loaded on first use, so `useQuery`
822
- * carries only this; once both are loaded later queries subscribe at once.
823
- * `setOpen` reports `false` until the channel is open.
810
+ * `./live` loads on first use and does the rest, loading the socket client
811
+ * in turn, so `useQuery` carries only this. `setOpen` reports `false` until
812
+ * the channel is open.
824
813
  */
825
814
  function followLive(provided, live, resource, setOpen) {
826
- let cancelled = false;
827
- let stop = null;
828
- const start = (module, socket) => {
829
- liveModule = module;
830
- if (!cancelled && socket) stop = module.subscribeLive(socket, live, resource, setOpen);
815
+ let stop;
816
+ const start = (module) => {
817
+ if (stop === void 0) stop = module.followLive(provided, live, resource, setOpen);
831
818
  };
832
- const socket = provided ?? instance;
833
- if (liveModule && socket) start(liveModule, socket);
834
- else Promise.all([liveModule ?? lazyModules.live(), socket ?? loadRealtimeClient()]).then(([module, socket]) => start(loadedModule(module), socket)).catch(() => {});
819
+ if (liveModule.current) start(liveModule.current);
820
+ else loadLazy(liveModule).then(start).catch(() => {});
835
821
  return () => {
836
- cancelled = true;
837
822
  stop?.();
823
+ stop = null;
838
824
  setOpen(false);
839
825
  };
840
826
  }
@@ -844,14 +830,7 @@ function followLive(provided, live, resource, setOpen) {
844
830
  * Never loads or creates the client.
845
831
  */
846
832
  function reconnectRealtime() {
847
- instance?.reconnect();
848
- }
849
- /**
850
- * The open socket's id, for the `X-Gemi-Socket` header, or `null`. Never
851
- * loads or creates the client.
852
- */
853
- function currentSocketId() {
854
- return instance?.socketId ?? null;
833
+ realtime.client?.reconnect();
855
834
  }
856
835
  //#endregion
857
836
  //#region client/realtime/RealtimeContext.ts
@@ -3473,7 +3452,7 @@ function useChannelSubscription(pattern, params, handlers, enabled) {
3473
3452
  };
3474
3453
  }, [
3475
3454
  provided,
3476
- pattern === null ? null : channelKey(pattern, params),
3455
+ pattern === null ? null : JSON.stringify([pattern, params]),
3477
3456
  active
3478
3457
  ]);
3479
3458
  if (typeof window === "undefined") return active ? CLOSED : IDLE;
@@ -3629,6 +3608,6 @@ function useTheme() {
3629
3608
  return context;
3630
3609
  }
3631
3610
  //#endregion
3632
- export { DEFAULT_STALE_TIME as $, ServerDataContext as A, configureRealtime as B, readRoutePayload as C, useNavigate as D, useSearchParams as E, ProgressManager as F, reconnectRealtime as G, followLive 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, loadedModule as U, currentSocketId as V, provideLiveModule 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, channelKey as z };
3611
+ 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 };
3633
3612
 
3634
- //# sourceMappingURL=ThemeProvider-DaX0eyqs.js.map
3613
+ //# sourceMappingURL=ThemeProvider-gWqXjGh-.js.map