@everfur/sdk 0.12.0 → 0.13.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 (268) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +2 -1
  3. package/dist/{Chat-BOG0SXKV.d.cts → Chat.d-DUNTfzqC.d.ts} +170 -8
  4. package/dist/{Chat-CIolBgjJ.d.ts → Chat.d-Dts8u_1a.d.cts} +170 -8
  5. package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews.d-BIp599lz.d.cts} +1 -1
  6. package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews.d-BMU2jFPw.d.cts} +1 -1
  7. package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews.d-Ce2Zhnrb.d.ts} +1 -1
  8. package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews.d-CubkMPbU.d.ts} +1 -1
  9. package/dist/{ErrorPolicyPort-10s3HJCt.d.cts → ErrorPolicyPort.d-68yrE3BE.d.ts} +1 -1
  10. package/dist/{ErrorPolicyPort-C3nNSS_j.d.ts → ErrorPolicyPort.d-DirW9hgO.d.cts} +1 -1
  11. package/dist/{EverfurError-DeBqRpQV.d.cts → EverfurError.d-8NHtlgzA.d.cts} +11 -1
  12. package/dist/{EverfurError-DeBqRpQV.d.ts → EverfurError.d-8NHtlgzA.d.ts} +11 -1
  13. package/dist/{EverfurResult-ClPTS0P2.d.ts → EverfurResult.d-BFH-3s6E.d.cts} +1 -1
  14. package/dist/{EverfurResult-COlXj1wq.d.cts → EverfurResult.d-D_-254ZY.d.ts} +1 -1
  15. package/dist/{IntakeMedia-BH0fYDT2.d.cts → IntakeMedia.d-4a89XrP7.d.ts} +1 -1
  16. package/dist/{IntakeMedia-B-_vA9ZB.d.cts → IntakeMedia.d-DGxrhgIW.d.ts} +1 -1
  17. package/dist/{IntakeMedia-CIoTXAWs.d.ts → IntakeMedia.d-DUPR4lVM.d.cts} +1 -1
  18. package/dist/{IntakeMedia-Bavl7E4Z.d.ts → IntakeMedia.d-JJCUvQu7.d.cts} +1 -1
  19. package/dist/LifecyclePort.d-Cr1p33a7.d.cts +23 -0
  20. package/dist/LifecyclePort.d-Cr1p33a7.d.ts +23 -0
  21. package/dist/{PhotoController-vzY5bfY_.d.ts → PhotoController.d-BzCJOE7e.d.cts} +2 -2
  22. package/dist/{PhotoController-3l7MT9jA.d.cts → PhotoController.d-D0XiUUOl.d.ts} +2 -2
  23. package/dist/animations/index.cjs +5 -1
  24. package/dist/animations/index.d.cts +24 -24
  25. package/dist/animations/index.d.ts +24 -24
  26. package/dist/animations/index.js +5 -1
  27. package/dist/{attachments-CGxvnYu4.d.ts → attachments.d-Bp2qbHxn.d.cts} +22 -26
  28. package/dist/{attachments-CWNj1ZkM.d.ts → attachments.d-D1yhJjcZ.d.ts} +4 -4
  29. package/dist/{attachments-waXcJWCp.d.cts → attachments.d-DisnvB9R.d.cts} +4 -4
  30. package/dist/{attachments-B6h4cJU-.d.cts → attachments.d-Djy9z_0Z.d.ts} +22 -26
  31. package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy.d-BJF6gd1A.d.ts} +24 -9
  32. package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy.d-BlBmhAJc.d.cts} +24 -9
  33. package/dist/{branding-DJf4h12Q.d.ts → branding.d-DI8S400y.d.cts} +9 -2
  34. package/dist/{branding-BCfwLj0h.d.cts → branding.d-OIGLbQeM.d.ts} +9 -2
  35. package/dist/{callRoom-BhIdadyV.d.cts → callRoom.d-B1DoYdJe.d.cts} +1 -1
  36. package/dist/{callRoom-B92eH_ij.d.ts → callRoom.d-Dqm1rUqT.d.ts} +1 -1
  37. package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository.d-CT2LTicS.d.cts} +3 -3
  38. package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository.d-UsWOz9bv.d.ts} +3 -3
  39. package/dist/chat/index.cjs +132 -57
  40. package/dist/chat/index.d.cts +18 -16
  41. package/dist/chat/index.d.ts +18 -16
  42. package/dist/chat/index.js +133 -58
  43. package/dist/client/index.cjs +15 -10
  44. package/dist/client/index.d.cts +19 -18
  45. package/dist/client/index.d.ts +19 -18
  46. package/dist/client/index.js +15 -10
  47. package/dist/{config-B0p6Lygh.d.cts → config.d-BR3DT9ho.d.cts} +3 -3
  48. package/dist/{config-DmFAZJOx.d.ts → config.d-Dy6igYlH.d.ts} +3 -3
  49. package/dist/consent/index.cjs +5 -1
  50. package/dist/consent/index.d.cts +10 -10
  51. package/dist/consent/index.d.ts +10 -10
  52. package/dist/consent/index.js +5 -1
  53. package/dist/{context-BNreNLtL.d.ts → context.d-Cwks0p3C.d.cts} +15 -15
  54. package/dist/{context-BgS2a57J.d.cts → context.d-QcCgguzA.d.ts} +15 -15
  55. package/dist/{copy-DLJriGQS.d.ts → copy.d-CiMn2IIt.d.ts} +6 -6
  56. package/dist/{copy-lWp-Lkv5.d.cts → copy.d-DLJTyRfT.d.cts} +6 -6
  57. package/dist/core/index.cjs +17 -13
  58. package/dist/core/index.d.cts +33 -29
  59. package/dist/core/index.d.ts +33 -29
  60. package/dist/core/index.js +17 -13
  61. package/dist/{depth-BYb3RXoA.d.cts → depth.d-CjPGVPDL.d.cts} +9 -115
  62. package/dist/{depth-COz-sSG5.d.ts → depth.d-OSALbYM7.d.ts} +9 -115
  63. package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository.d-CVQa1DA1.d.cts} +10 -5
  64. package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository.d-Cf3LbTwD.d.ts} +10 -5
  65. package/dist/features.d-fNsGcg0R.d.cts +108 -0
  66. package/dist/features.d-fNsGcg0R.d.ts +108 -0
  67. package/dist/focus.d-DMg2ngHI.d.ts +1178 -0
  68. package/dist/focus.d-az9cqUz3.d.cts +1178 -0
  69. package/dist/health-plan/index.cjs +370 -0
  70. package/dist/health-plan/index.d.cts +251 -0
  71. package/dist/health-plan/index.d.ts +251 -0
  72. package/dist/health-plan/index.js +370 -0
  73. package/dist/idempotency.d-D461_DPD.d.cts +910 -0
  74. package/dist/idempotency.d-WpXx9zQo.d.ts +910 -0
  75. package/dist/{identity-Cw07BKZp.d.ts → identity.d-60LeJt_s.d.cts} +3 -3
  76. package/dist/{identity-DFVGYn1o.d.cts → identity.d-DzTijonw.d.ts} +3 -3
  77. package/dist/index.cjs +141 -66
  78. package/dist/index.d.cts +31 -29
  79. package/dist/index.d.ts +31 -29
  80. package/dist/index.js +142 -67
  81. package/dist/{models-A4A5S7AG.d.cts → models.d-BagXhafD.d.ts} +8 -3
  82. package/dist/{models-CnXY5LuO.d.ts → models.d-BnLm3VAA.d.cts} +8 -3
  83. package/dist/notifications/index.cjs +5 -1
  84. package/dist/notifications/index.d.cts +9 -9
  85. package/dist/notifications/index.d.ts +9 -9
  86. package/dist/notifications/index.js +5 -1
  87. package/dist/optInView.d-CEyHR6PK.d.cts +325 -0
  88. package/dist/optInView.d-acKpV8V2.d.ts +325 -0
  89. package/dist/parse.d-C8CXyS58.d.ts +210 -0
  90. package/dist/parse.d-tEzufgJX.d.cts +210 -0
  91. package/dist/{pets-BYALZTSu.d.ts → pets.d-C_53_fzo.d.ts} +3 -3
  92. package/dist/{pets-CcyPQS-H.d.cts → pets.d-NbJvP_kh.d.cts} +3 -3
  93. package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository.d-BuGHymNx.d.ts} +4 -4
  94. package/dist/{petsRepository-518QkPxH.d.ts → petsRepository.d-lp1BHRqM.d.cts} +4 -4
  95. package/dist/photo/index.cjs +6 -2
  96. package/dist/photo/index.d.cts +9 -9
  97. package/dist/photo/index.d.ts +9 -9
  98. package/dist/photo/index.js +6 -2
  99. package/dist/{ports-BN6RHF9W.d.ts → ports.d-BX4f4UsB.d.cts} +14 -1
  100. package/dist/{ports-BN6RHF9W.d.cts → ports.d-BX4f4UsB.d.ts} +14 -1
  101. package/dist/{ports-RuNJmBA-.d.cts → ports.d-CEROoqnA.d.cts} +16 -10
  102. package/dist/{ports-DmQeMArX.d.ts → ports.d-COIyN624.d.ts} +16 -10
  103. package/dist/presentation.d-DMbdad7G.d.cts +90 -0
  104. package/dist/presentation.d-DMbdad7G.d.ts +90 -0
  105. package/dist/records/depth/index.cjs +11 -7
  106. package/dist/records/depth/index.d.cts +14 -12
  107. package/dist/records/depth/index.d.ts +14 -12
  108. package/dist/records/depth/index.js +11 -7
  109. package/dist/records/index.cjs +225 -62
  110. package/dist/records/index.d.cts +159 -20
  111. package/dist/records/index.d.ts +159 -20
  112. package/dist/records/index.js +225 -62
  113. package/dist/recordsAsk.d-C5CGSi3j.d.cts +14 -0
  114. package/dist/recordsAsk.d-C5CGSi3j.d.ts +14 -0
  115. package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel.d-CXUMPw1K.d.ts} +5 -5
  116. package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel.d-DWQQpjFR.d.cts} +5 -5
  117. package/dist/{resolve-D4Ywz5OS.d.ts → resolve.d-jI8FmBj3.d.cts} +3 -3
  118. package/dist/{resolve-D4Ywz5OS.d.cts → resolve.d-jI8FmBj3.d.ts} +3 -3
  119. package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes.d-4yFNNuYR.d.ts} +20 -13
  120. package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes.d-D6N_fhxx.d.cts} +20 -13
  121. package/dist/server/events/index.cjs +7 -3
  122. package/dist/server/events/index.d.cts +51 -9
  123. package/dist/server/events/index.d.ts +51 -9
  124. package/dist/server/events/index.js +7 -3
  125. package/dist/server/index.cjs +12 -6
  126. package/dist/server/index.d.cts +152 -8
  127. package/dist/server/index.d.ts +152 -8
  128. package/dist/server/index.js +12 -6
  129. package/dist/sheetCopy.d-CAhLOxjc.d.cts +4 -0
  130. package/dist/sheetCopy.d-CAhLOxjc.d.ts +4 -0
  131. package/dist/sheetSeam.d-Cviqk89n.d.ts +45 -0
  132. package/dist/sheetSeam.d-DCS3LW8g.d.cts +45 -0
  133. package/dist/shop/index.cjs +262 -0
  134. package/dist/shop/index.d.cts +193 -0
  135. package/dist/shop/index.d.ts +193 -0
  136. package/dist/shop/index.js +262 -0
  137. package/dist/televet/booking/index.cjs +16 -12
  138. package/dist/televet/booking/index.d.cts +36 -22
  139. package/dist/televet/booking/index.d.ts +36 -22
  140. package/dist/televet/booking/index.js +16 -12
  141. package/dist/televet/call/index.d.cts +5 -5
  142. package/dist/televet/call/index.d.ts +5 -5
  143. package/dist/televet/index.cjs +7 -3
  144. package/dist/televet/index.d.cts +12 -12
  145. package/dist/televet/index.d.ts +12 -12
  146. package/dist/televet/index.js +7 -3
  147. package/dist/{televetGlobal-C5dTUACe.d.cts → televetGlobal.d-CC-DrqkQ.d.ts} +7 -2
  148. package/dist/{televetGlobal-CnjrfhT4.d.ts → televetGlobal.d-CKwDCbmN.d.cts} +7 -2
  149. package/dist/testing/index.cjs +7 -3
  150. package/dist/testing/index.d.cts +3 -3
  151. package/dist/testing/index.d.ts +3 -3
  152. package/dist/testing/index.js +7 -3
  153. package/dist/testing/rn/index.cjs +5 -1
  154. package/dist/testing/rn/index.d.cts +23 -22
  155. package/dist/testing/rn/index.d.ts +23 -22
  156. package/dist/testing/rn/index.js +5 -1
  157. package/dist/testing/web/index.cjs +5 -1
  158. package/dist/testing/web/index.d.cts +23 -22
  159. package/dist/testing/web/index.d.ts +23 -22
  160. package/dist/testing/web/index.js +5 -1
  161. package/dist/texting/index.cjs +158 -0
  162. package/dist/texting/index.d.cts +36 -0
  163. package/dist/texting/index.d.ts +36 -0
  164. package/dist/texting/index.js +158 -0
  165. package/dist/threadOptions.d-B1pTMmDF.d.cts +260 -0
  166. package/dist/threadOptions.d-B1pTMmDF.d.ts +260 -0
  167. package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows.d-BNxgzYRW.d.cts} +1 -1
  168. package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows.d-CU5GvvLk.d.ts} +1 -1
  169. package/dist/{tokens-DLj8OnLH.d.cts → tokens.d-DarDaV39.d.cts} +10 -2
  170. package/dist/{tokens-DLj8OnLH.d.ts → tokens.d-DarDaV39.d.ts} +10 -2
  171. package/dist/{typeStyle-BxVyF71R.d.ts → typeStyle.d-Bl8pzbBy.d.cts} +2 -2
  172. package/dist/{typeStyle-DJedEu14.d.cts → typeStyle.d-C1HBRAI3.d.ts} +2 -2
  173. package/dist/{uploadTransport-BM_pnEWj.d.cts → uploadTransport.d-CWL7CdWP.d.cts} +1 -1
  174. package/dist/{uploadTransport-C6kGP1Kd.d.ts → uploadTransport.d-EGoUl7gX.d.ts} +1 -1
  175. package/dist/usePresentation.d-D6qsFzBz.d.cts +9 -0
  176. package/dist/usePresentation.d-DuGQe_Do.d.ts +9 -0
  177. package/dist/useRecords.d-Cb-36SF5.d.cts +121 -0
  178. package/dist/useRecords.d-aQTzQZoV.d.ts +121 -0
  179. package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth.d-DFcCfiXm.d.ts} +8 -20
  180. package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth.d-sAq2Qkhr.d.cts} +8 -20
  181. package/dist/{useVetVisit-DmWa7lt1.d.ts → useVetVisit.d-BtdwhmgD.d.cts} +15 -4
  182. package/dist/{useVetVisit-PtBjNwZr.d.cts → useVetVisit.d-DoYQimyt.d.ts} +15 -4
  183. package/dist/video/index.cjs +6 -2
  184. package/dist/video/index.d.cts +7 -7
  185. package/dist/video/index.d.ts +7 -7
  186. package/dist/video/index.js +6 -2
  187. package/dist/{view-C6go2uUt.d.ts → view.d-C-SNpDJX.d.ts} +10 -122
  188. package/dist/{view-CiF_HVFQ.d.cts → view.d-Dps5C8-s.d.cts} +10 -122
  189. package/dist/web/consent/index.cjs +5 -1
  190. package/dist/web/consent/index.d.cts +10 -10
  191. package/dist/web/consent/index.d.ts +10 -10
  192. package/dist/web/consent/index.js +5 -1
  193. package/dist/web/health-plan/index.cjs +414 -0
  194. package/dist/web/health-plan/index.d.cts +335 -0
  195. package/dist/web/health-plan/index.d.ts +335 -0
  196. package/dist/web/health-plan/index.js +414 -0
  197. package/dist/web/index.cjs +150 -82
  198. package/dist/web/index.d.cts +152 -38
  199. package/dist/web/index.d.ts +152 -38
  200. package/dist/web/index.js +150 -82
  201. package/dist/web/notifications/index.cjs +16 -3
  202. package/dist/web/notifications/index.d.cts +39 -209
  203. package/dist/web/notifications/index.d.ts +39 -209
  204. package/dist/web/notifications/index.js +16 -3
  205. package/dist/web/records/depth/index.cjs +11 -7
  206. package/dist/web/records/depth/index.d.cts +14 -12
  207. package/dist/web/records/depth/index.d.ts +14 -12
  208. package/dist/web/records/depth/index.js +11 -7
  209. package/dist/web/records/index.cjs +95 -68
  210. package/dist/web/records/index.d.cts +66 -21
  211. package/dist/web/records/index.d.ts +66 -21
  212. package/dist/web/records/index.js +95 -68
  213. package/dist/web/records/upload/index.d.cts +2 -2
  214. package/dist/web/records/upload/index.d.ts +2 -2
  215. package/dist/web/records-sheet/index.cjs +278 -0
  216. package/dist/web/records-sheet/index.d.cts +102 -0
  217. package/dist/web/records-sheet/index.d.ts +102 -0
  218. package/dist/web/records-sheet/index.js +278 -0
  219. package/dist/web/shop/index.cjs +301 -0
  220. package/dist/web/shop/index.d.cts +42 -0
  221. package/dist/web/shop/index.d.ts +42 -0
  222. package/dist/web/shop/index.js +301 -0
  223. package/dist/web/televet/booking/index.cjs +16 -12
  224. package/dist/web/televet/booking/index.d.cts +37 -23
  225. package/dist/web/televet/booking/index.d.ts +37 -23
  226. package/dist/web/televet/booking/index.js +16 -12
  227. package/dist/web/televet/call/index.d.cts +4 -4
  228. package/dist/web/televet/call/index.d.ts +4 -4
  229. package/dist/web/televet/index.cjs +7 -3
  230. package/dist/web/televet/index.d.cts +12 -12
  231. package/dist/web/televet/index.d.ts +12 -12
  232. package/dist/web/televet/index.js +7 -3
  233. package/dist/web/texting/index.cjs +157 -0
  234. package/dist/web/texting/index.d.cts +36 -0
  235. package/dist/web/texting/index.d.ts +36 -0
  236. package/dist/web/texting/index.js +157 -0
  237. package/health-plan/package.json +8 -0
  238. package/package.json +106 -4
  239. package/shop/package.json +8 -0
  240. package/texting/package.json +8 -0
  241. package/web/health-plan/native-blocked.cjs +12 -0
  242. package/web/health-plan/package.json +8 -0
  243. package/web/records-sheet/native-blocked.cjs +12 -0
  244. package/web/records-sheet/package.json +8 -0
  245. package/web/shop/native-blocked.cjs +12 -0
  246. package/web/shop/package.json +8 -0
  247. package/web/texting/native-blocked.cjs +12 -0
  248. package/web/texting/package.json +8 -0
  249. /package/dist/{CameraPort-Cv31Pz7g.d.cts → CameraPort.d-Cv31Pz7g.d.cts} +0 -0
  250. /package/dist/{CameraPort-Cv31Pz7g.d.ts → CameraPort.d-Cv31Pz7g.d.ts} +0 -0
  251. /package/dist/{TelemetryPort-BDNr00hu.d.cts → TelemetryPort.d-BDNr00hu.d.cts} +0 -0
  252. /package/dist/{TelemetryPort-BDNr00hu.d.ts → TelemetryPort.d-BDNr00hu.d.ts} +0 -0
  253. /package/dist/{cacheEpoch-DknKn3S0.d.cts → cacheEpoch.d-DknKn3S0.d.cts} +0 -0
  254. /package/dist/{cacheEpoch-DknKn3S0.d.ts → cacheEpoch.d-DknKn3S0.d.ts} +0 -0
  255. /package/dist/{callCopy-Bw6oZT54.d.cts → callCopy.d-Bw6oZT54.d.cts} +0 -0
  256. /package/dist/{callCopy-Bw6oZT54.d.ts → callCopy.d-Bw6oZT54.d.ts} +0 -0
  257. /package/dist/{ids-B2GAAifq.d.cts → ids.d-B2GAAifq.d.cts} +0 -0
  258. /package/dist/{ids-B2GAAifq.d.ts → ids.d-B2GAAifq.d.ts} +0 -0
  259. /package/dist/{optionalModule-DbJmsq5f.d.cts → optionalModule.d-DbJmsq5f.d.cts} +0 -0
  260. /package/dist/{optionalModule-DbJmsq5f.d.ts → optionalModule.d-DbJmsq5f.d.ts} +0 -0
  261. /package/dist/{profile-CSs1wlXT.d.cts → profile.d-CSs1wlXT.d.cts} +0 -0
  262. /package/dist/{profile-CSs1wlXT.d.ts → profile.d-CSs1wlXT.d.ts} +0 -0
  263. /package/dist/{projection-CeIUsbSk.d.cts → projection.d-CeIUsbSk.d.cts} +0 -0
  264. /package/dist/{projection-CeIUsbSk.d.ts → projection.d-CeIUsbSk.d.ts} +0 -0
  265. /package/dist/{species-BXAIMh7I.d.cts → species.d-BXAIMh7I.d.cts} +0 -0
  266. /package/dist/{species-BXAIMh7I.d.ts → species.d-BXAIMh7I.d.ts} +0 -0
  267. /package/dist/{visitIntent-D7_yVp1I.d.cts → visitIntent.d-D7_yVp1I.d.cts} +0 -0
  268. /package/dist/{visitIntent-D7_yVp1I.d.ts → visitIntent.d-D7_yVp1I.d.ts} +0 -0
@@ -21,6 +21,8 @@
21
21
  /* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
22
22
  /* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
23
23
  /* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
24
+ /* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
25
+ /* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
24
26
  /* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
25
27
  /* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
26
28
  /* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
@@ -45,6 +47,7 @@
45
47
  /* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
46
48
  /* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
47
49
  /* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
50
+ /* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
48
51
  /* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
49
52
  /* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
50
53
  /* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
@@ -81,13 +84,14 @@
81
84
  /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
82
85
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
83
86
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
87
+ /* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
84
88
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
85
89
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
86
90
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
87
91
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
88
92
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
89
93
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
90
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
94
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
91
95
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
92
96
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
93
97
  /* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
@@ -97,18 +101,20 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
97
101
  /* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
98
102
  /* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
99
103
  /* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
100
- /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
101
- return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
104
+ /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
105
+ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
102
106
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
103
107
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
104
108
  return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid("pet_ref must be a string");if(petRef.trim().length===0)return invalid("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str2=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
105
109
  return Object.freeze({petRef:str2(o.pet_ref)??petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str2(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str2(o.pet_id),petRef:petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str2(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
106
- return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid3=validate(petRef,profile);if(invalid3!==null)return err(invalid3);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useStalePetHold(runtime,userRef,petRef,scopeEpoch){let[owner,setOwner]=react.useState({pet:petRef,user:userRef}),adopt=owner.pet!==petRef||owner.user===null&&userRef!==null;adopt&&setOwner({pet:petRef,user:userRef});let current=adopt?{user:userRef}:owner,held=petRef!==null&&current.user!==null&&current.user!==userRef;return react.useEffect(()=>{if(!held||userRef===null||petRef===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef)&&setOwner({pet:petRef,user:userRef})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef,petRef,scopeEpoch]),held}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef=opts?.petRef??activePet??null,conversationId=opts?.conversationId??null,held=useStalePetHold(runtime,userRef,petRef,scopeEpoch),scope=react.useMemo(()=>({runtime:runtime,userRef:userRef,petRef:petRef,conversationId:conversationId,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef,petRef,conversationId,scopeEpoch,held]),[binding,setBinding]=react.useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef,petRef:petRef,conversationId:conversationId}),active=react.useRef(null);react.useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef,petRef:petRef,conversationId:conversationId});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef,petRef,conversationId,scopeEpoch,held,scope]);let subscribe=react.useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=react.useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=react.useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=react.useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=react.useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=react.useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=react.useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=react.useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=react.useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=react.useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=react.useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef?{petRef:petRef}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef]);return react.useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}var FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
107
- return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str3=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str3(o.upload_id),uploadUrl=str3(o.upload_url),s3Key=str3(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
108
- return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str3(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight2=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed=false,publish2=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed&&inFlight2.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight2.add(id),run(row).finally(()=>{inFlight2.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=react.useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef,scopeEpoch,maxPerMessage,options.transport]),scoped=react.useMemo(()=>options.queue??build(),[options.queue,build]),disposed=react.useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=react.useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;react.useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=react.useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=react.useState(null),add=react.useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=react.useCallback(id=>queue.retry(id),[queue]),remove=react.useCallback(id=>queue.remove(id),[queue]),clear=react.useCallback(()=>queue.clear(),[queue]),dismissRejected=react.useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return react.useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function petRegistrationKey(runtime,auth,petRef,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef,pet,onRegistered){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),register=react.useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef,scopeEpoch]),bodyKey=react.useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=react.useState({key:null,status:"idle",error:null,registered:null}),generation=react.useRef(0),onRegisteredRef=react.useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef===null||bodyKey===null?null:`${String(userRef)}|${scopeEpoch}|${petRef}|${bodyKey}`,run=react.useCallback(()=>{if(petRef===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef,scopeKey]);react.useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=react.useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return react.useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=react.useState(NONE),pending=react.useRef(null),knownIds=react.useRef([]);knownIds.current=messages.map(message=>message.id),react.useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE?current:NONE);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=react.useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return react.useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=react.useRef(askEverfur);latest.current=askEverfur;let asked=react.useRef(null);react.useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId=state.activeConversationId;return conversationId===null||conversationId.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=react.useRef(target);latest.current=target;let lastRefresh=react.useRef(null),deferred=react.useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=react.useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},react.useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),react.useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId=target.conversationId??"",petRef=target.petRef??"";return conversationId===""&&petRef===""?null:`${String(conversationId)}|${String(petRef)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=react.useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=react.useRef(null);react.useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}function useChatDraft(send,conversationId,seed){let[state,setState]=react.useState({send:send,conversationId:conversationId,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId);react.useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh2=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId,text:fresh2?seed:text3,seeded:fresh2?seed:seeded}})},[send,conversationId,seed]);let setDraft=react.useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId,text:text3,seeded:previous.seeded})),[send,conversationId]);return[belongs?state.text:"",setDraft]}function usePersistedDraft(store,conversationId,draft,setDraft){let latest=react.useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=react.useRef(null),[settled,setSettled]=react.useState(null);react.useEffect(()=>{if(store===void 0)return;let key=`${conversationId??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId));if(!live)return;let stored2=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored2.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored2),setSettled(key)})(),()=>{live=false}},[store,conversationId]),react.useEffect(()=>{store===void 0||settled!==`${conversationId??""}`||callHost(()=>store.write(conversationId,draft))},[store,conversationId,draft,settled])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=react.useState(false),[query,setQuery]=react.useState(""),scope=chat.listConversations,generation=react.useRef(0),[state,setState]=react.useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);react.useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=react.useCallback(async cursor=>{let request=++generation.current,more=cursor!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor?{cursor:cursor}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=react.useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=react.useState(null),[expanded,setExpanded]=react.useState(false);react.useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=react.useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=react.useCallback(()=>setExpanded(true),[]);return react.useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
109
- return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef,conversationId){let opts={};return petRef!==void 0&&(opts.petRef=petRef),conversationId!==void 0&&(opts.conversationId=conversationId),opts}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
110
+ return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid4=validate(petRef,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useStalePetHold(runtime,userRef,petRef,scopeEpoch){let[owner,setOwner]=react.useState({pet:petRef,user:userRef}),adopt=owner.pet!==petRef||owner.user===null&&userRef!==null;adopt&&setOwner({pet:petRef,user:userRef});let current=adopt?{user:userRef}:owner,held=petRef!==null&&current.user!==null&&current.user!==userRef;return react.useEffect(()=>{if(!held||userRef===null||petRef===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef)&&setOwner({pet:petRef,user:userRef})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef,petRef,scopeEpoch]),held}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef=opts?.petRef??activePet??null,conversationId=opts?.conversationId??null,held=useStalePetHold(runtime,userRef,petRef,scopeEpoch),scope=react.useMemo(()=>({runtime:runtime,userRef:userRef,petRef:petRef,conversationId:conversationId,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef,petRef,conversationId,scopeEpoch,held]),[binding,setBinding]=react.useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef,petRef:petRef,conversationId:conversationId}),active=react.useRef(null);react.useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef,petRef:petRef,conversationId:conversationId});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef,petRef,conversationId,scopeEpoch,held,scope]);let subscribe=react.useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=react.useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=react.useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=react.useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=react.useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=react.useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=react.useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=react.useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=react.useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=react.useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=react.useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef?{petRef:petRef}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef]);return react.useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark"}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
111
+ return Object.freeze(out)}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var REF_MAX2=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str3=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str3(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str3(value,REF_MAX2);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
112
+ return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str3(v,len),max);function focusOf(value){let o=obj(value),kicker=str3(o?.kicker,120),title=str3(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str3(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str3(risk?.lead,300)===null?null:clean({lead:str3(risk?.lead,300),body:str3(risk?.body),kind:kindOf(risk?.kind)}),odds:str3(odds?.label,120)===null||str3(odds?.from,20)===null||str3(odds?.to,20)===null?null:clean({label:str3(odds?.label,120),tag:str3(odds?.tag,40),from:str3(odds?.from,20),to:str3(odds?.to,20),toLabel:str3(odds?.toLabel,120)}),quote:str3(quote?.kicker,120)===null||str3(quote?.text)===null?null:clean({kicker:str3(quote?.kicker,120),tag:str3(quote?.tag,40),text:str3(quote?.text)}),jump:str3(jump?.title,300)===null||str3(jump?.go,60)===null?null:clean({title:str3(jump?.title,300),go:str3(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str3(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str3(s?.title,300);return t===null?null:clean({title:t,body:str3(s?.body),source:str3(s?.source,200)})});return title===null||steps===null?null:clean({title:title,label:str3(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str3(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text3=str3(v?.text),by=str3(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text3===null||by===null?null:clean({stars:Math.round(stars),text:text3,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str3(v?.chip,40),t=str3(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str3(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str3(v?.value,40),label=str3(v?.label,120);return val===null||label===null?null:clean({value:val,label:label})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,productId:idOf(o.productId),partnerSku:str3(o.partnerSku,200),rating:str3(rating?.value,20)===null?null:clean({value:str3(rating?.value,20),label:str3(rating?.label,120)}),line:str3(o.line),reviews:str3(reviews?.label,200)===null||reviewItems===null?null:clean({label:str3(reviews?.label,200),items:reviewItems}),checkoutLine:str3(o.checkoutLine,300),why:str3(why?.title,200)===null||whyRows===null?null:clean({title:str3(why?.title,200),rows:whyRows,score:str3(score?.text,200)===null||str3(score?.value,20)===null?null:clean({text:str3(score?.text,200),value:str3(score?.value,20)})}),dose:str3(dose?.title,200)===null||stats===null?null:clean({title:str3(dose?.title,200),stats:stats,note:str3(dose?.note)}),ingredients:ingredientItems===null?null:clean({label:str3(ingredients?.label,200),items:ingredientItems}),proof:str3(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str3(o.more,120),fine:str3(o.fine),checkin:str3(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str3(v?.title,300),body=str3(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str3(o?.title,200),questions=words(o?.questions,12,300),add=str3(o?.add,80),added=str3(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str3(v?.key,REF_MAX2),t=str3(v?.title,300),action=str3(v?.action,80),added=str3(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str3(v?.body),price:str3(v?.price,40),was:str3(v?.was,40),tag:str3(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added})},6);return title===null||items===null?null:clean({title:title,items:items})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str3(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str3(o.eyebrow,120),title:title,subtitle:str3(o.subtitle,300),headImageUrl:imageOf(o.headImageUrl),byline:str3(byline?.name,120)===null?null:clean({name:str3(byline?.name,120),role:str3(byline?.role,120),imageUrl:imageOf(byline?.imageUrl)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),fine:str3(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,60),val=str3(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
113
+ return Object.freeze({petRef:str3(o.pet_ref,REF_MAX2)??petRef,pet:/* @__PURE__ */Object.freeze({name:str3(pet?.name,120),species:str3(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str3(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid2("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=react.useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},react.useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=react.useRef(refreshKey);react.useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef,petRef,fresh2){let reads=sharedReads.get(reader);reads===void 0&&(reads=/* @__PURE__ */new Map,sharedReads.set(reader,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh2&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=react.useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=react.useCallback((pet,fresh2)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,userRef,pet,fresh2),[hostRepository,repository,own,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=react.useState({phase:"idle",petRef:null,page:null,error:null}),epoch=react.useRef(0),quiet=react.useRef(0),read=react.useCallback(async fresh2=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh2);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=react.useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=react.useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),react.useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return react.useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
110
114
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
111
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView2(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView2(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
115
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe=react.useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=react.useCallback(()=>{if(store===void 0)return false;let snapshot=store.getSnapshot();return decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}).enabled},[store,name]);return react.useSyncExternalStore(subscribe,read,read)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=react.useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=react.useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return react.useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}function selectView(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
116
+ return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state,policy){if(policy===void 0)return visibleFollowUps(state);let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state.messages.length-1;i>=0;i-=1){let m=state.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state.suggestedPrompts)take(prompt);let fill=[];try{fill=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill=[]}for(let prompt of Array.isArray(fill)?fill:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
117
+ return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef,conversationId){let opts={};return petRef!==void 0&&(opts.petRef=petRef),conversationId!==void 0&&(opts.conversationId=conversationId),opts}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){return false}function followUpPolicyFor(host,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(count===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count<=0)return{...{},count:1,exclude:NONE,fill:[]};let hostExclude=host?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes():hostExclude;return{...{},count:count,...exclude!==void 0?{exclude:exclude}:{}}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function petRegistrationKey(runtime,auth,petRef,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef,pet,onRegistered){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),register=react.useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef,scopeEpoch]),bodyKey=react.useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=react.useState({key:null,status:"idle",error:null,registered:null}),generation=react.useRef(0),onRegisteredRef=react.useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef===null||bodyKey===null?null:`${String(userRef)}|${scopeEpoch}|${petRef}|${bodyKey}`,run=react.useCallback(()=>{if(petRef===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef,scopeKey]);react.useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=react.useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return react.useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE2=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=react.useState(NONE2),pending=react.useRef(null),knownIds=react.useRef([]);knownIds.current=messages.map(message=>message.id),react.useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE2?current:NONE2);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=react.useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return react.useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt,key){let clean2=sanitizeSeedPrompt(prompt),id=clean2===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean2}`,latest=react.useRef(askEverfur);latest.current=askEverfur;let done=react.useRef(null),inFlight2=react.useRef(null),current=react.useRef(id);current.current=id,react.useEffect(()=>{if(clean2===null||id===null||isBootstrapping||done.current===id||inFlight2.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight2.current=id;let settle=result=>{inFlight2.current===id&&(inFlight2.current=null),!isChatNotReadyResult(result)&&current.current===id&&(done.current=id)};Promise.resolve(ask(clean2)).then(settle,()=>settle(void 0))},[clean2,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId=state.activeConversationId;return conversationId===null||conversationId.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function useChatLifecycle(lifecycle,target){let latest=react.useRef(target);latest.current=target;let lastRefresh=react.useRef(null),deferred=react.useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=react.useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},react.useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),react.useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId=target.conversationId??"",petRef=target.petRef??"";return conversationId===""&&petRef===""?null:`${String(conversationId)}|${String(petRef)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=react.useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=react.useRef(null);react.useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=react.useState(false),[query,setQuery]=react.useState(""),scope=chat.listConversations,generation=react.useRef(0),[state,setState]=react.useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);react.useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=react.useCallback(async cursor=>{let request=++generation.current,more=cursor!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor?{cursor:cursor}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=react.useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=react.useState(null),[expanded,setExpanded]=react.useState(false);react.useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=react.useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=react.useCallback(()=>setExpanded(true),[]);return react.useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var MIN_OFFSTATE_HEIGHT=48;function selectView2(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView2(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
112
118
  return jsxRuntime.jsx(reactNative.View,{style:[styles2.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
113
119
  return jsxRuntime.jsx(reactNative.View,{style:[styles2.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
114
120
  return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
@@ -150,16 +156,27 @@ return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
150
156
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.22,width:size*.92,height:size*.66,borderWidth:w,borderColor:color,borderRadius:size*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.3,height:size*.3,borderRadius:size,borderWidth:w,borderColor:color}})})]})}function SearchGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),unit=size/24,outer=16*unit+w,ringAt=11*unit-outer/2,start=11+8/Math.SQRT2,length=(21-start)*Math.SQRT2*unit,middle=(start+21)/2*unit;/* @__PURE__ */
151
157
  return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
152
158
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:ringAt,left:ringAt,width:outer,height:outer,borderRadius:outer,borderWidth:w,borderColor:color}}),
153
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function MapPinGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),ring=size*.62;/* @__PURE__ */
159
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
160
+ return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
161
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:size*.3,height:size*.82,borderWidth:w,borderColor:color,borderRadius:w,transform:[{rotate:"45deg"}]}}),
162
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,left:0,width:size*.4,height:w,borderRadius:w,backgroundColor:color}})]})}function MapPinGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),ring=size*.62;/* @__PURE__ */
154
163
  return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
155
164
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:w*1.4,height:w*1.4,borderRadius:w,backgroundColor:color}})}),
156
165
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:size*.04,width:ring*.5,height:ring*.5,borderRightWidth:w,borderBottomWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:size,color:color,testID:testID}){let half=size*.36;/* @__PURE__ */
157
166
  return jsxRuntime.jsx(reactNative.View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:0,height:0,marginLeft:size*.12,borderLeftWidth:size*.78,borderTopWidth:half,borderBottomWidth:half,borderLeftColor:color,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:size,color:color,testID:testID}){/* @__PURE__ */
158
167
  return jsxRuntime.jsx(reactNative.View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.5,height:size*.5,backgroundColor:color}})})}function Ring({size:size,strokeWidth:strokeWidth,color:color,children:children}){/* @__PURE__ */
159
- return jsxRuntime.jsx(reactNative.View,{style:[box(size),{borderRadius:size/2,borderWidth:strokeWidth??reactNative.StyleSheet.hairlineWidth,borderColor:color}],children:children})}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return chatMotion(theme)}var NEWTON_ITERATIONS=8;function bezierComponent(t,a1,a2){return((1-3*a2+3*a1)*t+(3*a2-6*a1))*t*t+3*a1*t}function bezierSlope(t,a1,a2){return 3*(1-3*a2+3*a1)*t*t+2*(3*a2-6*a1)*t+3*a1}function bezierEasing(curve){let[x1,y1,x2,y2]=curve;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<NEWTON_ITERATIONS;i+=1){let slope=bezierSlope(t,x1,x2);if(slope===0)break;t-=(bezierComponent(t,x1,x2)-x)/slope}return bezierComponent(Math.min(1,Math.max(0,t)),y1,y2)}}var STANDARD=bezierEasing(CHAT_EASING.standard),OUT_QUAD=bezierEasing(CHAT_EASING.outQuad),OUT=bezierEasing(CHAT_EASING.out);function useAnimatedValue(initial){let ref=react.useRef(null);return ref.current===null&&(ref.current=new reactNative.Animated.Value(initial)),ref.current}function useFadeIn(durationMs,options={}){let risePx=options.risePx??0,delayMs=options.delayMs??0,value=useAnimatedValue(durationMs>0?0:1);return react.useEffect(()=>{if(durationMs<=0)return;let timing=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?reactNative.Animated.sequence([reactNative.Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),react.useMemo(()=>({opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})}]}),[value,risePx])}function FadePresence({visible:visible,inMs:inMs,outMs:outMs,style:style,children:children}){let[mounted,setMounted]=react.useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return react.useEffect(()=>{if(visible){setMounted(true);let animation2=reactNative.Animated.timing(opacity,{toValue:1,duration:Math.max(0,inMs),easing:STANDARD,useNativeDriver:true});return animation2.start(),()=>animation2.stop()}if(!mounted)return;if(outMs<=0){setMounted(false);return}let animation=reactNative.Animated.timing(opacity,{toValue:0,duration:outMs,easing:STANDARD,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&setMounted(false)}),()=>animation.stop()},[visible,mounted,inMs,outMs,opacity]),!mounted&&!visible?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[style,{opacity:opacity}],children:children})}var AT_REST=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function useBubbleEnter(animate,motion){let[durationMs]=react.useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);react.useEffect(()=>{if(durationMs<=0)return;let animation=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT,useNativeDriver:true});return animation.start(),()=>animation.stop()},[durationMs,value]);let fromScale=motion.bubbleFromScale,risePx=motion.bubbleRisePx;return react.useMemo(()=>run?{opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})},{scale:value.interpolate({inputRange:[0,1],outputRange:[fromScale,1]})}]}:AT_REST,[run,value,risePx,fromScale])}function useEnteringRows(rows){let verdicts=react.useRef(null),head=react.useRef(null),first=rows[0]?.id??null;if(verdicts.current===null||head.current!==first){let opened=verdicts.current===null;verdicts.current=new Map(rows.map(row=>[row.id,opened&&row.pending===true])),head.current=first}let map=verdicts.current;for(let row of rows)map.has(row.id)||map.set(row.id,true);return react.useCallback(id=>map.get(id)===true,[map])}var PRESS_SCALE_HIT_SLOP=12;function PressScale({style:style,containerStyle:containerStyle,children:children,onPressIn:onPressIn,onPressOut:onPressOut,hitSlop:hitSlop,...pressable}){let motion=useChatMotion(),scale=useAnimatedValue(1),animate=react.useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||reactNative.Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
168
+ return jsxRuntime.jsx(reactNative.View,{style:[box(size),{borderRadius:size/2,borderWidth:strokeWidth??reactNative.StyleSheet.hairlineWidth,borderColor:color}],children:children})}function ArrowUpGlyph({size:size,color:color,strokeWidth:strokeWidth,testID:testID}){let w=stroke(size,strokeWidth),head=size*.46;/* @__PURE__ */
169
+ return jsxRuntime.jsxs(reactNative.View,{style:box(size),testID:testID,...HIDDEN,children:[
170
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.16,bottom:size*.12,width:w,borderRadius:w,backgroundColor:color}}),
171
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.16+w/2,width:head,height:head,borderLeftWidth:w,borderTopWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
172
+ return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
173
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.8,height:size*.6,marginTop:-size*.12,borderWidth:w,borderColor:color,borderRadius:size*.14}}),
174
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:size*.1,left:size*.22,width:size*.2,height:size*.2,borderLeftWidth:w,borderBottomWidth:w,borderColor:color}})]})}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return chatMotion(theme)}var NEWTON_ITERATIONS=8;function bezierComponent(t,a1,a2){return((1-3*a2+3*a1)*t+(3*a2-6*a1))*t*t+3*a1*t}function bezierSlope(t,a1,a2){return 3*(1-3*a2+3*a1)*t*t+2*(3*a2-6*a1)*t+3*a1}function bezierEasing(curve){let[x1,y1,x2,y2]=curve;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<NEWTON_ITERATIONS;i+=1){let slope=bezierSlope(t,x1,x2);if(slope===0)break;t-=(bezierComponent(t,x1,x2)-x)/slope}return bezierComponent(Math.min(1,Math.max(0,t)),y1,y2)}}var STANDARD=bezierEasing(CHAT_EASING.standard),OUT_QUAD=bezierEasing(CHAT_EASING.outQuad),OUT=bezierEasing(CHAT_EASING.out);function useAnimatedValue(initial){let ref=react.useRef(null);return ref.current===null&&(ref.current=new reactNative.Animated.Value(initial)),ref.current}function useFadeIn(durationMs,options={}){let risePx=options.risePx??0,delayMs=options.delayMs??0,value=useAnimatedValue(durationMs>0?0:1);return react.useEffect(()=>{if(durationMs<=0)return;let timing=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?reactNative.Animated.sequence([reactNative.Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),react.useMemo(()=>({opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})}]}),[value,risePx])}function FadePresence({visible:visible,inMs:inMs,outMs:outMs,style:style,children:children}){let[mounted,setMounted]=react.useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return react.useEffect(()=>{if(visible){setMounted(true);let animation2=reactNative.Animated.timing(opacity,{toValue:1,duration:Math.max(0,inMs),easing:STANDARD,useNativeDriver:true});return animation2.start(),()=>animation2.stop()}if(!mounted)return;if(outMs<=0){setMounted(false);return}let animation=reactNative.Animated.timing(opacity,{toValue:0,duration:outMs,easing:STANDARD,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&setMounted(false)}),()=>animation.stop()},[visible,mounted,inMs,outMs,opacity]),!mounted&&!visible?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[style,{opacity:opacity}],children:children})}var AT_REST=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function useBubbleEnter(animate,motion){let[durationMs]=react.useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);react.useEffect(()=>{if(durationMs<=0)return;let animation=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT,useNativeDriver:true});return animation.start(),()=>animation.stop()},[durationMs,value]);let fromScale=motion.bubbleFromScale,risePx=motion.bubbleRisePx;return react.useMemo(()=>run?{opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})},{scale:value.interpolate({inputRange:[0,1],outputRange:[fromScale,1]})}]}:AT_REST,[run,value,risePx,fromScale])}function useEnteringRows(rows){let verdicts=react.useRef(null),head=react.useRef(null),first=rows[0]?.id??null;if(verdicts.current===null||head.current!==first){let opened=verdicts.current===null;verdicts.current=new Map(rows.map(row=>[row.id,opened&&row.pending===true])),head.current=first}let map=verdicts.current;for(let row of rows)map.has(row.id)||map.set(row.id,true);return react.useCallback(id=>map.get(id)===true,[map])}var PRESS_SCALE_HIT_SLOP=12;function PressScale({style:style,containerStyle:containerStyle,children:children,onPressIn:onPressIn,onPressOut:onPressOut,hitSlop:hitSlop,...pressable}){let motion=useChatMotion(),scale=useAnimatedValue(1),animate=react.useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||reactNative.Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
160
175
  return jsxRuntime.jsx(reactNative.Pressable,{...pressable,hitSlop:hitSlop??PRESS_SCALE_HIT_SLOP,style:containerStyle,onPressIn:event=>{animate(motion.pressScale),onPressIn?.(event)},onPressOut:event=>{animate(1),onPressOut?.(event)},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[style,{transform:[{scale:scale}]}],children:children})})}function useRevealedText(text3,revealing,motion){let ticking=revealing&&motion.revealTickMs>0,[visible,setVisible]=react.useState(0),latest=react.useRef(text3);return latest.current=text3,react.useEffect(()=>{if(!ticking)return;let id=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.length))},motion.revealTickMs);return()=>clearInterval(id)},[ticking,motion]),ticking?text3.slice(0,Math.min(visible,text3.length)):text3}var layoutAnimationEnabled=false;function animateLayout(motion){motion.layoutMs<=0||(layoutAnimationEnabled||(layoutAnimationEnabled=true,reactNative.Platform.OS==="android"&&typeof reactNative.UIManager.setLayoutAnimationEnabledExperimental=="function"&&reactNative.UIManager.setLayoutAnimationEnabledExperimental(true)),reactNative.LayoutAnimation.configureNext({duration:motion.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function useAnimateLayoutOn(key,motion){let previous=react.useRef(key);previous.current!==key&&(previous.current=key,animateLayout(motion))}var CLOSE_SIZE=36,CLOSE_GLYPH=22,CLOSE_HIT_SLOP=12,CLOSE_TOP_OFFSET=12,CLOSE_RIGHT=16,BACKDROP="#000",CLOSE_BG="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:uri,label:label,onClose:onClose}){let theme=useEverfurTheme(),insets=reactNativeSafeAreaContext.useSafeAreaInsets();return uri===null?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Modal,{visible:true,animationType:theme.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:onClose,children:[
161
176
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,style:styles.backdrop,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:uri},style:styles.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:label,accessibilityIgnoresInvertColors:true})}),
162
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=reactNative.StyleSheet.create({backdrop:{flex:1,backgroundColor:BACKDROP,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:CLOSE_RIGHT},closeButton:{width:CLOSE_SIZE,height:CLOSE_SIZE,borderRadius:CLOSE_SIZE/2,backgroundColor:CLOSE_BG,alignItems:"center",justifyContent:"center"}});var TAIL_SIZE=12,TILE_MIN_WIDTH=80,TILE_ICON_SIZE=44,TILE_GLYPH=22,BUBBLE_SHADOW_OPACITY=.14,BUBBLE_SHADOW_RADIUS=18,BUBBLE_SHADOW_OFFSET_Y=8,TILE_LABEL=/* @__PURE__ */Object.freeze({photo:CHAT_COPY.attachmentPhoto,camera:CHAT_COPY.attachmentCamera});function AttachmentPickerPopover({sources:sources,full:full,onPick:onPick,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
177
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=reactNative.StyleSheet.create({backdrop:{flex:1,backgroundColor:BACKDROP,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:CLOSE_RIGHT},closeButton:{width:CLOSE_SIZE,height:CLOSE_SIZE,borderRadius:CLOSE_SIZE/2,backgroundColor:CLOSE_BG,alignItems:"center",justifyContent:"center"}});var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}var FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
178
+ return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str4=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str4(o.upload_id),uploadUrl=str4(o.upload_url),s3Key=str4(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
179
+ return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str4(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight2=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed2=false,publish2=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed2&&inFlight2.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight2.add(id),run(row).finally(()=>{inFlight2.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed2||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed2||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed2||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed2||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed2||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed2=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=react.useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef,scopeEpoch,maxPerMessage,options.transport]),scoped=react.useMemo(()=>options.queue??build(),[options.queue,build]),disposed2=react.useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=react.useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;react.useEffect(()=>{if(queue!==options.queue){if(disposed2.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed2.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=react.useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=react.useState(null),add=react.useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=react.useCallback(id=>queue.retry(id),[queue]),remove=react.useCallback(id=>queue.remove(id),[queue]),clear=react.useCallback(()=>queue.clear(),[queue]),dismissRejected=react.useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return react.useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}function useChatDraft(send,conversationId,seed){let[state,setState]=react.useState({send:send,conversationId:conversationId,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId);react.useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh2=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId,text:fresh2?seed:text3,seeded:fresh2?seed:seeded}})},[send,conversationId,seed]);let setDraft=react.useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId,text:text3,seeded:previous.seeded})),[send,conversationId]);return[belongs?state.text:"",setDraft]}function usePersistedDraft(store,conversationId,draft,setDraft){let latest=react.useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=react.useRef(null),[settled,setSettled]=react.useState(null);react.useEffect(()=>{if(store===void 0)return;let key=`${conversationId??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId));if(!live)return;let stored2=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored2.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored2),setSettled(key)})(),()=>{live=false}},[store,conversationId]),react.useEffect(()=>{store===void 0||settled!==`${conversationId??""}`||callHost(()=>store.write(conversationId,draft))},[store,conversationId,draft,settled])}var TAIL_SIZE=12,TILE_MIN_WIDTH=80,TILE_ICON_SIZE=44,TILE_GLYPH=22,BUBBLE_SHADOW_OPACITY=.14,BUBBLE_SHADOW_RADIUS=18,BUBBLE_SHADOW_OFFSET_Y=8,TILE_LABEL=/* @__PURE__ */Object.freeze({photo:CHAT_COPY.attachmentPhoto,camera:CHAT_COPY.attachmentCamera});function AttachmentPickerPopover({sources:sources,full:full,onPick:onPick,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
163
180
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.anchor,pointerEvents:"box-none",children:[
164
181
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles2.dismissLayer,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closeAttachmentPicker,onPress:onClose}),
165
182
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.bubble,children:[
@@ -172,21 +189,26 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles2.anchor,pointerEvents:"box
172
189
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:row.previewUri},style:styles2.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),uploading?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.uploadingOverlay,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:theme.color.surface})}):null,flash?/* @__PURE__ */jsxRuntime.jsx(SuccessFlash,{styles:styles2,onDone:()=>setFlash(false)}):null]})}),failed?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),style:styles2.failedOverlay,onPress:()=>onRetry(row.id),children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.failedInner,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}):null,
173
190
  /* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),hitSlop:6,containerStyle:styles2.removeSlot,style:styles2.removeButton,onPress:()=>onRemove(row.id),children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:REMOVE_GLYPH,color:theme.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:styles2,onDone:onDone}){let theme=useEverfurTheme(),motion=useChatMotion(),opacity=react.useRef(null);opacity.current===null&&(opacity.current=new reactNative.Animated.Value(0));let value=opacity.current;return react.useEffect(()=>{let animation=reactNative.Animated.sequence([reactNative.Animated.timing(value,{toValue:1,duration:SUCCESS_FLASH_FADE_IN_MS,useNativeDriver:true}),reactNative.Animated.delay(motion.uploadFlashMs),reactNative.Animated.timing(value,{toValue:0,duration:SUCCESS_FLASH_FADE_OUT_MS,useNativeDriver:true})]);return animation.start(({finished:finished})=>{finished&&onDone()}),()=>animation.stop()},[value,motion.uploadFlashMs,onDone]),/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{pointerEvents:"none",style:[styles2.successOverlay,{opacity:value}],children:/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}function SentImages({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles3(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
174
191
  return jsxRuntime.jsx(reactNative.View,{style:single?styles2.sentSingle:styles2.sentGrid,children:images.map((image,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onPress:()=>onPreview(image),children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:image.uri},style:single?styles2.singleImage:styles2.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${image.uri}-${index}`))})}function makeStyles3(theme){let c=theme.color,t=theme.type;return reactNative.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:THUMB_SIZE,height:THUMB_SIZE,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:CARD_RADIUS,overflow:"hidden",backgroundColor:c.composerFill,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:withAlpha(theme.color.brandInk,UPLOADING_ALPHA)??theme.color.brandSofter},successOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:SUCCESS_OVERLAY},failedOverlay:{...ABSOLUTE_FILL,borderRadius:CARD_RADIUS,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:FAILED_OVERLAY},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:REMOVE_SIZE,height:REMOVE_SIZE,borderRadius:REMOVE_SIZE/2,backgroundColor:REMOVE_BG,borderWidth:1.5,borderColor:c.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:SINGLE_IMAGE,height:SINGLE_IMAGE,borderRadius:SINGLE_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND},gridImage:{width:GRID_IMAGE,height:GRID_IMAGE,borderRadius:GRID_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND}})}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="chat attachment upload: the file handle has no uri",FAILED="chat attachment upload failed";function filePartOf(file){return{uri:file.uri,name:sanitizeFilename(file.name),type:file.mimeType}}function createRnChatAttachmentTransport(options={}){/* @__PURE__ */
175
- return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=react.useState(null);react.useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=react.useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=react.useState(null),wanted=request!==null&&module===null;return react.useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>Promise.resolve(bookingExperience__namespace));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
176
- return jsxRuntime.jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid2(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid2(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid2(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=react.useState(null);if(react.useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=react.useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch,opts.controller]),preflightController=react.useRef(controller);preflightController.current=controller;let scope=react.useMemo(()=>({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}),[runtime,userRef,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=react.useState(IDLE2),inFlight2=react.useRef(null),scopeRef=react.useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=react.useRef(controller);controllerRef.current=controller;let availableRef=react.useRef(available);availableRef.current=available;let start=react.useCallback((petRef,visit)=>{if(inFlight2.current)return inFlight2.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef===void 0?defaultPet:petRef;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight2.current===tracked&&(inFlight2.current=null)});return inFlight2.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=react.useCallback((petRef,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef===void 0?defaultPet:petRef,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=react.useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=react.useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}var defaultOpenUrl=url=>reactNative.Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=react.useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET=44,BUSY_OPACITY=.6;function VetVisitButton(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles4(theme),[theme]),settling=react.useRef(false);if(!visit.available)/* @__PURE__ */
192
+ return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}var SPINNER_DELAY_MS=300,THANKS_VISIBLE_MS=3e3,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET=44,INPUT_MAX_HEIGHT=120,BUBBLE_MAX_WIDTH="88%",BUBBLE_MAX_WIDTH_CAP=520,HALF_STEP=2,BUBBLE_EDGE_WIDTH=.5,BUBBLE_LEAD_USER=1.5,BUBBLE_LEAD_ASSISTANT=1.6,PENDING_OPACITY=.6,COMPOSER_MIN_HEIGHT=56,COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_RIGHT=5,COMPOSER_PADDING_VERTICAL=5,INPUT_MIN_HEIGHT=36,INPUT_LINE_HEIGHT=20,APP_BODY_SIZE=14,SEND_CONTROL_SIZE=MIN_TOUCH_TARGET,TEXT_ACTION_HIT_SLOP=4,SEND_GLYPH_SIZE=24,STOP_GLYPH_SIZE=22,SEND_DISABLED_OPACITY=.4,ATTACH_CONTROL_SIZE=MIN_TOUCH_TARGET,ATTACH_GLYPH_SIZE=20,ATTACH_DISABLED_OPACITY=.4,EMPTY_MIN_HEIGHT=480,FOLLOW_UP_HEADING_SIZE=12,FOLLOW_UP_HEADING_TRACKING=.72,FOLLOW_UP_ROW_MIN_HEIGHT=48,RULE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,EMPTY_PADDING_TOP="12%",ASSISTANT_AVATAR_SIZE=20;function useChatTheme(){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles4(theme),[theme]);return{theme:theme,styles:styles2}}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,userLine=Math.round(t.size.body*BUBBLE_LEAD_USER),assistantLine=Math.round(t.size.body*BUBBLE_LEAD_ASSISTANT),inputLine=Math.round(INPUT_LINE_HEIGHT*t.size.body/APP_BODY_SIZE),rule=c.borderRingCream,slots=theme.slots;return reactNative.StyleSheet.create({container:{flex:1,minHeight:MIN_SURFACE_HEIGHT,backgroundColor:c.chatGround},body:{flex:1},centered:{minHeight:MIN_SURFACE_HEIGHT,flexGrow:1,alignItems:"center",justifyContent:"center",padding:s.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:EMPTY_PADDING_TOP,paddingHorizontal:s.lg,paddingBottom:s.lg,minHeight:EMPTY_MIN_HEIGHT,gap:s.lg},errorText:{...face(theme,"regular"),fontSize:t.size.subtitle,lineHeight:t.size.subtitle*t.lineHeight.snug,color:c.danger,textAlign:"center",marginBottom:s.md},retryButton:{minHeight:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,alignItems:"center",justifyContent:"center",paddingHorizontal:s.xl,paddingVertical:s.sm,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},retryLabel:{...face(theme,"medium"),color:c.onPrimary,fontSize:t.size.body,...slotText(slots.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.sm,backgroundColor:c.surfaceCream},setupNoticeText:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption,flexShrink:1},turnNotice:{gap:s.xs,padding:s.md,borderRadius:r.lg,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,alignItems:"flex-start",...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...headingFace(theme,"bold"),color:c.text.primary,fontSize:t.size.body,...slotText(slots.card)},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,...slotText(slots.card)},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.body},setupNoticeAction:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.caption},reconnectingCaption:{...face(theme,"medium"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*t.lineHeight.relaxed)},list:{flex:1},listContent:{padding:s.lg,gap:s.xl},rowBlock:{gap:s.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:s.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:BUBBLE_MAX_WIDTH,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP,backgroundColor:c.bubbleUser,...c.primaryEdge!==c.primary&&c.bubbleUser===c.primary?{borderWidth:BUBBLE_EDGE_WIDTH,borderColor:c.primaryEdge}:{},borderRadius:r.lg,borderBottomRightRadius:r.xs,...slotBox(slots.userBubble,BUBBLE_EDGE_WIDTH)},bubbleAssistant:slots.assistantBubble?.backgroundColor===void 0?{...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)}:{paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP,borderRadius:r.lg,...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)},bubbleVet:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP,backgroundColor:c.bubbleVet,borderRadius:r.lg,borderTopLeftRadius:r.xs,...slotBox(slots.vetBubble,BUBBLE_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{...face(theme,"regular"),color:c.onPrimary,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.userBubble)},bubbleTextAssistant:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:assistantLine,...slotText(slots.assistantBubble)},bubbleTextVet:{...face(theme,"regular"),color:c.onBubbleVet,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.vetBubble)},assistantName:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,marginBottom:s.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:s.sm,marginBottom:s.xs},assistantAvatar:{width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:ASSISTANT_AVATAR_SIZE/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:s.sm,marginBottom:s.xs},vetSender:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},vetTime:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption},bubbleBold:face(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(theme,"mono"),followUps:{alignSelf:"stretch",marginTop:s.md},followUpsHeading:{...face(theme,"monoBold"),color:c.text.muted,fontSize:FOLLOW_UP_HEADING_SIZE,textTransform:"uppercase",letterSpacing:FOLLOW_UP_HEADING_TRACKING,paddingBottom:s.sm,borderBottomWidth:RULE_WIDTH,borderBottomColor:rule},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:RULE_WIDTH,borderTopColor:rule},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.md,minHeight:FOLLOW_UP_ROW_MIN_HEIGHT,paddingVertical:s.sm+HALF_STEP,...slots.chip?.backgroundColor!==void 0||slots.chip?.borderColor!==void 0?{paddingHorizontal:s.md}:{},...slotBox(slots.chip)},followUpText:{...face(theme,"bold"),flex:1,color:c.brandInk,fontSize:t.size.bodyTight,...slotText(slots.chip)},composerOuter:{position:"relative"},composer:{marginHorizontal:s.md,marginTop:s.xs,minHeight:COMPOSER_MIN_HEIGHT,justifyContent:"center",paddingLeft:s.sm,paddingRight:COMPOSER_PADDING_RIGHT,paddingVertical:COMPOSER_PADDING_VERTICAL,backgroundColor:c.composerFill,borderWidth:COMPOSER_BORDER_WIDTH,borderColor:c.composerBorder,borderRadius:r.pill,...slotBox(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerRow:{flexDirection:"row",alignItems:"center",gap:s.xs,minHeight:INPUT_MIN_HEIGHT},attachControl:{width:ATTACH_CONTROL_SIZE,height:ATTACH_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:ATTACH_DISABLED_OPACITY},input:{flex:1,minHeight:INPUT_MIN_HEIGHT,maxHeight:INPUT_MAX_HEIGHT,paddingHorizontal:0,paddingVertical:0,...face(theme,"regular"),fontSize:t.size.body,lineHeight:inputLine,color:c.text.primary,...slotText(slots.composerInput)},sendControl:{minHeight:SEND_CONTROL_SIZE,minWidth:SEND_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},sendDisc:{width:SEND_CONTROL_SIZE,height:SEND_CONTROL_SIZE,borderRadius:SEND_CONTROL_SIZE/2,alignItems:"center",justifyContent:"center",...slotBox(slots.sendButton)},sendControlDisabled:{opacity:SEND_DISABLED_OPACITY},footnote:{...face(theme,"regular"),color:c.text.muted,fontSize:FOOTNOTE_SIZE,lineHeight:FOOTNOTE_LINE,textAlign:"center",marginTop:s.sm,marginBottom:s.xs,paddingHorizontal:s.lg},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),DEFAULT_MAX_PER_MESSAGE=1,COMPACT_HEIGHT=52,COMPACT_RING=1.5,COMPACT_DISC=40,COMPACT_ARROW=20,COMPACT_DIM_OPACITY=.3;function composerPlaceholder(branded,petName,petPlaceholder){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:forPet(CHAT_COPY.placeholder,petName)}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=react.useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??DEFAULT_MAX_PER_MESSAGE,transport:transport}),bound=react.useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
193
+ return jsxRuntime.jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName,compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false}){let{theme:theme,styles:styles2}=useChatTheme(),compactStyles=react.useMemo(()=>makeCompactStyles(theme),[theme]),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed);usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft);let[pickerOpen,setPickerOpen]=react.useState(false),[pickFailed,setPickFailed]=react.useState(false);react.useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=composerPlaceholder(theme.meta.placeholder,petName,petPlaceholder),uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=react.useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(text3,{imageS3Keys:keys}),attachments.state.clear()):send(text3),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,attachments,onStage]),onStop=react.useCallback(()=>{stop()},[stop]),pickFrom=react.useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),isOverLimit=react.useMemo(()=>[...draft.trim()].length>MESSAGE_MAX_CHARS,[draft]),sendDisabled=isOverLimit||sendBlocked||draft.trim().length===0,sendDimmed=isOverLimit||sendBlocked||dimEmptySend&&draft.trim().length===0,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk,compactInk=theme.slots.sendButton?.textColor??theme.color.surface;/* @__PURE__ */
194
+ return jsxRuntime.jsxs(reactNative.View,{style:styles2.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsxRuntime.jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
195
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:compact?[styles2.composer,compactStyles.bar]:styles2.composer,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(AttachmentStrip,{attachments:rows,rejected:pickFailed?PICK_FAILED:attachments.state.rejected,uploadFailed:uploadFailed,onRetry:attachments.state.retry,onRemove:attachments.state.remove,onPreview:row=>onPreview({uri:row.previewUri,label:row.filename})}):null,
196
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.composerRow,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles2.attachControl,slotsFull?styles2.attachControlDisabled:null],onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsxRuntime.jsx(UploadGlyph,{size:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:theme.color.brandInk,strokeWidth:1.75})}):null,
197
+ /* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles2.input,value:draft,onChangeText:setDraft,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",...SUBMIT_ON_RETURN,blurOnSubmit:false,multiline:true,editable:true}),isStreaming?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles2.sendControl,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:compact?compactStyles.disc:styles2.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsxRuntime.jsx(StopGlyph,{size:compact?COMPACT_ARROW:STOP_GLYPH_SIZE,color:compact?compactInk:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles2.sendControl,sendDimmed?compact?compactStyles.dimmed:styles2.sendControlDisabled:null],children:compact?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:compactStyles.disc,testID:"everfur-send-disc",children:/* @__PURE__ */jsxRuntime.jsx(ArrowUpGlyph,{size:COMPACT_ARROW,color:compactInk,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),SUBMIT_ON_RETURN=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function makeCompactStyles(theme){let c=theme.color,slot=theme.slots.sendButton;return reactNative.StyleSheet.create({bar:{minHeight:COMPACT_HEIGHT,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:COMPACT_RING,borderColor:theme.slots.composerInput?.borderColor??c.text.primary},disc:{width:COMPACT_DISC,height:COMPACT_DISC,borderRadius:COMPACT_DISC/2,alignItems:"center",justifyContent:"center",backgroundColor:slot?.backgroundColor??c.text.primary},dimmed:{opacity:COMPACT_DIM_OPACITY}})}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=react.useState(null);react.useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=react.useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=react.useState(null),wanted=request!==null&&module===null;return react.useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>Promise.resolve(bookingExperience__namespace));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
198
+ return jsxRuntime.jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=react.useState(null);if(react.useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=react.useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch,opts.controller]),preflightController=react.useRef(controller);preflightController.current=controller;let scope=react.useMemo(()=>({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}),[runtime,userRef,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=react.useState(IDLE2),inFlight2=react.useRef(null),scopeRef=react.useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=react.useRef(controller);controllerRef.current=controller;let availableRef=react.useRef(available);availableRef.current=available;let start=react.useCallback((petRef,visit)=>{if(inFlight2.current)return inFlight2.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef===void 0?defaultPet:petRef;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight2.current===tracked&&(inFlight2.current=null)});return inFlight2.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=react.useCallback((petRef,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef===void 0?defaultPet:petRef,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=react.useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=react.useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=react.useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit,joinVisit:joinVisit}}var defaultOpenUrl=url=>reactNative.Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=react.useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET2=44,BUSY_OPACITY=.6;function VetVisitButton(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles5(theme),[theme]),settling=react.useRef(false);if(!visit.available)/* @__PURE__ */
177
199
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[null,
178
200
  /* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
179
201
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
180
202
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{if(!(busy||settling.current)){if(!redirecting){let request={...petRef!==void 0?{petRef:petRef}:{},...usState!==void 0?{usState:usState}:{},...visitRef!=null?{visitRef:visitRef,intent:intent??null}:{}};openVetVisitInApp(request,onStartInApp)===null&&callHost(onError,"unavailable",null);return}settling.current=true,(visitRef==null?visit.open():visit.openVisit(visitRef,intent??null)).then(result=>{result.opened?callHost(onOpened,result.flowId??null):result.reason!=="cancelled"&&callHost(onError,result.reason,result.error)}).finally(()=>{settling.current=false})}},accessibilityRole:"button",accessibilityLabel:text3,accessibilityState:{busy:busy,disabled:busy},style:[styles2.button,busy?styles2.busy:null,style],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.label,labelStyle],children:text3})}),
181
- /* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]})}function makeStyles4(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandImage({uri:uri,label:label,decorative:decorative=false,style:style,resizeMode:resizeMode="contain",fallback:fallback=null,onError:onError,testID:testID}){let image=useBrandImage(uri);if(uri===null||!image.shown)return fallback;let a11y=decorative?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...label===void 0?{}:{accessibilityLabel:label}};/* @__PURE__ */
203
+ /* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]})}function makeStyles5(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandImage({uri:uri,label:label,decorative:decorative=false,style:style,resizeMode:resizeMode="contain",fallback:fallback=null,onError:onError,testID:testID}){let image=useBrandImage(uri);if(uri===null||!image.shown)return fallback;let a11y=decorative?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...label===void 0?{}:{accessibilityLabel:label}};/* @__PURE__ */
182
204
  return jsxRuntime.jsx(reactNative.Image,{source:{uri:uri},style:style,resizeMode:resizeMode,...a11y,onError:()=>{image.onError(),onError?.()},...testID===void 0?{}:{testID:testID}})}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var UNMEASURED=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),NO_BALANCE=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function balanceHeaderSides(m,reserved,logoWidth){if(m.row===null||m.leading===null||m.trailing===null)return NO_BALANCE;let difference=Math.abs(m.leading-m.trailing);if(difference<.5)return NO_BALANCE;let centre=m.row-reserved-m.leading-m.trailing,spare=Math.min(difference,Math.max(0,centre-logoWidth));return spare<.5?NO_BALANCE:m.leading<m.trailing?{leading:m.leading+spare,trailing:void 0}:{leading:void 0,trailing:m.trailing+spare}}function nextMeasures(prev,key,width){let old=prev[key];return old!==null&&Math.abs(old-width)<.5?prev:{...prev,[key]:width}}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same(c.brand,compiled.brand)&&same(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
183
205
  /* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
184
206
  /* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
185
207
  /* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
186
208
  /* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
187
209
  /* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
188
- /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}function letterSize(size){return Math.max(12,Math.round(size*.42))}function PetDisc({pet:pet,size:size,ringStroke:ringStroke}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles5(theme),[theme]),inner=size-ringStroke*2,palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),fontSize=letterSize(inner);/* @__PURE__ */
189
- return jsxRuntime.jsx(Ring,{size:size,strokeWidth:ringStroke,color:theme.color.mark,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.disc,{width:inner,height:inner,borderRadius:inner/2},palette===null?styles2.discEmpty:{backgroundColor:palette.background}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles2.letter,{fontSize:fontSize,lineHeight:Math.round(fontSize*1.2),color:palette===null?theme.color.text.muted:palette.foreground}],children:palette===null?getInitial(null):palette.initial})})})}function makeStyles5(theme){return reactNative.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:theme.color.brandSoft},letter:{...face(theme,"bold"),textAlign:"center",includeFontPadding:false}})}function sheetSlotBox(slot,borderWidth){let{borderRadius:borderRadius,...box2}=slotBox(slot,borderWidth);return borderRadius===void 0?box2:{...box2,borderTopLeftRadius:borderRadius,borderTopRightRadius:borderRadius}}function drawerSlotBox(slot,borderWidth){let{backgroundColor:backgroundColor,borderColor:borderColor,borderWidth:width,borderRadius:borderRadius}=slotBox(slot,borderWidth);return{...backgroundColor===void 0?{}:{backgroundColor:backgroundColor},...borderColor===void 0?{}:{borderRightColor:borderColor,borderRightWidth:width??1},...borderRadius===void 0?{}:{borderTopRightRadius:borderRadius,borderBottomRightRadius:borderRadius}}}var ROW_RING_SIZE=48,ROW_RING_STROKE=2,LIST_MAX_HEIGHT=320,PANEL_MAX_HEIGHT="80%",BACKDROP2="rgba(17,17,17,0.45)",CHECK_SIZE=18,PANEL_RADIUS=22,CLOSE_RADIUS=12,META_TRACKING=.4,MIN_TOUCH_TARGET2=44;function petDisplayName(pet){return pet?.name?.trim()||CHAT_COPY.yourPet}function PetSwitcherSheet({visible:visible,pets:pets,activePetRef:activePetRef,onSelect:onSelect,onAddPet:onAddPet=null,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles6(theme),[theme]);return visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"fade",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.root,children:[
210
+ /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}function letterSize(size){return Math.max(12,Math.round(size*.42))}function PetDisc({pet:pet,size:size,ringStroke:ringStroke}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles6(theme),[theme]),inner=size-ringStroke*2,palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),fontSize=letterSize(inner);/* @__PURE__ */
211
+ return jsxRuntime.jsx(Ring,{size:size,strokeWidth:ringStroke,color:theme.color.mark,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.disc,{width:inner,height:inner,borderRadius:inner/2},palette===null?styles2.discEmpty:{backgroundColor:palette.background}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles2.letter,{fontSize:fontSize,lineHeight:Math.round(fontSize*1.2),color:palette===null?theme.color.text.muted:palette.foreground}],children:palette===null?getInitial(null):palette.initial})})})}function makeStyles6(theme){return reactNative.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:theme.color.brandSoft},letter:{...face(theme,"bold"),textAlign:"center",includeFontPadding:false}})}function sheetSlotBox(slot,borderWidth){let{borderRadius:borderRadius,...box2}=slotBox(slot,borderWidth);return borderRadius===void 0?box2:{...box2,borderTopLeftRadius:borderRadius,borderTopRightRadius:borderRadius}}function drawerSlotBox(slot,borderWidth){let{backgroundColor:backgroundColor,borderColor:borderColor,borderWidth:width,borderRadius:borderRadius}=slotBox(slot,borderWidth);return{...backgroundColor===void 0?{}:{backgroundColor:backgroundColor},...borderColor===void 0?{}:{borderRightColor:borderColor,borderRightWidth:width??1},...borderRadius===void 0?{}:{borderTopRightRadius:borderRadius,borderBottomRightRadius:borderRadius}}}var ROW_RING_SIZE=48,ROW_RING_STROKE=2,LIST_MAX_HEIGHT=320,PANEL_MAX_HEIGHT="80%",BACKDROP2="rgba(17,17,17,0.45)",CHECK_SIZE=18,PANEL_RADIUS=22,CLOSE_RADIUS=12,META_TRACKING=.4,MIN_TOUCH_TARGET3=44;function petDisplayName(pet){return pet?.name?.trim()||CHAT_COPY.yourPet}function PetSwitcherSheet({visible:visible,pets:pets,activePetRef:activePetRef,onSelect:onSelect,onAddPet:onAddPet=null,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles7(theme),[theme]);return visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"fade",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.root,children:[
190
212
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,onPress:onClose,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.backdrop})}),
191
213
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.panel,accessibilityViewIsModal:true,children:[
192
214
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:CHAT_COPY.yourPets}),
@@ -198,7 +220,7 @@ return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel
198
220
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.meta,numberOfLines:1,children:isActive?`${CHAT_COPY.activePrefix}${meta}`:meta})]}),isActive?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:CHECK_SIZE,color:theme.color.brandInk}):null]},pet.petRef)})}),onAddPet!==null?/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addAnotherPet,style:styles2.addRow,onPress:onAddPet,children:[
199
221
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.addDisc,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.addPlus,children:"+"})}),
200
222
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.addLabel,children:CHAT_COPY.addAnotherPet})]}):null,
201
- /* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.closeText,children:CHAT_COPY.close})})]})]})}):null}function makeStyles6(theme){let c=theme.color,r=theme.radius,dialogText=slotText(theme.slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:BACKDROP2},panel:{backgroundColor:c.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:PANEL_RADIUS,borderTopRightRadius:PANEL_RADIUS,gap:14,maxHeight:PANEL_MAX_HEIGHT,...sheetSlotBox(theme.slots.dialog)},title:{...headingFace(theme,"bold"),fontSize:18,lineHeight:22,color:c.brandInk,...dialogText},list:{maxHeight:LIST_MAX_HEIGHT,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:MIN_TOUCH_TARGET2,paddingHorizontal:8},addDisc:{width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:ROW_RING_STROKE,borderStyle:"dashed",borderColor:c.brandBorder,backgroundColor:c.surfaceCream},addPlus:{...face(theme,"bold"),fontSize:20,lineHeight:22,color:c.brandInk},addLabel:{...face(theme,"bold"),fontSize:15,lineHeight:20,color:c.text.primary,...dialogText},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface},rowActive:{borderColor:c.brandInk,backgroundColor:c.brandSoft},copy:{flex:1,gap:2},name:{...face(theme,"bold"),fontSize:15,lineHeight:18,color:c.text.primary},meta:{...face(theme,"monoBold"),fontSize:11,lineHeight:13,color:c.text.muted,textTransform:"uppercase",letterSpacing:META_TRACKING},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:CLOSE_RADIUS,backgroundColor:c.brandSoft},closeText:{...face(theme,"bold"),color:c.brandInk,fontSize:13,lineHeight:16,letterSpacing:META_TRACKING}})}var MIN_TOUCH_TARGET3=44,ICON_BUTTON_SIZE=36,MENU_GLYPH_SIZE=22,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,UNREAD_DOT_INSET=6,HEADER_AVATAR_SIZE=35,HEADER_RING_STROKE=1.75,ADD_BADGE_SIZE=12.4,ADD_BADGE_BORDER=.5,ADD_BADGE_GLYPH=8,LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,ROW_PADDING=16,CENTRE_GAP=8;function headerPet(pets,petRef){return headerPetOf(pets,petRef)}function ChatHeader({pets:pets,petRef:petRef,historyUnread:historyUnread,onOpenHistory:onOpenHistory,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles7(theme),[theme]),[switcherOpen,setSwitcherOpen]=react.useState(false),shown=headerPet(pets.pets,petRef),canSwitch=pets.pets.length>=2,shownPetRef=petRef??shown?.petRef??null,name=petDisplayName(shown),[measures,setMeasures]=react.useState(UNMEASURED),measure=react.useCallback(key=>event=>{let width=event.nativeEvent.layout.width;setMeasures(prev=>nextMeasures(prev,key,width))},[]),onRowLayout=react.useMemo(()=>measure("row"),[measure]),onLeadingLayout=react.useMemo(()=>measure("leading"),[measure]),onTrailingLayout=react.useMemo(()=>measure("trailing"),[measure]),reserved=2*ROW_PADDING+2*(theme.slots.header?.borderColor!==void 0?1:0)+2*CENTRE_GAP,sideMins=balanceHeaderSides(measures,reserved,LOGO_MAX_WIDTH),select=next=>{setSwitcherOpen(false),pets.setActivePet(next),callHost(onPetChange,next)},addPet=onAddPet===void 0?null:()=>{setSwitcherOpen(false),callHost(onAddPet)};/* @__PURE__ */
223
+ /* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.closeText,children:CHAT_COPY.close})})]})]})}):null}function makeStyles7(theme){let c=theme.color,r=theme.radius,dialogText=slotText(theme.slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:BACKDROP2},panel:{backgroundColor:c.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:PANEL_RADIUS,borderTopRightRadius:PANEL_RADIUS,gap:14,maxHeight:PANEL_MAX_HEIGHT,...sheetSlotBox(theme.slots.dialog)},title:{...headingFace(theme,"bold"),fontSize:18,lineHeight:22,color:c.brandInk,...dialogText},list:{maxHeight:LIST_MAX_HEIGHT,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:MIN_TOUCH_TARGET3,paddingHorizontal:8},addDisc:{width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:ROW_RING_STROKE,borderStyle:"dashed",borderColor:c.brandBorder,backgroundColor:c.surfaceCream},addPlus:{...face(theme,"bold"),fontSize:20,lineHeight:22,color:c.brandInk},addLabel:{...face(theme,"bold"),fontSize:15,lineHeight:20,color:c.text.primary,...dialogText},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface},rowActive:{borderColor:c.brandInk,backgroundColor:c.brandSoft},copy:{flex:1,gap:2},name:{...face(theme,"bold"),fontSize:15,lineHeight:18,color:c.text.primary},meta:{...face(theme,"monoBold"),fontSize:11,lineHeight:13,color:c.text.muted,textTransform:"uppercase",letterSpacing:META_TRACKING},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:CLOSE_RADIUS,backgroundColor:c.brandSoft},closeText:{...face(theme,"bold"),color:c.brandInk,fontSize:13,lineHeight:16,letterSpacing:META_TRACKING}})}var MIN_TOUCH_TARGET4=44,ICON_BUTTON_SIZE=36,MENU_GLYPH_SIZE=22,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,UNREAD_DOT_INSET=6,HEADER_AVATAR_SIZE=35,HEADER_RING_STROKE=1.75,ADD_BADGE_SIZE=12.4,ADD_BADGE_BORDER=.5,ADD_BADGE_GLYPH=8,LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,ROW_PADDING=16,CENTRE_GAP=8;function headerPet(pets,petRef){return headerPetOf(pets,petRef)}function ChatHeader({pets:pets,petRef:petRef,historyUnread:historyUnread,onOpenHistory:onOpenHistory,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles8(theme),[theme]),[switcherOpen,setSwitcherOpen]=react.useState(false),shown=headerPet(pets.pets,petRef),canSwitch=pets.pets.length>=2,shownPetRef=petRef??shown?.petRef??null,name=petDisplayName(shown),[measures,setMeasures]=react.useState(UNMEASURED),measure=react.useCallback(key=>event=>{let width=event.nativeEvent.layout.width;setMeasures(prev=>nextMeasures(prev,key,width))},[]),onRowLayout=react.useMemo(()=>measure("row"),[measure]),onLeadingLayout=react.useMemo(()=>measure("leading"),[measure]),onTrailingLayout=react.useMemo(()=>measure("trailing"),[measure]),reserved=2*ROW_PADDING+2*(theme.slots.header?.borderColor!==void 0?1:0)+2*CENTRE_GAP,sideMins=balanceHeaderSides(measures,reserved,LOGO_MAX_WIDTH),select=next=>{setSwitcherOpen(false),pets.setActivePet(next),callHost(onPetChange,next)},addPet=onAddPet===void 0?null:()=>{setSwitcherOpen(false),callHost(onAddPet)};/* @__PURE__ */
202
224
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.row,onLayout:onRowLayout,children:[
203
225
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.leading,sideMins.leading===void 0?null:{minWidth:sideMins.leading}],children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sideContent,onLayout:onLeadingLayout,children:/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:historyUnread?`${CHAT_COPY.openHistoryNative}${CHAT_COPY.newReplySuffix}`:CHAT_COPY.openHistoryNative,containerStyle:styles2.iconSlot,style:styles2.iconButton,onPress:onOpenHistory,children:[
204
226
  /* @__PURE__ */jsxRuntime.jsx(MenuGlyph,{size:MENU_GLYPH_SIZE,color:theme.slots.header?.textColor??theme.color.text.primary,strokeWidth:2}),historyUnread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot,pointerEvents:"none"}):null]})})}),
@@ -208,7 +230,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles2.row,onLayout:onRowLayout,
208
230
  /* @__PURE__ */jsxRuntime.jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE}),
209
231
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsxRuntime.jsx(PlusGlyph,{size:ADD_BADGE_GLYPH,color:theme.color.brandInk,strokeWidth:2})})]}):pets.loading&&shown===null?
210
232
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.avatarWrap,accessible:true,accessibilityLabel:CHAT_COPY.yourPet,children:/* @__PURE__ */jsxRuntime.jsx(Ring,{size:HEADER_AVATAR_SIZE,strokeWidth:HEADER_RING_STROKE,color:theme.color.mark,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.placeholderDisc})})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:shown===null?CHAT_COPY.yourPet:name,children:/* @__PURE__ */jsxRuntime.jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE})})})]})}),
211
- /* @__PURE__ */jsxRuntime.jsx(PetSwitcherSheet,{visible:switcherOpen,pets:pets.pets,activePetRef:shown?.petRef??null,onSelect:select,onAddPet:addPet,onClose:()=>setSwitcherOpen(false)})]})}function makeStyles7(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2,header=theme.slots.header;return reactNative.StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET3,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:ROW_PADDING,paddingVertical:10,backgroundColor:c.surface,...slotBox(header)},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:header?.backgroundColor??c.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:theme.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:CENTRE_GAP,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var MIN_TOUCH_TARGET4=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles8(theme),[theme]),[reason,setReason]=react.useState(null),[note,setNote]=react.useState(""),[pending,setPending]=react.useState(false),[failed,setFailed]=react.useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
233
+ /* @__PURE__ */jsxRuntime.jsx(PetSwitcherSheet,{visible:switcherOpen,pets:pets.pets,activePetRef:shown?.petRef??null,onSelect:select,onAddPet:addPet,onClose:()=>setSwitcherOpen(false)})]})}function makeStyles8(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2,header=theme.slots.header;return reactNative.StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET4,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:ROW_PADDING,paddingVertical:10,backgroundColor:c.surface,...slotBox(header)},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:header?.backgroundColor??c.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:theme.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:CENTRE_GAP,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var MIN_TOUCH_TARGET5=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles9(theme),[theme]),[reason,setReason]=react.useState(null),[note,setNote]=react.useState(""),[pending,setPending]=react.useState(false),[failed,setFailed]=react.useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
212
234
  return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"slide",onRequestClose:skip,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:reactNative.Platform.OS==="ios"?"padding":void 0,style:styles2.root,children:[
213
235
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles2.scrim,onPress:skip,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y}),
214
236
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
@@ -226,7 +248,12 @@ return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel
226
248
  /* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles2.input,placeholder:CHAT_COPY.feedbackNotesPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.feedbackNotesPlaceholder,value:note,onChangeText:setNote,multiline:true,editable:!pending}),note.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[styles2.counter,overLimit?styles2.counterOver:null],children:`${[...note].length}/${FEEDBACK_NOTES_MAX_CHARS}`}):null]}),failed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.failed,accessibilityRole:"alert",children:CHAT_COPY.feedbackFailed}):null,
227
249
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[
228
250
  /* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSubmit,accessibilityState:{busy:pending,disabled:pending||overLimit},disabled:pending||overLimit,style:[styles2.submit,pending||overLimit?styles2.submitDisabled:null],onPress:()=>{submit()},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.submitLabel,children:CHAT_COPY.feedbackSubmit})}),
229
- /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles2.skip,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles8(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight,...dialogText},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted,...dialogText},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,reactNative.StyleSheet.hairlineWidth)},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary,...slotText(slots.chip)},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top",...slotBox(slots.input,1),...slotText(slots.input)},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var PANEL_WIDTH_FRACTION=.88,PANEL_MAX_WIDTH=420,PANEL_PADDING_TOP=58,BACKDROP3="rgba(17,17,17,0.28)",ACTIVE_ROW_ALPHA=.15,ACTION_SIZE=14,LABEL_SIZE=12,CONTROL_SIZE=44,CLOSE_GLYPH2=16,CARD_RADIUS2=14,ERROR_RADIUS=12,SEARCH_GLYPH=14,UNREAD_DOT=8,HALF_STEP=2,END_REACHED_THRESHOLD=.5,STANDARD2=bezierEasing(CHAT_EASING.standard);function drawerPanelWidth(windowWidth){return Math.min(Math.round(windowWidth*PANEL_WIDTH_FRACTION),PANEL_MAX_WIDTH)}function HistoryDrawer({chat:chat,history:history}){let[mounted,setMounted]=react.useState(history.open),onHidden=react.useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsxRuntime.jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles9(theme),[theme]),motion=useChatMotion(),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:width}=reactNative.useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=react.useRef(null);progress.current===null&&(progress.current=new reactNative.Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;react.useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=reactNative.Animated.timing(value,{toValue:open?1:0,duration:motion.drawerMs,easing:STANDARD2,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&!open&&onHidden()}),()=>animation.stop()},[open,value,motion.drawerMs,onHidden]);let translateX=value.interpolate({inputRange:[0,1],outputRange:[-panelWidth,0]}),rows=history.filtered,hasNoConversations=history.rows.length===0,complete=history.cursor===null&&!history.loading&&history.error===null,empty=hasNoConversations&&history.loading?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
251
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles2.skip,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles9(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight,...dialogText},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted,...dialogText},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,reactNative.StyleSheet.hairlineWidth)},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary,...slotText(slots.chip)},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top",...slotBox(slots.input,1),...slotText(slots.input)},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var BAR_SIZE=15,UNREAD_DOT=8;function HistoryBar({bar:bar,history:history,empty:empty,unread:unread,extra:extra}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles10(theme),[theme]),count=history.cursor===null?history.rows.length:0,icon=name=>{let render=bar.renderIcon;return render===void 0?null:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>render(name),fallback:null})};/* @__PURE__ */
252
+ return jsxRuntime.jsxs(reactNative.View,{style:styles2.bar,testID:"everfur-history-bar",children:[
253
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:count>0?`${bar.chats} ${count}`:bar.chats,accessibilityState:{expanded:history.open},onPress:history.open?history.close:history.show,style:styles2.control,children:[icon("history"),
254
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.label,children:bar.chats}),count>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.count,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles2.countText,children:String(count)})}):null,unread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.dot,testID:"everfur-chat-history-bar-unread"}):null]}),bar.extra??null,extra??null,
255
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.spacer}),empty?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:bar.newChat,onPress:history.newConversation,style:styles2.control,children:[icon("edit"),
256
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.label,children:bar.newChat})]})]})}function makeStyles10(theme){let c=theme.color,s=theme.space;return reactNative.StyleSheet.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:MIN_TOUCH_TARGET},label:{...face(theme,"bold"),fontSize:BAR_SIZE,color:c.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,alignItems:"center"},countText:{...face(theme,"bold"),fontSize:theme.type.size.caption,color:c.text.primary},dot:{width:UNREAD_DOT,height:UNREAD_DOT,borderRadius:UNREAD_DOT/2,backgroundColor:c.danger},spacer:{flexGrow:1}})}var PANEL_WIDTH_FRACTION=.88,PANEL_MAX_WIDTH=420,PANEL_PADDING_TOP=58,BACKDROP3="rgba(17,17,17,0.28)",ACTIVE_ROW_ALPHA=.15,ACTION_SIZE=14,LABEL_SIZE=12,CONTROL_SIZE=44,CLOSE_GLYPH2=16,CARD_RADIUS2=14,ERROR_RADIUS=12,SEARCH_GLYPH=14,UNREAD_DOT2=8,HALF_STEP2=2,END_REACHED_THRESHOLD=.5,STANDARD2=bezierEasing(CHAT_EASING.standard);function drawerPanelWidth(windowWidth){return Math.min(Math.round(windowWidth*PANEL_WIDTH_FRACTION),PANEL_MAX_WIDTH)}function HistoryDrawer({chat:chat,history:history}){let[mounted,setMounted]=react.useState(history.open),onHidden=react.useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsxRuntime.jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles11(theme),[theme]),motion=useChatMotion(),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:width}=reactNative.useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=react.useRef(null);progress.current===null&&(progress.current=new reactNative.Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;react.useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=reactNative.Animated.timing(value,{toValue:open?1:0,duration:motion.drawerMs,easing:STANDARD2,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&!open&&onHidden()}),()=>animation.stop()},[open,value,motion.drawerMs,onHidden]);let translateX=value.interpolate({inputRange:[0,1],outputRange:[-panelWidth,0]}),rows=history.filtered,hasNoConversations=history.rows.length===0,complete=history.cursor===null&&!history.loading&&history.error===null,empty=hasNoConversations&&history.loading?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
230
257
  /* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:styles2.emptyTitle.color}),
231
258
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyBody,children:HISTORY_COPY.loading})]}):hasNoConversations&&history.error!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,children:[
232
259
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyTitle,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
@@ -249,29 +276,80 @@ return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animation
249
276
  /* @__PURE__ */jsxRuntime.jsx(reactNative.FlatList,{data:rows,keyExtractor:row=>row.id,renderItem:({item:item})=>/* @__PURE__ */jsxRuntime.jsx(Row,{row:item,active:item.id===chat.conversationId,disabled:history.loading,styles:styles2,onPress:()=>{history.resume(item.id)}}),contentContainerStyle:rows.length===0?styles2.listEmpty:styles2.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:empty,ListFooterComponent:footer,onEndReached:history.loadMore,onEndReachedThreshold:END_REACHED_THRESHOLD})]})})]})})}function Row({row:row,active:active,disabled:disabled,styles:styles2,onPress:onPress}){let unread=row.unreadCount!==null&&row.unreadCount>0,meta=conversationMeta(row);/* @__PURE__ */
250
277
  return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:active,disabled:disabled},disabled:disabled,style:[styles2.item,active?styles2.itemActive:null],onPress:onPress,children:[
251
278
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.itemRow,children:[
252
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles9(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary,cardText=slotText(slots.card);return reactNative.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:BACKDROP3},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:c.surface,paddingHorizontal:s.lg,borderRightWidth:reactNative.StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md,...drawerSlotBox(slots.dialog,reactNative.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:s.md},header:{flexDirection:"row",alignItems:"center",gap:s.sm},heading:{...headingFace(theme,"bold"),flex:1,fontSize:t.size.subtitle,color:ink,...slotText(slots.dialog)},newChat:{minHeight:CONTROL_SIZE,justifyContent:"center",paddingHorizontal:s.xs},newChatLabel:{...face(theme,"bold"),fontSize:ACTION_SIZE,color:c.brandInk},closeButton:{width:CONTROL_SIZE,height:CONTROL_SIZE,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:s.sm,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm+HALF_STEP,borderWidth:1,borderColor:c.borderRingCream,...slotBox(slots.input,1)},searchInput:{...face(theme,"regular"),flex:1,fontSize:t.size.bodyTight,color:c.text.primary,padding:0,...slotText(slots.input)},countLabel:{...face(theme,"mono"),fontSize:LABEL_SIZE,color:c.text.muted},list:{gap:s.xs,paddingBottom:s.xl},listEmpty:{flexGrow:1},item:{paddingVertical:s.sm+HALF_STEP,paddingHorizontal:s.sm,borderRadius:theme.radius.md,gap:HALF_STEP},itemActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??c.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:s.sm},itemTitle:{...face(theme,"bold"),flex:1,fontSize:t.size.bodyTight,color:ink},itemMeta:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted},unreadDot:{width:UNREAD_DOT,height:UNREAD_DOT,borderRadius:UNREAD_DOT/2,backgroundColor:c.danger},errorCard:{borderRadius:ERROR_RADIUS,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.danger,backgroundColor:c.surface,padding:s.md},errorText:{...face(theme,"regular"),fontSize:t.size.caption,color:c.danger},emptyCard:{borderRadius:CARD_RADIUS2,padding:s.md+HALF_STEP,gap:s.xs+HALF_STEP,backgroundColor:c.surfaceSubtle,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.borderRingCream,...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(theme,"bold"),fontSize:t.size.bodyTight,color:ink,...cardText},emptyBody:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary,...cardText},noMatch:{...face(theme,"regular"),fontSize:t.size.bodyTight,color:c.text.muted,paddingVertical:s.sm},retrySlot:{marginTop:s.sm,alignSelf:"flex-start"},retryButton:{borderRadius:theme.radius.pill,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm,borderWidth:1,borderColor:c.brandInk,...slotBox(slots.primaryButton)},retryText:{...face(theme,"bold"),fontSize:t.size.caption,color:c.brandInk,...slotText(slots.primaryButton)},loadMoreFooter:{paddingVertical:s.md+HALF_STEP,alignItems:"center"},loadMoreLabel:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted}})}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number"&&Number.isFinite(hostOffset),probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset}:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset,onLayout:onLayout}:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function useKeyboardOpen(){let[open,setOpen]=react.useState(false);return react.useEffect(()=>{let keyboard=reactNative.Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=reactNative.Platform.OS==="ios",shown=keyboard.addListener(ios?"keyboardWillShow":"keyboardDidShow",()=>setOpen(true)),hidden=keyboard.addListener(ios?"keyboardWillHide":"keyboardDidHide",()=>setOpen(false));return()=>{shown.remove(),hidden.remove()}},[]),open}var SLOT_MIN_CONTRAST=4.5;var SLOT_MIN_BORDER_CONTRAST=3;function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
253
- return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}function withBannerSlot(tier,slot){if(slot===void 0)return tier;let next={...tier};return slot.backgroundColor!==void 0&&(next.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(next.borderColor=slot.borderColor),slot.textColor!==void 0&&(next.textColor=slot.textColor,next.reasonColor=slot.textColor),/* @__PURE__ */Object.freeze(next)}function chatVetVisitOptions(petRef,vet){let options={entry:"chat",petRef:petRef};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var CARD_EDGE=.75,EMERGENCY_EDGE=1.5,EMERGENCY_EDGE_ALPHA=.4,CARD_PAD_X_EXTRA=4,REASON_LEAD=1.5,CLOSE_SIZE2=22,CLOSE_GLYPH3=14,CLOSE_HIT_SLOP2=8,INFO_GLYPH=20,INFO_HIT_SLOP=10,PIN_GLYPH=13,PILL_LABEL_SIZE=12,PILL_LABEL_LINE=15,ACTION_MIN_HEIGHT=44,ACTION_PAD_X=14,ACTION_EDGE=1.25,ACTION_LABEL_SIZE=14,ACTION_GLYPH_GAP=6,COMPACT_REASON_LINES=2;function tierPaint(theme,tier){let c=theme.color;if(tier.level==="emergency")return{card:{backgroundColor:c.badgeBgCritical,borderColor:withAlpha(c.danger,EMERGENCY_EDGE_ALPHA)??c.danger,borderWidth:EMERGENCY_EDGE},label:c.danger,reason:c.text.primary,close:c.danger,action:{fill:c.surface,edge:c.danger,ink:c.danger}};let radius=theme.slots.banner?.borderRadius;return{card:{backgroundColor:tier.backgroundColor,borderColor:tier.borderColor,borderWidth:CARD_EDGE,...radius===void 0?{}:{borderRadius:radius}},label:tier.textColor,reason:tier.reasonColor,close:tier.textColor,action:null}}function UrgencyBanner({surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:compact=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles10(theme),[theme]),motion=useChatMotion(),tier=surface.tier===null?null:themedUrgencyTier(surface.tier,theme),source=surface.source;/* @__PURE__ */
279
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles11(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary,cardText=slotText(slots.card);return reactNative.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:BACKDROP3},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:c.surface,paddingHorizontal:s.lg,borderRightWidth:reactNative.StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md,...drawerSlotBox(slots.dialog,reactNative.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:s.md},header:{flexDirection:"row",alignItems:"center",gap:s.sm},heading:{...headingFace(theme,"bold"),flex:1,fontSize:t.size.subtitle,color:ink,...slotText(slots.dialog)},newChat:{minHeight:CONTROL_SIZE,justifyContent:"center",paddingHorizontal:s.xs},newChatLabel:{...face(theme,"bold"),fontSize:ACTION_SIZE,color:c.brandInk},closeButton:{width:CONTROL_SIZE,height:CONTROL_SIZE,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:s.sm,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,paddingHorizontal:s.md+HALF_STEP2,paddingVertical:s.sm+HALF_STEP2,borderWidth:1,borderColor:c.borderRingCream,...slotBox(slots.input,1)},searchInput:{...face(theme,"regular"),flex:1,fontSize:t.size.bodyTight,color:c.text.primary,padding:0,...slotText(slots.input)},countLabel:{...face(theme,"mono"),fontSize:LABEL_SIZE,color:c.text.muted},list:{gap:s.xs,paddingBottom:s.xl},listEmpty:{flexGrow:1},item:{paddingVertical:s.sm+HALF_STEP2,paddingHorizontal:s.sm,borderRadius:theme.radius.md,gap:HALF_STEP2},itemActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??c.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:s.sm},itemTitle:{...face(theme,"bold"),flex:1,fontSize:t.size.bodyTight,color:ink},itemMeta:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted},unreadDot:{width:UNREAD_DOT2,height:UNREAD_DOT2,borderRadius:UNREAD_DOT2/2,backgroundColor:c.danger},errorCard:{borderRadius:ERROR_RADIUS,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.danger,backgroundColor:c.surface,padding:s.md},errorText:{...face(theme,"regular"),fontSize:t.size.caption,color:c.danger},emptyCard:{borderRadius:CARD_RADIUS2,padding:s.md+HALF_STEP2,gap:s.xs+HALF_STEP2,backgroundColor:c.surfaceSubtle,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.borderRingCream,...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(theme,"bold"),fontSize:t.size.bodyTight,color:ink,...cardText},emptyBody:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary,...cardText},noMatch:{...face(theme,"regular"),fontSize:t.size.bodyTight,color:c.text.muted,paddingVertical:s.sm},retrySlot:{marginTop:s.sm,alignSelf:"flex-start"},retryButton:{borderRadius:theme.radius.pill,paddingHorizontal:s.md+HALF_STEP2,paddingVertical:s.sm,borderWidth:1,borderColor:c.brandInk,...slotBox(slots.primaryButton)},retryText:{...face(theme,"bold"),fontSize:t.size.caption,color:c.brandInk,...slotText(slots.primaryButton)},loadMoreFooter:{paddingVertical:s.md+HALF_STEP2,alignItems:"center"},loadMoreLabel:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted}})}function historyDayLabel(iso,now=/* @__PURE__ */new Date,locale){let date2=new Date(iso);if(Number.isNaN(date2.getTime()))return null;let a=new Date(now);a.setHours(0,0,0,0);let b=new Date(date2);b.setHours(0,0,0,0);let days=Math.round((a.getTime()-b.getTime())/864e5);if(days===0||days===1)try{let word=new Intl.RelativeTimeFormat(locale,{numeric:"auto"}).format(-days,"day");return word.charAt(0).toLocaleUpperCase(locale)+word.slice(1)}catch{}return date2.toLocaleDateString(locale,{month:"short",day:"numeric"})}function historyTime(iso,locale){let date2=new Date(iso);return Number.isNaN(date2.getTime())?null:date2.toLocaleTimeString(locale,{hour:"numeric",minute:"2-digit"})}function groupByDay(rows,now=/* @__PURE__ */new Date){let groups=[];for(let row of rows){let day=historyDayLabel(row.updatedAt,now)??"",last=groups[groups.length-1];last!==void 0&&last.day===day?last.rows.push(row):groups.push({day:day,rows:[row]})}return groups}var SCRIM2="rgba(38,37,35,0.38)",SHEET_RADIUS2=28,GRAB_W=40,GRAB_H=5,KICKER_SIZE=11,MONO_SIZE=10.5,ICON_TILE=36,ICON_RADIUS=11,ROW_RADIUS=14,TITLE_SIZE=15,PREVIEW_SIZE=13.5,NEW_CHAT_HEIGHT=52,NEW_CHAT_SIZE=16,UNREAD_DOT3=8,MAX_HEIGHT="80%";function sheetIcon(sheet,name,fallback){let render=sheet?.renderIcon;return render===void 0?fallback:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>render(name),fallback:fallback})}function HistorySheet({chat:chat,history:history,sheet:sheet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles12(theme),[theme]),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),groups=react.useMemo(()=>groupByDay(history.rows),[history.rows]);if(!history.open)return null;let c=theme.color,hostTitle=sheet?.title?.trim(),title=hostTitle!==void 0&&hostTitle!==""?hostTitle:HISTORY_COPY.heading;/* @__PURE__ */
280
+ return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:"slide",onRequestClose:history.close,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.root,children:[
281
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:[ABSOLUTE_FILL,styles2.scrim],onPress:history.close,accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.closeA11y}),
282
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles2.sheet,{paddingBottom:Math.max(40,insets.bottom+theme.space.lg)}],accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
283
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.grab}),
284
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.top,children:[
285
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.kicker,accessibilityRole:"header",children:title}),
286
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.closeA11y,onPress:history.close,style:styles2.close,children:sheetIcon(sheet,"close",/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:22,color:c.text.primary,strokeWidth:2}))})]}),
287
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{style:styles2.scroll,contentContainerStyle:styles2.scrollContent,keyboardShouldPersistTaps:"handled",children:[history.loading&&history.rows.length===0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.state,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
288
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:c.brandInk}),
289
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.mono,children:HISTORY_COPY.loading})]}):null,history.error!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.state,children:[
290
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.stateText,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
291
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.retry,onPress:()=>{history.load()},style:styles2.link,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.linkText,children:HISTORY_COPY.retry})})]}):null,!history.loading&&history.error===null&&history.rows.length===0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.stateText,styles2.state],children:HISTORY_COPY.empty}):null,groups.map(group=>/* @__PURE__ */jsxRuntime.jsxs(react.Fragment,{children:[group.day?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[styles2.mono,styles2.day],children:group.day}):null,group.rows.map(row=>{let current=row.id===chat.conversationId,unread=row.unreadCount!==null&&row.unreadCount>0,time=historyTime(row.updatedAt);/* @__PURE__ */
292
+ return jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:current},onPress:()=>{history.resume(row.id)},style:[styles2.row,current?styles2.rowCurrent:null],children:[
293
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.icon,children:sheetIcon(sheet,"chat",/* @__PURE__ */jsxRuntime.jsx(ChatBubbleGlyph,{size:19,color:c.brandInk,strokeWidth:1.75}))}),
294
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.rowWords,children:[
295
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.rowTitle,numberOfLines:1,children:conversationTitle(row.title)}),row.preview!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.preview,numberOfLines:1,children:row.preview}):null]}),
296
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.rowEnd,children:[time!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[styles2.mono,styles2.time,unread?styles2.timeUnread:null],children:time}):null,unread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot,testID:`everfur-history-sheet-unread-${String(row.id)}`}):null]})]},String(row.id))})]},group.day)),history.cursor!==null&&!history.loadingMore?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.more,onPress:history.loadMore,style:styles2.link,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.linkText,children:HISTORY_COPY.more})}):null]}),
297
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.newChat,onPress:history.newConversation,style:styles2.newChat,children:[sheetIcon(sheet,"edit",/* @__PURE__ */jsxRuntime.jsx(EditGlyph,{size:18,color:c.onPrimary,strokeWidth:1.75})),
298
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.newChatText,children:HISTORY_COPY.newChat})]})]})]})})}function makeStyles12(theme){let c=theme.color,s=theme.space,mono={...face(theme,"mono"),fontSize:MONO_SIZE,letterSpacing:MONO_SIZE*.06,textTransform:"uppercase",color:c.text.muted};return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:SCRIM2},sheet:{maxHeight:MAX_HEIGHT,backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS2,borderTopRightRadius:SHEET_RADIUS2,paddingTop:10,paddingHorizontal:20},grab:{width:GRAB_W,height:GRAB_H,borderRadius:3,backgroundColor:c.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...mono,fontSize:KICKER_SIZE,letterSpacing:KICKER_SIZE*.08,flexShrink:1},close:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:MIN_TOUCH_TARGET/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:s.xs},mono:mono,day:{marginTop:s.lg,marginBottom:s.xs},state:{marginVertical:s.md,gap:s.sm,alignItems:"flex-start"},stateText:{...face(theme,"regular"),fontSize:theme.type.size.body,color:c.text.primary},link:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center"},linkText:{...face(theme,"bold"),fontSize:theme.type.size.body,color:c.brandInk},row:{flexDirection:"row",alignItems:"center",gap:s.md,paddingVertical:10,paddingHorizontal:s.sm,borderRadius:ROW_RADIUS,minHeight:MIN_TOUCH_TARGET},rowCurrent:{backgroundColor:c.surfaceSubtle},icon:{width:ICON_TILE,height:ICON_TILE,borderRadius:ICON_RADIUS,backgroundColor:c.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(theme,"bold"),fontSize:TITLE_SIZE,color:c.text.primary},preview:{...face(theme,"regular"),fontSize:PREVIEW_SIZE,color:c.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:MONO_SIZE*.04,textTransform:"none"},timeUnread:{...face(theme,"monoBold"),color:c.text.primary},unreadDot:{width:UNREAD_DOT3,height:UNREAD_DOT3,borderRadius:UNREAD_DOT3/2,backgroundColor:c.danger},newChat:{marginTop:s.lg,minHeight:NEW_CHAT_HEIGHT,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:s.sm,borderRadius:theme.radius.pill,backgroundColor:c.primary},newChatText:{...face(theme,"bold"),fontSize:NEW_CHAT_SIZE,color:c.onPrimary}})}var HEALTH_PLAN_TOP_CARD_COPY=/* @__PURE__ */Object.freeze({action:who=>who.possessive===null?null:`See ${who.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(focus,ask)=>focus.risk?.lead?`${focus.risk.lead} ${ask}`:`${focus.title}: ${ask}`,close:who=>who.possessive===null?null:`Close ${who.possessive} focus`});function healthPlanPossessive(pet){if(pet.sex==="female")return"her";if(pet.sex==="male")return"his";let name=pet.name?.trim();return name?`${name}'s`:null}function healthPlanTopCard(page,options={}){let focus=page?.page?.focus;if(page===null||focus===void 0||focus.title.trim()===""||focus.kicker.trim()==="")return;let copy={...HEALTH_PLAN_TOP_CARD_COPY,...options.copy},who={pet:page.pet,possessive:healthPlanPossessive(page.pet)},badge=focus.sources?.find(source=>source.label.trim()!=="")?.label,action=options.onOpenPlan===void 0?null:copy.action(who),close=copy.close(who),ask=copy.ask.trim(),onOpenPlan=options.onOpenPlan;return{kicker:focus.kicker,...badge===void 0?{}:{badge:badge},title:focus.title,...focus.risk?.lead?{lead:focus.risk.lead}:{},...focus.risk?.body?{body:focus.risk.body}:{},...action===null||action.trim()===""||onOpenPlan===void 0?{}:{action:{label:action,onPress:onOpenPlan}},...ask===""?{}:{ask:{label:ask,prompt:copy.askPrompt(focus,ask)}},closeLabel:close===null||close.trim()===""?CHAT_COPY.close:close,pill:focus.kicker}}var CARD_RADIUS3=20,CARD_PAD_TOP=14,CARD_PAD=16,TITLE_SIZE2=18,KICKER_SIZE2=15,BADGE_SIZE2=13,BODY_SIZE=15,ASK_SIZE=14.5,CLOSE_GLYPH3=18,DOT=9,PILL_MIN_HEIGHT=36,PILL_PAD_X=14,PILL_SIZE=15,PILL_DOT=8,ACTION_MIN_HEIGHT=40,LEAD=1.35;function TopCard({card:card,open:open,onOpenChange:onOpenChange,ask:ask}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles13(theme),[theme]);if(!open)return null;let closeLabel=card.closeLabel!==void 0&&card.closeLabel.trim()!==""?card.closeLabel:CHAT_COPY.close,action=card.action,question=card.ask,glyph=/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH3,color:theme.color.text.primary,strokeWidth:2});/* @__PURE__ */
299
+ return jsxRuntime.jsxs(reactNative.View,{style:styles2.card,testID:"everfur-top-card",children:[
300
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.kickerRow,children:[
301
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.kicker,children:card.kicker}),card.badge!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.badge,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.badgeText,children:card.badge})}):null,
302
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onOpenChange(false),accessibilityRole:"button",accessibilityLabel:closeLabel,style:styles2.close,testID:"everfur-top-card-close",children:card.renderIcon!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>card.renderIcon?.("close"),fallback:glyph}):glyph})]}),
303
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:card.title}),card.lead!==void 0||card.body!==void 0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.finding,children:[
304
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.dot}),
305
+ /* @__PURE__ */jsxRuntime.jsxs(Text,{style:styles2.findingText,children:[card.lead!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.lead,children:card.lead}):null,card.lead!==void 0&&card.body!==void 0?" ":null,card.body??null]})]}):null,action!==void 0||question!==void 0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[action!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{callHost(action.onPress)},accessibilityRole:"button",accessibilityLabel:action.label,style:styles2.action,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.actionText,children:action.label})}):null,question!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>ask(question.prompt),accessibilityRole:"button",accessibilityLabel:question.label,style:styles2.ask,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.askText,children:question.label})}):null]}):null]})}function TopCardPill({card:card,open:open,onOpenChange:onOpenChange}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles13(theme),[theme]);if(open)return null;let words2=card.pill??card.kicker;/* @__PURE__ */
306
+ return jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onOpenChange(true),accessibilityRole:"button",accessibilityLabel:words2,accessibilityState:{expanded:false},style:styles2.pill,testID:"everfur-top-card-pill",children:[
307
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.pillDot}),
308
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.pillText,numberOfLines:1,children:words2})]})}function makeStyles13(theme){let c=theme.color,s=theme.space;return reactNative.StyleSheet.create({card:{paddingTop:CARD_PAD_TOP,paddingHorizontal:CARD_PAD,paddingBottom:CARD_PAD,borderRadius:CARD_RADIUS3,backgroundColor:c.surface,borderWidth:1,borderColor:c.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:s.sm,minHeight:MIN_TOUCH_TARGET-8},kicker:{...face(theme,"bold"),fontSize:KICKER_SIZE2,color:c.text.primary,flexShrink:1},badge:{marginLeft:"auto",paddingHorizontal:10,paddingVertical:2,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,flexShrink:1},badgeText:{...face(theme,"medium"),fontSize:BADGE_SIZE2,color:c.text.secondary},close:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:MIN_TOUCH_TARGET/2},title:{...headingFace(theme,"bold"),fontSize:TITLE_SIZE2,lineHeight:Math.round(TITLE_SIZE2*LEAD),color:c.text.primary,marginTop:s.xs},finding:{flexDirection:"row",gap:s.sm,marginTop:s.xs+2},dot:{width:DOT,height:DOT,borderRadius:DOT/2,marginTop:7,backgroundColor:c.danger},findingText:{...face(theme,"regular"),flex:1,fontSize:BODY_SIZE,lineHeight:Math.round(BODY_SIZE*1.45),color:c.text.primary},lead:face(theme,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.lg,marginTop:14},action:{minHeight:Math.max(ACTION_MIN_HEIGHT,MIN_TOUCH_TARGET),paddingHorizontal:s.lg,borderRadius:theme.radius.pill,backgroundColor:c.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(theme,"bold"),fontSize:BODY_SIZE,color:c.onPrimary},ask:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center",maxWidth:"100%"},askText:{...face(theme,"bold"),fontSize:ASK_SIZE,color:c.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:s.sm,minHeight:Math.max(PILL_MIN_HEIGHT,MIN_TOUCH_TARGET),paddingHorizontal:PILL_PAD_X,borderRadius:theme.radius.pill,backgroundColor:c.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:PILL_DOT,height:PILL_DOT,borderRadius:PILL_DOT/2,backgroundColor:c.danger},pillText:{...face(theme,"bold"),fontSize:PILL_SIZE,color:c.danger,flexShrink:1}})}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number"&&Number.isFinite(hostOffset),probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset}:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset,onLayout:onLayout}:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function useKeyboardOpen(){let[open,setOpen]=react.useState(false);return react.useEffect(()=>{let keyboard=reactNative.Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=reactNative.Platform.OS==="ios",shown=keyboard.addListener(ios?"keyboardWillShow":"keyboardDidShow",()=>setOpen(true)),hidden=keyboard.addListener(ios?"keyboardWillHide":"keyboardDidHide",()=>setOpen(false));return()=>{shown.remove(),hidden.remove()}},[]),open}var SLOT_MIN_CONTRAST=4.5;var SLOT_MIN_BORDER_CONTRAST=3;function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
309
+ return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}function withBannerSlot(tier,slot){if(slot===void 0)return tier;let next={...tier};return slot.backgroundColor!==void 0&&(next.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(next.borderColor=slot.borderColor),slot.textColor!==void 0&&(next.textColor=slot.textColor,next.reasonColor=slot.textColor),/* @__PURE__ */Object.freeze(next)}function chatVetVisitOptions(petRef,vet){let options={entry:"chat",petRef:petRef};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var CARD_EDGE=.75,EMERGENCY_EDGE=1.5,EMERGENCY_EDGE_ALPHA=.4,CARD_PAD_X_EXTRA=4,REASON_LEAD=1.5,CLOSE_SIZE2=22,CLOSE_GLYPH4=14,CLOSE_HIT_SLOP2=8,INFO_GLYPH=20,INFO_HIT_SLOP=10,PIN_GLYPH=13,PILL_LABEL_SIZE=12,PILL_LABEL_LINE=15,ACTION_MIN_HEIGHT2=44,ACTION_PAD_X=14,ACTION_EDGE=1.25,ACTION_LABEL_SIZE=14,ACTION_GLYPH_GAP=6,COMPACT_REASON_LINES=2;function tierPaint(theme,tier){let c=theme.color;if(tier.level==="emergency")return{card:{backgroundColor:c.badgeBgCritical,borderColor:withAlpha(c.danger,EMERGENCY_EDGE_ALPHA)??c.danger,borderWidth:EMERGENCY_EDGE},label:c.danger,reason:c.text.primary,close:c.danger,action:{fill:c.surface,edge:c.danger,ink:c.danger}};let radius=theme.slots.banner?.borderRadius;return{card:{backgroundColor:tier.backgroundColor,borderColor:tier.borderColor,borderWidth:CARD_EDGE,...radius===void 0?{}:{borderRadius:radius}},label:tier.textColor,reason:tier.reasonColor,close:tier.textColor,action:null}}function UrgencyBanner({surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:compact=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles14(theme),[theme]),motion=useChatMotion(),tier=surface.tier===null?null:themedUrgencyTier(surface.tier,theme),source=surface.source;/* @__PURE__ */
254
310
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
255
311
  /* @__PURE__ */jsxRuntime.jsx(FadePresence,{visible:surface.showBanner&&tier!==null,inMs:motion.bannerInMs,outMs:motion.bannerOutMs,style:styles2.pinned,children:tier!==null&&source!==null?/* @__PURE__ */jsxRuntime.jsx(BannerCard,{tier:tier,reason:source.reason,surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}):null}),
256
312
  /* @__PURE__ */jsxRuntime.jsx(FadePresence,{visible:surface.showCompactIcon,inMs:motion.iconInMs,outMs:motion.iconOutMs,style:styles2.indicatorRow,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.showLatestVetAlert,hitSlop:INFO_HIT_SLOP,onPress:surface.expand,children:/* @__PURE__ */jsxRuntime.jsx(InfoGlyph,{size:INFO_GLYPH,color:theme.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:tier,reason:reason,surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}){let theme=useEverfurTheme(),paint=tierPaint(theme,tier),builtIn=/* @__PURE__ */jsxRuntime.jsx(VetAction,{tier:tier,paint:paint,petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles2}),vetAction=surface.showVetAction?renderVetAction!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderVetAction(tier.level),fallback:builtIn,resetKey:tier.level}):builtIn:null,poison=paint.action!==null?/* @__PURE__ */jsxRuntime.jsx(PoisonControl,{paint:paint.action,styles:styles2}):null,erLine=tier.level==="emergency"&&onFindVet===void 0;/* @__PURE__ */
257
313
  return jsxRuntime.jsxs(reactNative.View,{accessibilityRole:"alert",style:[styles2.card,paint.card,compact?styles2.cardCompact:null],testID:compact?"chat-urgency-compact":void 0,children:[
258
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.label,{color:paint.label}],children:tier.label}),reason!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.reason,{color:paint.reason}],numberOfLines:compact?COMPACT_REASON_LINES:void 0,accessibilityLabel:compact?reason:void 0,children:reason}):null,erLine?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.reason,styles2.erLine,{color:paint.reason}],children:CHAT_COPY.goToNearestEmergencyVet}):null,vetAction!==null||poison!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[vetAction,poison]}):null,surface.dismissLabel!==null?/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:surface.dismissLabel,hitSlop:CLOSE_HIT_SLOP2,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:surface.dismiss,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH3,color:paint.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:paint,styles:styles2}){let call=()=>{try{reactNative.Linking.openURL(POISON_CONTROL_TEL).catch(()=>{})}catch{}};/* @__PURE__ */
314
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.label,{color:paint.label}],children:tier.label}),reason!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.reason,{color:paint.reason}],numberOfLines:compact?COMPACT_REASON_LINES:void 0,accessibilityLabel:compact?reason:void 0,children:reason}):null,erLine?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.reason,styles2.erLine,{color:paint.reason}],children:CHAT_COPY.goToNearestEmergencyVet}):null,vetAction!==null||poison!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[vetAction,poison]}):null,surface.dismissLabel!==null?/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:surface.dismissLabel,hitSlop:CLOSE_HIT_SLOP2,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:surface.dismiss,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH4,color:paint.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:paint,styles:styles2}){let call=()=>{try{reactNative.Linking.openURL(POISON_CONTROL_TEL).catch(()=>{})}catch{}};/* @__PURE__ */
259
315
  return jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.poisonControlNative,hitSlop:0,style:[styles2.action,{backgroundColor:paint.fill,borderColor:paint.edge}],onPress:call,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:paint.ink}],children:CHAT_COPY.poisonControlNative})})}function VetAction({tier:tier,paint:paint,petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles2}){let theme=useEverfurTheme(),visit=useVetVisit(chatVetVisitOptions(petRef,vet)),busy=visit.status==="opening",hostFinder=!visit.available&&onFindVet!==void 0,onPress=visit.available?()=>{visit.open()}:onFindVet!==void 0?()=>{callHost(onFindVet,tier.level)}:null;if(onPress===null)return null;let action=paint.action;if(action!==null){let label=hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVet,ink2=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??action.ink;/* @__PURE__ */
260
316
  return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},hitSlop:0,style:[styles2.action,{backgroundColor:action.fill,borderColor:action.edge},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
261
317
  /* @__PURE__ */jsxRuntime.jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink2,strokeWidth:1.5}),
262
318
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:ink2}],children:label})]})}let ink=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??tier.textColor;/* @__PURE__ */
263
319
  return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},style:[styles2.findVetButton,{borderColor:tier.borderColor,backgroundColor:tier.pillColor},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
264
320
  /* @__PURE__ */jsxRuntime.jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink,strokeWidth:1.5}),
265
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles10(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return reactNative.StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=react.useCallback(petRef=>handle.setActivePet(petRef),[handle]);return react.useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=reactNative.AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(reactNative.AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=react.useRef(false),scope=react.useRef({send:chat.send,id:chat.conversationId});react.useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var SPINNER_DELAY_MS=300,THANKS_VISIBLE_MS=3e3,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120,BUBBLE_MAX_WIDTH="88%",BUBBLE_MAX_WIDTH_CAP=520,HALF_STEP2=2,BUBBLE_EDGE_WIDTH=.5,BUBBLE_LEAD_USER=1.5,BUBBLE_LEAD_ASSISTANT=1.6,PENDING_OPACITY=.6,COMPOSER_MIN_HEIGHT=56,COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_RIGHT=5,COMPOSER_PADDING_VERTICAL=5,INPUT_MIN_HEIGHT=36,INPUT_LINE_HEIGHT=20,APP_BODY_SIZE=14,SEND_CONTROL_SIZE=MIN_TOUCH_TARGET5,TEXT_ACTION_HIT_SLOP=4,SEND_GLYPH_SIZE=24,STOP_GLYPH_SIZE=22,SEND_DISABLED_OPACITY=.4,ATTACH_CONTROL_SIZE=MIN_TOUCH_TARGET5,ATTACH_GLYPH_SIZE=20,ATTACH_DISABLED_OPACITY=.4,EMPTY_MIN_HEIGHT=480,FOLLOW_UP_HEADING_SIZE=12,FOLLOW_UP_HEADING_TRACKING=.72,FOLLOW_UP_ROW_MIN_HEIGHT=48,RULE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,EMPTY_PADDING_TOP="12%",ASSISTANT_AVATAR_SIZE=20;function useChatTheme(){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles11(theme),[theme]);return{theme:theme,styles:styles2}}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,userLine=Math.round(t.size.body*BUBBLE_LEAD_USER),assistantLine=Math.round(t.size.body*BUBBLE_LEAD_ASSISTANT),inputLine=Math.round(INPUT_LINE_HEIGHT*t.size.body/APP_BODY_SIZE),rule=c.borderRingCream,slots=theme.slots;return reactNative.StyleSheet.create({container:{flex:1,minHeight:MIN_SURFACE_HEIGHT,backgroundColor:c.chatGround},body:{flex:1},centered:{minHeight:MIN_SURFACE_HEIGHT,flexGrow:1,alignItems:"center",justifyContent:"center",padding:s.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:EMPTY_PADDING_TOP,paddingHorizontal:s.lg,paddingBottom:s.lg,minHeight:EMPTY_MIN_HEIGHT,gap:s.lg},errorText:{...face(theme,"regular"),fontSize:t.size.subtitle,lineHeight:t.size.subtitle*t.lineHeight.snug,color:c.danger,textAlign:"center",marginBottom:s.md},retryButton:{minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:s.xl,paddingVertical:s.sm,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},retryLabel:{...face(theme,"medium"),color:c.onPrimary,fontSize:t.size.body,...slotText(slots.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.sm,backgroundColor:c.surfaceCream},setupNoticeText:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption,flexShrink:1},turnNotice:{gap:s.xs,padding:s.md,borderRadius:r.lg,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,alignItems:"flex-start",...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...headingFace(theme,"bold"),color:c.text.primary,fontSize:t.size.body,...slotText(slots.card)},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,...slotText(slots.card)},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET5,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.body},setupNoticeAction:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.caption},reconnectingCaption:{...face(theme,"medium"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*t.lineHeight.relaxed)},list:{flex:1},listContent:{padding:s.lg,gap:s.xl},rowBlock:{gap:s.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:s.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:BUBBLE_MAX_WIDTH,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleUser,...c.primaryEdge!==c.primary&&c.bubbleUser===c.primary?{borderWidth:BUBBLE_EDGE_WIDTH,borderColor:c.primaryEdge}:{},borderRadius:r.lg,borderBottomRightRadius:r.xs,...slotBox(slots.userBubble,BUBBLE_EDGE_WIDTH)},bubbleAssistant:slots.assistantBubble?.backgroundColor===void 0?{...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)}:{paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,borderRadius:r.lg,...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)},bubbleVet:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleVet,borderRadius:r.lg,borderTopLeftRadius:r.xs,...slotBox(slots.vetBubble,BUBBLE_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{...face(theme,"regular"),color:c.onPrimary,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.userBubble)},bubbleTextAssistant:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:assistantLine,...slotText(slots.assistantBubble)},bubbleTextVet:{...face(theme,"regular"),color:c.onBubbleVet,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.vetBubble)},assistantName:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,marginBottom:s.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:s.sm,marginBottom:s.xs},assistantAvatar:{width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:ASSISTANT_AVATAR_SIZE/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:s.sm,marginBottom:s.xs},vetSender:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},vetTime:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption},bubbleBold:face(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(theme,"mono"),followUps:{alignSelf:"stretch",marginTop:s.md},followUpsHeading:{...face(theme,"monoBold"),color:c.text.muted,fontSize:FOLLOW_UP_HEADING_SIZE,textTransform:"uppercase",letterSpacing:FOLLOW_UP_HEADING_TRACKING,paddingBottom:s.sm,borderBottomWidth:RULE_WIDTH,borderBottomColor:rule},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:RULE_WIDTH,borderTopColor:rule},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.md,minHeight:FOLLOW_UP_ROW_MIN_HEIGHT,paddingVertical:s.sm+HALF_STEP2,...slots.chip?.backgroundColor!==void 0||slots.chip?.borderColor!==void 0?{paddingHorizontal:s.md}:{},...slotBox(slots.chip)},followUpText:{...face(theme,"bold"),flex:1,color:c.brandInk,fontSize:t.size.bodyTight,...slotText(slots.chip)},composerOuter:{position:"relative"},composer:{marginHorizontal:s.md,marginTop:s.xs,minHeight:COMPOSER_MIN_HEIGHT,justifyContent:"center",paddingLeft:s.sm,paddingRight:COMPOSER_PADDING_RIGHT,paddingVertical:COMPOSER_PADDING_VERTICAL,backgroundColor:c.composerFill,borderWidth:COMPOSER_BORDER_WIDTH,borderColor:c.composerBorder,borderRadius:r.pill,...slotBox(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerRow:{flexDirection:"row",alignItems:"center",gap:s.xs,minHeight:INPUT_MIN_HEIGHT},attachControl:{width:ATTACH_CONTROL_SIZE,height:ATTACH_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:ATTACH_DISABLED_OPACITY},input:{flex:1,minHeight:INPUT_MIN_HEIGHT,maxHeight:INPUT_MAX_HEIGHT,paddingHorizontal:0,paddingVertical:0,...face(theme,"regular"),fontSize:t.size.body,lineHeight:inputLine,color:c.text.primary,...slotText(slots.composerInput)},sendControl:{minHeight:SEND_CONTROL_SIZE,minWidth:SEND_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},sendDisc:{width:SEND_CONTROL_SIZE,height:SEND_CONTROL_SIZE,borderRadius:SEND_CONTROL_SIZE/2,alignItems:"center",justifyContent:"center",...slotBox(slots.sendButton)},sendControlDisabled:{opacity:SEND_DISABLED_OPACITY},footnote:{...face(theme,"regular"),color:c.text.muted,fontSize:FOOTNOTE_SIZE,lineHeight:FOOTNOTE_LINE,textAlign:"center",marginTop:s.sm,marginBottom:s.xs,paddingHorizontal:s.lg},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles2}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.assistantSender,testID:"everfur-assistant-sender",children:[
266
- /* @__PURE__ */jsxRuntime.jsx(BrandImage,{uri:avatarUrl,decorative:true,style:styles2.assistantAvatar,resizeMode:"cover",onError:image.onError,testID:"everfur-assistant-avatar"}),named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.assistantName,styles2.assistantNameInRow],children:CHAT_COPY.assistantName}):null]}):named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null}var CHECKIN_COPY=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[pending,setPending]=react.useState(null),[error,setError]=react.useState(null),[tapped,setTapped]=react.useState(null),choose=react.useCallback(answer2=>{answerCheckin!==null&&(setPending(answer2),setError(null),answerCheckin(checkin.caseId,answer2).then(result=>{setPending(null),result.ok?setTapped(answer2):setError(result.error)}))},[answerCheckin,checkin.caseId]),answer=tapped??checkin.answer;return{answer:answer,answerable:!isCheckinSettled(checkin),escalated:answer==="worse",pending:pending,error:error,choose:choose}}var MIN_TOUCH_TARGET6=44,PENDING_OPACITY2=.6;function CheckinCard({message:message,checkin:checkin,onAnswer:onAnswer,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles12(theme),[theme]),state=useCheckinCard(checkin,onAnswer),settled=state.answer!==null||state.pending!==null,answerable=onAnswer!==null&&state.answerable,day=checkinDayNumber(checkin.openedAt,checkinDueDay(message));/* @__PURE__ */
321
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles14(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return reactNative.StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT2,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=react.useCallback(petRef=>handle.setActivePet(petRef),[handle]);return react.useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=reactNative.AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(reactNative.AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=react.useRef(false),scope=react.useRef({send:chat.send,id:chat.conversationId});react.useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles2}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.assistantSender,testID:"everfur-assistant-sender",children:[
322
+ /* @__PURE__ */jsxRuntime.jsx(BrandImage,{uri:avatarUrl,decorative:true,style:styles2.assistantAvatar,resizeMode:"cover",onError:image.onError,testID:"everfur-assistant-avatar"}),named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.assistantName,styles2.assistantNameInRow],children:CHAT_COPY.assistantName}):null]}):named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
323
+ return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count){return count===1?`1 ${CHAT_COPY.sourceSingular}`:`${count} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function tileImageUrl(url){return hardenHttpsUrl(url.trim())}function followUpActionsFor(chat,options){if(options?.followUpActions===void 0||chat.isStreaming||chat.status==="error")return[];let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true?[]:hostList(options.followUpActions,{answer:last.text,question:questionFor(chat.messages,last.id),messageId:last.id})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor&&runs.push({kind:"text",text:text3.slice(cursor,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor=match.index+match[0].length}return cursor<text3.length&&runs.push({kind:"text",text:text3.slice(cursor)}),runs}function renderInlineMarkdown(text3,styles2){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
324
+ return jsxRuntime.jsx(Text,{style:styles2.bold,children:run.text},key);case"italic":return styles2.italic?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.italic,children:run.text},key):run.text;case"code":return styles2.code?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.code,children:run.text},key):run.text;default:return run.text}}):text3}var MONO_SIZE2=10.5,BODY_SIZE2=15.5,BODY_LEAD=1.5,CARD_RADIUS4=16,CARD_PAD2=12,TILE=38,TILE_RADIUS=11,CARD_TITLE=15,STAT_SIZE=22,CHIP_HEIGHT=32,CHIP_SIZE=13.5,ROW_RADIUS2=14,ROW_SIZE=15,CHEVRON=16,LABEL_SIZE2=13,PILL_SIZE2=13,PILL_HEIGHT=26,TILE_GLYPH2=20;function useCardStyles(){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles15(theme),[theme]);return{theme:theme,styles:styles2}}function Chevron({options:options,color:color}){let glyph=/* @__PURE__ */jsxRuntime.jsx(ChevronGlyph,{size:CHEVRON,color:color,strokeWidth:2,direction:"right"}),render=options?.renderIcon;return render===void 0?glyph:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>render("chevron"),fallback:glyph})}function AnswerCard({card:card,options:options}){let{theme:theme,styles:styles2}=useCardStyles();if(card.render!==void 0){let render=card.render;/* @__PURE__ */
325
+ return jsxRuntime.jsx(reactNative.View,{style:styles2.card,accessible:false,accessibilityLabel:card.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:render,fallback:null})})}let stat=card.value!==void 0,image=card.tile?.imageUrl!==void 0?tileImageUrl(card.tile.imageUrl):null,body=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[stat?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.tile,children:image!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:image},style:styles2.tileImage,accessibilityIgnoresInvertColors:true}):card.tile?.icon??null}),
326
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.cardWords,children:[
327
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.cardTitle,children:card.title}),card.meta!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.cardMeta,children:card.meta}):null]}),stat?/* @__PURE__ */jsxRuntime.jsxs(Text,{tier:"control",style:styles2.stat,children:[card.value?.amount,card.value?.unit!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.statUnit,children:card.value.unit}):null]}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[card.pill!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.pill,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles2.pillText,numberOfLines:1,children:card.pill.label})}):null,card.onPress!==void 0?/* @__PURE__ */jsxRuntime.jsx(Chevron,{options:options,color:theme.color.text.muted}):null]})]});if(card.onPress!==void 0){let onPress=card.onPress;/* @__PURE__ */
328
+ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{callHost(onPress)},accessibilityRole:"button",accessibilityLabel:card.title,style:styles2.card,children:body})}/* @__PURE__ */
329
+ return jsxRuntime.jsx(reactNative.View,{style:styles2.card,children:body})}function CardsAnswer({message:message,text:text3,streaming:streaming,messages:messages,options:options,sentiment:sentiment,onSentiment:onSentiment,sender:sender,footer:footer,onOpenUrl:onOpenUrl}){let{styles:styles2}=useCardStyles(),context=react.useMemo(()=>({answer:message.text,question:questionFor(messages,message.id),messageId:message.id}),[message.text,message.id,messages]),settled=!streaming&&message.pending!==true,hostCards=settled?hostList(options?.cards,context):[],sources=react.useMemo(()=>settled?toCitationCards(message.citations):[],[settled,message.citations]),byline=options?.byline,chips=options?.feedback!==void 0&&message.responseId!==void 0&&onSentiment!==void 0?options.feedback:null,inline={bold:styles2.bold,italic:styles2.italic,code:styles2.code};/* @__PURE__ */
330
+ return jsxRuntime.jsxs(reactNative.View,{style:styles2.answer,testID:"everfur-answer-cards",children:[byline!==void 0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.byline,children:[byline.icon??null,
331
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.bylineText,children:byline.label})]}):sender,
332
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.body,children:answerParagraphs(text3).flatMap((paragraph,index)=>answerBlocks(paragraph).map((block,at)=>{let key=`${index}-${at}`;return block.kind==="text"?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.paragraph,children:renderInlineMarkdown(block.text,inline)},key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.list,children:block.items.map((item,n)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.listItem,children:[
333
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.paragraph,children:block.ordered?`${block.start+n}.`:"•"}),
334
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.paragraph,styles2.listText],children:renderInlineMarkdown(item,inline)})]},n))},key)}))}),hostCards.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.cards,children:hostCards.map(card=>/* @__PURE__ */jsxRuntime.jsx(AnswerCard,{card:card,options:options},card.key))}):null,sources.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.cards,accessibilityLabel:sourcesLabel(sources.length),children:[
335
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.label,children:sourcesLabel(sources.length)}),sources.map(source=>{let url=source.url;/* @__PURE__ */
336
+ return jsxRuntime.jsx(AnswerCard,{card:{key:source.key,title:source.title,...source.meta!==null?{meta:source.meta}:{},tile:{icon:/* @__PURE__ */jsxRuntime.jsx(SourceTileGlyph,{})},...onOpenUrl!==void 0&&url!==null?{onPress:()=>onOpenUrl(url)}:{}},options:options},source.key)})]}):null,settled&&chips!==null&&onSentiment!==void 0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.feedback,children:[
337
+ /* @__PURE__ */jsxRuntime.jsx(FeedbackChip,{label:chips.helpful,on:sentiment==="up",onPress:()=>onSentiment("up"),styles:styles2}),
338
+ /* @__PURE__ */jsxRuntime.jsx(FeedbackChip,{label:chips.notHelpful,on:sentiment==="down",onPress:()=>onSentiment("down"),styles:styles2})]}):null,settled?footer(chips===null):null]})}function SourceTileGlyph(){let theme=useEverfurTheme();/* @__PURE__ */
339
+ return jsxRuntime.jsx(BookGlyph,{size:TILE_GLYPH2,color:theme.color.brandInk,strokeWidth:1.5})}function FeedbackChip({label:label,on:on,onPress:onPress,styles:styles2}){/* @__PURE__ */
340
+ return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:on},style:[styles2.chip,on?styles2.chipOn:null],hitSlop:(MIN_TOUCH_TARGET-CHIP_HEIGHT)/2,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.chipText,children:label})})}function CardsFollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt,actions:actions,options:options}){let{theme:theme,styles:styles2}=useCardStyles();return prompts.length===0&&actions.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.followUps,accessibilityLabel:CHAT_COPY.followUpsHeadingNative,testID:"everfur-cards-follow-ups",children:[
341
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.label,accessibilityRole:"header",children:CHAT_COPY.followUpsHeadingNative}),actions.map(action=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>{callHost(action.onPress)},accessibilityRole:"button",accessibilityLabel:action.label,style:[styles2.row,styles2.rowAction],children:[action.icon??null,
342
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.rowText,styles2.rowTextAction],children:action.label}),
343
+ /* @__PURE__ */jsxRuntime.jsx(Chevron,{options:options,color:theme.color.text.primary})]},`action:${action.key}`)),prompts.map(prompt=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,style:styles2.row,children:[
344
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.rowText,children:prompt}),
345
+ /* @__PURE__ */jsxRuntime.jsx(Chevron,{options:options,color:theme.color.brandInk})]},prompt))]})}function makeStyles15(theme){let c=theme.color,s=theme.space,mono={...face(theme,"mono"),fontSize:MONO_SIZE2,textTransform:"uppercase",color:c.text.muted},ring={borderWidth:1,borderColor:c.borderRingCream};return reactNative.StyleSheet.create({answer:{gap:s.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...mono,letterSpacing:MONO_SIZE2*.06,flexShrink:1},body:{gap:10},paragraph:{...face(theme,"regular"),fontSize:BODY_SIZE2,lineHeight:Math.round(BODY_SIZE2*BODY_LEAD),color:c.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:s.sm,paddingLeft:s.xs},listText:{flex:1},bold:face(theme,"bold"),italic:{fontStyle:"italic"},code:face(theme,"mono"),cards:{gap:s.sm},card:{flexDirection:"row",alignItems:"center",gap:s.md,padding:CARD_PAD2,borderRadius:CARD_RADIUS4,backgroundColor:c.surface,...ring,minHeight:MIN_TOUCH_TARGET},tile:{width:TILE,height:TILE,borderRadius:TILE_RADIUS,backgroundColor:c.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:TILE,height:TILE},cardWords:{flex:1,minWidth:0},cardTitle:{...face(theme,"bold"),fontSize:CARD_TITLE,lineHeight:Math.round(CARD_TITLE*1.25),color:c.text.primary},cardMeta:{...mono,letterSpacing:MONO_SIZE2*.04,marginTop:3},stat:{...face(theme,"mono"),fontSize:STAT_SIZE,color:c.text.primary},statUnit:{...face(theme,"mono"),fontSize:MONO_SIZE2+2,color:c.text.muted},pill:{minHeight:PILL_HEIGHT,paddingHorizontal:10,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,justifyContent:"center",flexShrink:0},pillText:{...face(theme,"bold"),fontSize:PILL_SIZE2,color:c.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:s.sm,alignItems:"center"},chip:{minHeight:CHIP_HEIGHT,paddingHorizontal:12,borderRadius:theme.radius.pill,...ring,justifyContent:"center"},chipOn:{backgroundColor:c.surfaceSubtle},chipText:{...face(theme,"bold"),fontSize:CHIP_SIZE,color:c.text.primary},followUps:{gap:s.sm,alignSelf:"stretch",marginTop:s.xs},label:{...face(theme,"bold"),fontSize:LABEL_SIZE2,color:c.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:MIN_TOUCH_TARGET,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:ROW_RADIUS2,backgroundColor:c.surface,...ring},rowAction:{},rowText:{...face(theme,"bold"),flex:1,fontSize:ROW_SIZE,lineHeight:Math.round(ROW_SIZE*1.3),color:c.brandInk},rowTextAction:{color:c.text.primary}})}var CHECKIN_COPY=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[pending,setPending]=react.useState(null),[error,setError]=react.useState(null),[tapped,setTapped]=react.useState(null),choose=react.useCallback(answer2=>{answerCheckin!==null&&(setPending(answer2),setError(null),answerCheckin(checkin.caseId,answer2).then(result=>{setPending(null),result.ok?setTapped(answer2):setError(result.error)}))},[answerCheckin,checkin.caseId]),answer=tapped??checkin.answer;return{answer:answer,answerable:!isCheckinSettled(checkin),escalated:answer==="worse",pending:pending,error:error,choose:choose}}var MIN_TOUCH_TARGET6=44,PENDING_OPACITY2=.6;function CheckinCard({message:message,checkin:checkin,onAnswer:onAnswer,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles16(theme),[theme]),state=useCheckinCard(checkin,onAnswer),settled=state.answer!==null||state.pending!==null,answerable=onAnswer!==null&&state.answerable,day=checkinDayNumber(checkin.openedAt,checkinDueDay(message));/* @__PURE__ */
267
346
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onLayout:onLayout,children:[
268
347
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.head,children:[
269
348
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.eyebrow,children:CHECKIN_COPY.eyebrow}),day!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.headDay,children:fillCopy(CHECKIN_COPY.day,{day:day})}):null]}),
270
349
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.question,accessibilityRole:"text",children:message.text}),answerable?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.row,state.pending?styles2.rowPending:null],children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
271
- return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles2.pill,selected?styles2.pillSelected:null],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.pillLabel,selected?styles2.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.logged,children:CHECKIN_COPY.logged}):null,state.escalated?onFindVet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles2.findVet,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.findVetLabel,children:CHECKIN_COPY.findVet})}):petRef?/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.findVet,labelStyle:styles2.findVetLabel}):null:null,checkin.resolutionText?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,reactNative.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,...cardText},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var RULE_WIDTH2=1.5,BODY_GAP=3;function CheckinPastAsk({text:text3,runDueDays:runDueDays,openedAt:openedAt,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles13(theme),[theme]),days=runDueDays.map(dueDay=>checkinDayNumber(openedAt,dueDay)).filter(day=>day!==null),collapsed=runDueDays.length>1;return collapsed&&days.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.row,onLayout:onLayout,children:[
350
+ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles2.pill,selected?styles2.pillSelected:null],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.pillLabel,selected?styles2.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.logged,children:CHECKIN_COPY.logged}):null,state.escalated?onFindVet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles2.findVet,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.findVetLabel,children:CHECKIN_COPY.findVet})}):petRef?/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.findVet,labelStyle:styles2.findVetLabel}):null:null,checkin.resolutionText?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function makeStyles16(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,reactNative.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,...cardText},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var RULE_WIDTH2=1.5,BODY_GAP=3;function CheckinPastAsk({text:text3,runDueDays:runDueDays,openedAt:openedAt,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles17(theme),[theme]),days=runDueDays.map(dueDay=>checkinDayNumber(openedAt,dueDay)).filter(day=>day!==null),collapsed=runDueDays.length>1;return collapsed&&days.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.row,onLayout:onLayout,children:[
272
351
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),
273
- /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.body,children:[days.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.days,children:days.map(day=>fillCopy(CHECKIN_COPY.day,{day:day})).join(CHECKIN_COPY.daySeparator)}):null,collapsed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.question,accessibilityRole:"text",children:text3})]})]})}function makeStyles13(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({row:{flexDirection:"row",paddingVertical:s.xs},rule:{width:RULE_WIDTH2,borderRadius:1,backgroundColor:c.borderHairlineGreen,marginRight:s.md},body:{flex:1,gap:BODY_GAP},days:{...face(theme,"monoMedium"),fontSize:t.size.nano,letterSpacing:t.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase"},question:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:t.size.bodyTight*t.lineHeight.normal,color:c.text.muted}})}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
274
- return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count){return count===1?`1 ${CHAT_COPY.sourceSingular}`:`${count} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles14(theme),[theme]),cards=react.useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=react.useState(false);if(cards.length===0)return null;let count=cards.length;/* @__PURE__ */
352
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.body,children:[days.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.days,children:days.map(day=>fillCopy(CHECKIN_COPY.day,{day:day})).join(CHECKIN_COPY.daySeparator)}):null,collapsed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.question,accessibilityRole:"text",children:text3})]})]})}function makeStyles17(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({row:{flexDirection:"row",paddingVertical:s.xs},rule:{width:RULE_WIDTH2,borderRadius:1,backgroundColor:c.borderHairlineGreen,marginRight:s.md},body:{flex:1,gap:BODY_GAP},days:{...face(theme,"monoMedium"),fontSize:t.size.nano,letterSpacing:t.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase"},question:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:t.size.bodyTight*t.lineHeight.normal,color:c.text.muted}})}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles18(theme),[theme]),cards=react.useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=react.useState(false);if(cards.length===0)return null;let count=cards.length;/* @__PURE__ */
275
353
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.block,children:[
276
354
  /* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count,expanded),accessibilityState:{expanded:expanded},containerStyle:styles2.toggleSlot,style:styles2.togglePill,onPress:()=>setExpanded(current=>!current),children:[
277
355
  /* @__PURE__ */jsxRuntime.jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
@@ -282,57 +360,54 @@ return jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE_
282
360
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.tierDot,{backgroundColor:card.tierColor}]}),
283
361
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.cardTitle,linked?styles2.cardTitleLink:null],numberOfLines:2,children:card.title}),linked?/* @__PURE__ */jsxRuntime.jsx(ArrowUpRightGlyph,{size:LINK_GLYPH,color:theme.color.linkInk,strokeWidth:1.5}):null]}),card.meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.cardMeta,numberOfLines:1,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.cardExcerpt,numberOfLines:3,children:card.excerpt}):null]});if(card.url!==null&&open!==void 0){let url=card.url;/* @__PURE__ */
284
362
  return jsxRuntime.jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:label,style:styles2.card,onPress:()=>open(url),children:inner})}/* @__PURE__ */
285
- return jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles2.card,children:inner})}function makeStyles14(theme){let c=theme.color,s=theme.space,r=theme.radius,size=theme.type.size,cardText=slotText(theme.slots.card);return reactNative.StyleSheet.create({block:{gap:s.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:r.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:s.xs+2,paddingHorizontal:s.md,paddingVertical:s.xs+2,borderRadius:r.pill,backgroundColor:c.brandSoft},toggleLabel:{...face(theme,"monoBold"),fontSize:size.micro,lineHeight:size.micro,letterSpacing:TOGGLE_TRACKING,color:c.brandInk,textTransform:"uppercase"},row:{gap:s.sm,paddingRight:s.xl,paddingTop:s.xs},card:{width:CARD_WIDTH,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface,padding:s.md,gap:s.xs+2,...slotBox(theme.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:s.sm},tierDot:{width:TIER_DOT,height:TIER_DOT,borderRadius:r.pill},cardTitle:{...headingFace(theme,"bold"),flex:1,fontSize:size.bodyTight,lineHeight:TITLE_LINE,color:c.text.primary,letterSpacing:TITLE_TRACKING,...cardText},cardTitleLink:{color:c.linkInk},cardMeta:{...face(theme,"monoMedium"),fontSize:size.nano,lineHeight:META_LINE,letterSpacing:theme.type.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase",...cardText},cardExcerpt:{...face(theme,"regular"),fontSize:size.tiny,lineHeight:EXCERPT_LINE,color:c.text.muted,...cardText}})}var ICON_SIZE=15,ICON_HIT_SLOP=15,THUMB_HIT_SLOP=6,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,thanks:thanks=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles15(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=react.useMemo(()=>formatMessageTime(message.createdAt),[message.createdAt]),canCopy=onCopy!==void 0&&message.role!=="vet"&&message.text.length>0,thumbs=message.role==="assistant"&&onSentiment!==void 0&&message.responseId!==void 0,[justCopied,setJustCopied]=react.useState(false),resetTimer=react.useRef(null);react.useEffect(()=>()=>{resetTimer.current&&clearTimeout(resetTimer.current)},[]);let copy=()=>{onCopy!==void 0&&(callHostAsync(onCopy,message.text),setJustCopied(true),resetTimer.current&&clearTimeout(resetTimer.current),resetTimer.current=setTimeout(()=>{setJustCopied(false),resetTimer.current=null},motion.copiedMs))};return timeLabel===null&&!canCopy&&!thumbs?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.wrap,children:[
286
- /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],children:[timeLabel!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.timestamp,children:timeLabel}):null,canCopy?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:justCopied?CHAT_COPY.copied:isUser?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,hitSlop:ICON_HIT_SLOP,onPress:copy,style:styles2.iconHit,children:justCopied?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:ICON_SIZE,color:theme.color.success,strokeWidth:2}):/* @__PURE__ */jsxRuntime.jsx(CopyGlyph,{size:ICON_SIZE,color:theme.color.text.timestamp,strokeWidth:1.5})}):null,thumbs?SENTIMENT_OPTIONS.map(({sentiment:kind,label:label})=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:sentiment===kind},hitSlop:THUMB_HIT_SLOP,onPress:()=>onSentiment?.(kind),style:styles2.iconHit,children:/* @__PURE__ */jsxRuntime.jsx(ThumbGlyph,{size:ICON_SIZE,color:theme.color.sentiment[kind],active:sentiment===kind,rotate:SENTIMENT_ROTATE[kind],strokeWidth:1.5})},kind)):null]}),thanks?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.thanks,accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackThanks}):null]})}function makeStyles15(theme){let t=theme.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(theme,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:theme.color.text.timestamp,textAlign:"center"},iconHit:{width:ICON_SIZE,height:ICON_SIZE,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary}})}var QUICK_PROMPT_BRAND_EDGE="#10462E";var QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
363
+ return jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles2.card,children:inner})}function makeStyles18(theme){let c=theme.color,s=theme.space,r=theme.radius,size=theme.type.size,cardText=slotText(theme.slots.card);return reactNative.StyleSheet.create({block:{gap:s.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:r.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:s.xs+2,paddingHorizontal:s.md,paddingVertical:s.xs+2,borderRadius:r.pill,backgroundColor:c.brandSoft},toggleLabel:{...face(theme,"monoBold"),fontSize:size.micro,lineHeight:size.micro,letterSpacing:TOGGLE_TRACKING,color:c.brandInk,textTransform:"uppercase"},row:{gap:s.sm,paddingRight:s.xl,paddingTop:s.xs},card:{width:CARD_WIDTH,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface,padding:s.md,gap:s.xs+2,...slotBox(theme.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:s.sm},tierDot:{width:TIER_DOT,height:TIER_DOT,borderRadius:r.pill},cardTitle:{...headingFace(theme,"bold"),flex:1,fontSize:size.bodyTight,lineHeight:TITLE_LINE,color:c.text.primary,letterSpacing:TITLE_TRACKING,...cardText},cardTitleLink:{color:c.linkInk},cardMeta:{...face(theme,"monoMedium"),fontSize:size.nano,lineHeight:META_LINE,letterSpacing:theme.type.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase",...cardText},cardExcerpt:{...face(theme,"regular"),fontSize:size.tiny,lineHeight:EXCERPT_LINE,color:c.text.muted,...cardText}})}var ICON_SIZE=15,ICON_HIT_SLOP=15,THUMB_HIT_SLOP=6,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,thanks:thanks=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles19(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=react.useMemo(()=>formatMessageTime(message.createdAt),[message.createdAt]),canCopy=onCopy!==void 0&&message.role!=="vet"&&message.text.length>0,thumbs=message.role==="assistant"&&onSentiment!==void 0&&message.responseId!==void 0,[justCopied,setJustCopied]=react.useState(false),resetTimer=react.useRef(null);react.useEffect(()=>()=>{resetTimer.current&&clearTimeout(resetTimer.current)},[]);let copy=()=>{onCopy!==void 0&&(callHostAsync(onCopy,message.text),setJustCopied(true),resetTimer.current&&clearTimeout(resetTimer.current),resetTimer.current=setTimeout(()=>{setJustCopied(false),resetTimer.current=null},motion.copiedMs))};return timeLabel===null&&!canCopy&&!thumbs?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.wrap,children:[
364
+ /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],children:[timeLabel!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.timestamp,children:timeLabel}):null,canCopy?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:justCopied?CHAT_COPY.copied:isUser?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,hitSlop:ICON_HIT_SLOP,onPress:copy,style:styles2.iconHit,children:justCopied?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:ICON_SIZE,color:theme.color.success,strokeWidth:2}):/* @__PURE__ */jsxRuntime.jsx(CopyGlyph,{size:ICON_SIZE,color:theme.color.text.timestamp,strokeWidth:1.5})}):null,thumbs?SENTIMENT_OPTIONS.map(({sentiment:kind,label:label})=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:sentiment===kind},hitSlop:THUMB_HIT_SLOP,onPress:()=>onSentiment?.(kind),style:styles2.iconHit,children:/* @__PURE__ */jsxRuntime.jsx(ThumbGlyph,{size:ICON_SIZE,color:theme.color.sentiment[kind],active:sentiment===kind,rotate:SENTIMENT_ROTATE[kind],strokeWidth:1.5})},kind)):null]}),thanks?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.thanks,accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackThanks}):null]})}function makeStyles19(theme){let t=theme.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(theme,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:theme.color.text.timestamp,textAlign:"center"},iconHit:{width:ICON_SIZE,height:ICON_SIZE,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary}})}var QUICK_PROMPT_BRAND_EDGE="#10462E";var QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
287
365
  /* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
288
366
  /* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:PILL_ACTIVITY_ON_WHITE,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
289
367
  /* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:QUICK_PROMPT_BRAND_EDGE,brandEdge:true,borderWidth:1}),
290
- /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function quickPromptThemePaint(everfurLook,highlight){return everfurLook?null:{fill:highlight.fill,ink:highlight.ink}}var TRAILING_SIZE_SUFFIX_RE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function formatBreedForPrompt(breed){return breed==null?breed:breed.replace(TRAILING_SIZE_SUFFIX_RE,"").trim()}var UNINFORMATIVE_BREEDS=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function isUninformativeBreed(breed){let key=String(breed??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return UNINFORMATIVE_BREEDS.has(key)}function unspecifiedBreedLabel(species){return species==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function resolveBreedLabel(breed,species){return isUninformativeBreed(breed)?unspecifiedBreedLabel(species):String(breed).replace(/\s+/gu," ").trim()}function emptyStateTitle(pet){let petName=pet?.name?.trim()||CHAT_COPY.emptyTitlePetFallback;return fillCopy(CHAT_COPY.emptyTitle,{petName:petName})}function resolveQuickPrompts(pet,brandEdge=QUICK_PROMPT_BRAND_EDGE){let species=speciesOf(pet?.species),speciesFallback=species==="cat"?"my cat":"my dog",trimmedPetName=pet?.name?.trim()||null,petToken=trimmedPetName||speciesFallback,breedToken=resolveBreedLabel(formatBreedForPrompt(pet?.breed),species)||null,age=petAgeYears(pet?.ageYears),ageToken=age===null?null:String(age);/* @__PURE__ */
291
- return Object.freeze(PROMPTS.map(template=>{let usesBreed=template.label.includes("{breed}"),usesAge=template.label.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:template.label,resolvedLabel=fillCopy(baseLabel,{petName:petToken,breed:breedToken??speciesFallback,species:species,ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;/* @__PURE__ */
292
- return Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})}))}var CHIP_MIN_HEIGHT=44,CHIP_HIT_SLOP=0,CHIP_EDGE_WIDTH=1,CHIP_EDGE_ALPHA=.28,CHIP_GAP_EXTRA=2,CHIP_PAD_X_EXTRA=2,CHIP_LEAD=1.3,TITLE_TRACKING_EM=-.015;function QuickPrompts({pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles16(theme),[theme]),prompts=react.useMemo(()=>resolveQuickPrompts(pet,theme.color.brandInk),[pet,theme.color.brandInk]),themed=react.useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),title=emptyStateTitle(pet);/* @__PURE__ */
368
+ /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function quickPromptThemePaint(everfurLook,highlight){return everfurLook?null:{fill:highlight.fill,ink:highlight.ink}}var STARTER_PROMPTS_MAX=8;function cleanColor(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=64&&!/[;{}<>]/u.test(trimmed)?trimmed:null}function resolveStarterPrompts(prompts){if(!Array.isArray(prompts))return null;let out=[];for(let entry of prompts){if(out.length>=STARTER_PROMPTS_MAX)break;if(entry===null||typeof entry!="object"||typeof entry.label!="string")continue;let label=entry.label.trim();if(label.length===0)continue;let prompt=typeof entry.prompt=="string"&&entry.prompt.trim().length>0?entry.prompt.trim():label,tint=cleanColor(entry.tint);out.push(/* @__PURE__ */Object.freeze({id:`starter-${out.length}`,label:label,prompt:prompt,tint:tint,ink:tint===null?null:cleanColor(entry.ink)}))}return out.length>0?/* @__PURE__ */Object.freeze(out):null}var TRAILING_SIZE_SUFFIX_RE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function formatBreedForPrompt(breed){return breed==null?breed:breed.replace(TRAILING_SIZE_SUFFIX_RE,"").trim()}var UNINFORMATIVE_BREEDS=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function isUninformativeBreed(breed){let key=String(breed??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return UNINFORMATIVE_BREEDS.has(key)}function unspecifiedBreedLabel(species){return species==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function emptyStateTitle(pet){let petName=pet?.name?.trim()||CHAT_COPY.emptyTitlePetFallback;return fillCopy(CHAT_COPY.emptyTitle,{petName:petName})}function isPlaceholderBreed(breed){let lower=breed.toLowerCase();return lower===unspecifiedBreedLabel("dog").toLowerCase()||lower===unspecifiedBreedLabel("cat").toLowerCase()}function chipBreed(breed){let formatted=formatBreedForPrompt(breed);if(isUninformativeBreed(formatted))return null;let clean2=String(formatted).replace(/\s+/gu," ").trim();return isPlaceholderBreed(clean2)?null:clean2}function resolveQuickPrompts(pet,brandEdge=QUICK_PROMPT_BRAND_EDGE,options){let known=canonicalPetSpecies(pet?.species),trimmedPetName=pet?.name?.trim()||null,breedToken=chipBreed(pet?.breed),age=petAgeYears(pet?.ageYears),ageToken=age===null?null:String(age),vetPrepLabel=null;/* @__PURE__ */
369
+ return Object.freeze(PROMPTS.flatMap(template=>{let own=template.intent==="vet_report"&&vetPrepLabel!==null?vetPrepLabel:template.label,usesBreed=own.includes("{breed}"),usesAge=own.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:own;if(baseLabel.includes("{breed}")&&breedToken===null||baseLabel.includes("{ageYears}")&&ageToken===null||known===null&&(baseLabel.includes("{species}")||baseLabel.includes("{petName}")&&trimmedPetName===null))return[];let resolvedLabel=fillCopy(baseLabel,{petName:trimmedPetName??(known==="cat"?"my cat":"my dog"),breed:breedToken??"",species:known??"",ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;return[/* @__PURE__ */Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})]}))}var CHIP_MIN_HEIGHT=44,CHIP_HIT_SLOP=0,CHIP_EDGE_WIDTH=1,CHIP_EDGE_ALPHA=.28,CHIP_GAP_EXTRA=2,CHIP_PAD_X_EXTRA=2,CHIP_LEAD=1.3,TITLE_TRACKING_EM=-.015,RAPH_CHIP_TINTS=/* @__PURE__ */Object.freeze([
370
+ /* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
371
+ /* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
372
+ /* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
373
+ /* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,starterPrompts:starterPrompts,emptyState:emptyState,centered:centered=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles20(theme),[theme]),hostChips=react.useMemo(()=>resolveStarterPrompts(starterPrompts),[starterPrompts]),drawn=react.useMemo(()=>hostChips!==null?hostChips.map(host=>({prompt:{id:host.id,intent:"send",label:host.label,background:host.tint??theme.color.highlight,borderColor:"transparent",borderWidth:1},send:host.prompt,paint:host.tint===null?null:{fill:host.tint,ink:host.ink??theme.color.text.primary}})):resolveQuickPrompts(pet,theme.color.brandInk).map(prompt=>({prompt:prompt,send:prompt.label,paint:null})),[hostChips,pet,theme.color.brandInk,theme.color.highlight,theme.color.text.primary]),hostCycle=emptyState?.chipTints!==void 0,cycle=react.useMemo(()=>(emptyState?.chipTints??(theme.brightness==="light"?RAPH_CHIP_TINTS:[])).filter(t=>typeof t.tint=="string"&&t.tint.trim()!==""),[emptyState?.chipTints,theme.brightness]),chips=react.useMemo(()=>cycle.length===0?drawn:drawn.map((d,index)=>{if(d.paint!==null)return d;let t=cycle[index%cycle.length];return{...d,paint:{fill:t.tint,ink:t.ink??theme.color.text.primary},...hostCycle?{}:{cycleDefault:true}}}),[drawn,cycle,hostCycle,theme.color.text.primary]),themed=react.useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),hostChipThemed=react.useMemo(()=>({fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme.color.highlight,theme.color.onHighlight]),hostTitle=emptyState?.title?.trim(),title=hostTitle!==void 0&&hostTitle!==""?hostTitle:emptyStateTitle(pet);/* @__PURE__ */
293
374
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.block,children:[
294
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:title}),
295
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.list,accessibilityLabel:CHAT_COPY.suggestions,children:prompts.map((prompt,index)=>/* @__PURE__ */jsxRuntime.jsx(Chip,{prompt:prompt,themed:themed,index:index,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,pet:pet,styles:styles2},prompt.id))})]})}function Chip({prompt:prompt,themed:themed,index:index,pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,styles:styles2}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),paint=styles2.chipSlot===null?{backgroundColor:themed?.fill??prompt.background}:{backgroundColor:themed?.fill??prompt.background,...styles2.chipSlot},label=themed===null?styles2.chipSlotLabel===null?styles2.chipLabel:[styles2.chipLabel,styles2.chipSlotLabel]:[styles2.chipLabel,{color:themed.ink},...styles2.chipSlotLabel===null?[]:[styles2.chipSlotLabel]];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:prompt.label,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:[styles2.chip,styles2.chipEdge,paint],labelStyle:label})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>onSend(prompt.label),children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})})}function makeStyles16(theme){let chip=ownGroundSlot(theme.slots.chip),chipText=slotText(chip);return{chipSlot:chip===void 0?null:slotBox(chip,CHIP_EDGE_WIDTH),chipSlotLabel:chipText.color===void 0?null:chipText,...makeSheet(theme)}}function makeSheet(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},title:{...headingFace(theme,"medium"),fontSize:t.size.heading,lineHeight:Math.round(t.size.heading*t.lineHeight.snug),color:c.brandInk,letterSpacing:t.size.heading*TITLE_TRACKING_EM,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:s.sm+CHIP_GAP_EXTRA},chip:{borderRadius:theme.radius.pill,paddingHorizontal:s.lg+CHIP_PAD_X_EXTRA,paddingVertical:s.sm,minHeight:CHIP_MIN_HEIGHT,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:CHIP_EDGE_WIDTH,borderColor:withAlpha(c.brandInk,CHIP_EDGE_ALPHA)??c.borderRingCream},chipLabel:{...face(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*CHIP_LEAD),color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left"}})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor&&runs.push({kind:"text",text:text3.slice(cursor,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor=match.index+match[0].length}return cursor<text3.length&&runs.push({kind:"text",text:text3.slice(cursor)}),runs}function renderInlineMarkdown(text3,styles2){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
296
- return jsxRuntime.jsx(Text,{style:styles2.bold,children:run.text},key);case"italic":return styles2.italic?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.italic,children:run.text},key):run.text;case"code":return styles2.code?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.code,children:run.text},key):run.text;default:return run.text}}):text3}function TypingIndicator({petName:petName=null}){let{styles:styles2}=useChatTheme(),line=forPet(CHAT_COPY.reading,petName);/* @__PURE__ */
375
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:centered?[styles2.title,styles2.centerText]:styles2.title,accessibilityRole:"header",children:title}),
376
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:centered?[styles2.list,styles2.listCentered]:styles2.list,accessibilityLabel:CHAT_COPY.suggestions,children:chips.map(({prompt:prompt,send:send,paint:paint,cycleDefault:cycleDefault},index)=>/* @__PURE__ */jsxRuntime.jsx(Chip,{prompt:prompt,send:send,themed:paint??(hostChips!==null?hostChipThemed:themed),index:index,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,pet:pet,styles:styles2,tinted:paint!==null&&cycleDefault!==true,soft:paint!==null,centered:centered},prompt.id))})]})}function Chip({prompt:prompt,send:send,themed:themed,index:index,pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,styles:styles2,tinted:tinted,soft:soft,centered:centered}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),edge=centered&&soft?styles2.chipNoEdge:styles2.chipEdge,fill={backgroundColor:themed?.fill??prompt.background},paint=styles2.chipSlot===null?fill:tinted?{...styles2.chipSlot,...fill}:{...fill,...styles2.chipSlot},base2=centered?[styles2.chipLabel,styles2.centerText]:[styles2.chipLabel],label=themed===null?styles2.chipSlotLabel===null?base2:[...base2,styles2.chipSlotLabel]:tinted?[...base2,...styles2.chipSlotLabel===null?[]:[styles2.chipSlotLabel],{color:themed.ink}]:[...base2,{color:themed.ink},...styles2.chipSlotLabel===null?[]:[styles2.chipSlotLabel]];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,edge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:prompt.label,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:[styles2.chip,edge,paint],labelStyle:label})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,edge,paint],onPress:()=>onSend(send),children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})})}function makeStyles20(theme){let chip=ownGroundSlot(theme.slots.chip),chipText=slotText(chip);return{chipSlot:chip===void 0?null:slotBox(chip,CHIP_EDGE_WIDTH),chipSlotLabel:chipText.color===void 0?null:chipText,...makeSheet(theme)}}function makeSheet(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},title:{...headingFace(theme,"medium"),fontSize:t.size.heading,lineHeight:Math.round(t.size.heading*t.lineHeight.snug),color:c.brandInk,letterSpacing:t.size.heading*TITLE_TRACKING_EM,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:s.sm+CHIP_GAP_EXTRA},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:CHIP_EDGE_WIDTH,borderColor:"transparent"},chip:{borderRadius:theme.radius.pill,paddingHorizontal:s.lg+CHIP_PAD_X_EXTRA,paddingVertical:s.sm,minHeight:CHIP_MIN_HEIGHT,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:CHIP_EDGE_WIDTH,borderColor:withAlpha(c.brandInk,CHIP_EDGE_ALPHA)??c.borderRingCream},chipLabel:{...face(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*CHIP_LEAD),color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left"}})}function TypingIndicator({petName:petName=null}){let{styles:styles2}=useChatTheme(),line=forPet(CHAT_COPY.reading,petName);/* @__PURE__ */
297
377
  return jsxRuntime.jsx(Text,{tier:"compact",style:styles2.readingLine,accessibilityRole:"text",accessibilityLabel:line,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:line})}function resolveTurnScrollTarget(assistantTop,userTop,inset){let replyTarget=assistantTop-inset,target=userTop!=null?Math.min(replyTarget,userTop):replyTarget;return Math.max(0,target)}function latestTurn(messages){let assistantIndex=messages.length-1,last=messages[assistantIndex];if(last===void 0||last.role!=="assistant")return null;let above=messages[assistantIndex-1];return{assistantIndex:assistantIndex,userIndex:above!==void 0&&above.role==="user"?assistantIndex-1:null}}function nextFollowOffset(anchor,current,maxOffset){let end=Math.max(0,maxOffset),target=anchor===null?end:Math.min(Math.max(0,anchor),end);return target>current+1?target:null}function useThreadFollow(rows,isStreaming){let ref=react.useRef(null),following=react.useRef(true),wasStreaming=react.useRef(isStreaming),offset=react.useRef(0),viewport=react.useRef(0),content=react.useRef(0),tops=react.useRef(/* @__PURE__ */new Map),turn=latestTurn(rows),assistantId=turn===null?null:rows[turn.assistantIndex]?.id??null,userId=turn===null||turn.userIndex===null?null:rows[turn.userIndex]?.id??null,follow=react.useCallback(()=>{let view=ref.current;if(view===null||!following.current||viewport.current===0)return;let anchor=null;if(assistantId!==null){let assistantTop=tops.current.get(assistantId);if(assistantTop===void 0)return;let userTop=userId===null?null:tops.current.get(userId)??null;anchor=resolveTurnScrollTarget(assistantTop,userTop,96)}let next=nextFollowOffset(anchor,offset.current,content.current-viewport.current);next!==null&&(offset.current=next,view.scrollTo({y:next,animated:false}))},[assistantId,userId]);react.useEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true),wasStreaming.current=isStreaming,follow()},[rows,isStreaming,follow]);let onLayout=react.useCallback(event=>{viewport.current=event.nativeEvent.layout.height,follow()},[follow]),onContentSizeChange=react.useCallback((_width,height)=>{content.current=height,viewport.current>0&&(offset.current=Math.min(offset.current,Math.max(0,height-viewport.current))),follow()},[follow]),onScroll=react.useCallback(event=>{offset.current=event.nativeEvent.contentOffset.y},[]),onScrollBeginDrag=react.useCallback(()=>{following.current=false},[]),onScrollEnd=react.useCallback(event=>{let{contentOffset:contentOffset,contentSize:contentSize,layoutMeasurement:layoutMeasurement}=event.nativeEvent;offset.current=contentOffset.y,following.current=contentSize.height-contentOffset.y-layoutMeasurement.height<=24},[]),rowLayout=react.useCallback(id=>event=>{tops.current.set(id,event.nativeEvent.layout.y),(id===assistantId||id===userId)&&follow()},[assistantId,userId,follow]);return{ref:ref,onLayout:onLayout,onContentSizeChange:onContentSizeChange,onScroll:onScroll,onScrollBeginDrag:onScrollBeginDrag,onScrollEnd:onScrollEnd,rowLayout:rowLayout}}function renderView(view,chat,extras){switch(view){case"loading":return extras.renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:extras.renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(LoadingState,{})}):/* @__PURE__ */jsxRuntime.jsx(LoadingState,{});case"empty":/* @__PURE__ */
298
- return jsxRuntime.jsx(EmptyState,{pet:extras.shownPet,petRef:chat.petRef,onSelectPrompt:extras.onSelectPrompt,onVetPrep:extras.onVetPrep,vet:extras.vet});case"error":/* @__PURE__ */
378
+ return jsxRuntime.jsx(EmptyState,{pet:extras.shownPet,petRef:chat.petRef,onSelectPrompt:extras.onSelectPrompt,onVetPrep:extras.onVetPrep,vet:extras.vet,top:extras.threadTop,topCard:extras.topCard,starterPrompts:extras.starterPrompts,emptyState:extras.emptyState,centered:extras.emptyCentered===true});case"error":/* @__PURE__ */
299
379
  return jsxRuntime.jsx(ErrorState,{error:chat.error,onRetry:chat.retryLast,onAddPet:extras.onAddPet});case"populated":/* @__PURE__ */
300
- return jsxRuntime.jsx(PopulatedState,{messages:chat.messages,prompts:visibleFollowUps(chat),onSelectPrompt:extras.onSelectPrompt,isStreaming:chat.isStreaming,onAnswerCheckin:chat.petRef?chat.answerCheckin:null,onCopy:extras.onCopy,sentimentByMessage:chat.sentimentByMessage,onSentiment:extras.onSentiment,thanksFor:extras.thanksFor,imagesByMessage:extras.imagesByMessage,onPreview:extras.onPreview,notice:extras.notice,reconnecting:chat.reconnecting===true,onRetry:chat.retryLast,onStartNew:chat.newConversation,petRef:chat.petRef,onFindVet:extras.onCheckinFindVet,vet:extras.vet,onOpenUrl:extras.onOpenUrl,petName:extras.shownPet?.name??null});default:return assertNever(view)}}function LoadingState(){let{theme:theme,styles:styles2}=useChatTheme(),[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:CHAT_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk}):null})}function EmptyState({pet:pet,petRef:petRef,onSelectPrompt:onSelectPrompt,onVetPrep:onVetPrep,vet:vet}){let{styles:styles2}=useChatTheme();
380
+ return jsxRuntime.jsx(PopulatedState,{messages:chat.messages,prompts:followUpsWithPolicy(chat,extras.followUpPolicy),actions:extras.answerCards?followUpActionsFor(chat,extras.answerCards):NO_ACTIONS,answerCards:extras.answerCards??null,threadTop:extras.threadTop,onSelectPrompt:extras.onSelectPrompt,isStreaming:chat.isStreaming,onAnswerCheckin:chat.petRef?chat.answerCheckin:null,onCopy:extras.onCopy,sentimentByMessage:chat.sentimentByMessage,onSentiment:extras.onSentiment,thanksFor:extras.thanksFor,imagesByMessage:extras.imagesByMessage,onPreview:extras.onPreview,notice:extras.notice,reconnecting:chat.reconnecting===true,onRetry:chat.retryLast,onStartNew:chat.newConversation,petRef:chat.petRef,onFindVet:extras.onCheckinFindVet,vet:extras.vet,onOpenUrl:extras.onOpenUrl,petName:extras.shownPet?.name??null});default:return assertNever(view)}}function LoadingState(){let{theme:theme,styles:styles2}=useChatTheme(),[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:CHAT_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk}):null})}function EmptyState({pet:pet,petRef:petRef,onSelectPrompt:onSelectPrompt,onVetPrep:onVetPrep,vet:vet,top:top,topCard:topCard,starterPrompts:starterPrompts,emptyState:emptyState,centered:centered}){let{styles:styles2}=useChatTheme();
301
381
  /* @__PURE__ */
302
- return jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:styles2.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,accessibilityLabel:CHAT_COPY.empty,children:/* @__PURE__ */jsxRuntime.jsx(QuickPrompts,{pet:pet,petRef:petRef,onSend:onSelectPrompt,onVetPrep:onVetPrep,vet:vet})})}function FollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt}){let{styles:styles2}=useChatTheme();return prompts.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.followUps,children:[
382
+ return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles2.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,accessibilityLabel:CHAT_COPY.empty,children:[top??null,topCard??null,
383
+ /* @__PURE__ */jsxRuntime.jsx(QuickPrompts,{pet:pet,petRef:petRef,onSend:onSelectPrompt,onVetPrep:onVetPrep,vet:vet,starterPrompts:starterPrompts,emptyState:emptyState,centered:centered})]})}function FollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt}){let{styles:styles2}=useChatTheme();return prompts.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.followUps,children:[
303
384
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.followUpsHeading,accessibilityRole:"header",children:CHAT_COPY.followUpsHeadingNative}),prompts.map((prompt,index)=>/* @__PURE__ */jsxRuntime.jsx(FollowUpRow,{prompt:prompt,index:index,onSelectPrompt:onSelectPrompt},prompt))]})}function FollowUpRow({prompt:prompt,index:index,onSelectPrompt:onSelectPrompt}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index)});/* @__PURE__ */
304
385
  return jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsxs(PressScale,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,containerStyle:[styles2.followUpSlot,index>0?styles2.followUpSlotRuled:null],style:styles2.followUpRow,children:[
305
386
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.followUpText,children:prompt}),
306
387
  /* @__PURE__ */jsxRuntime.jsx(PlusGlyph,{size:FOLLOW_UP_PLUS,color:theme.slots.chip?.textColor??theme.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:error,onRetry:onRetry,onAddPet:onAddPet}){let{styles:styles2}=useChatTheme(),addPet=isPetNotRegistered(error)?guardHost(onAddPet):void 0;/* @__PURE__ */
307
388
  return jsxRuntime.jsxs(reactNative.View,{style:styles2.centered,accessible:true,accessibilityRole:"alert",children:[
308
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.errorText,children:error.displayMessage}),addPet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:addPet,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addPet,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.addPet})}):null,error.retryable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.retry})}):null]})}function PopulatedState({messages:messages,prompts:prompts,onSelectPrompt:onSelectPrompt,isStreaming:isStreaming,onAnswerCheckin:onAnswerCheckin,onCopy:onCopy,sentimentByMessage:sentimentByMessage,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:imagesByMessage,onPreview:onPreview,notice:notice,reconnecting:reconnecting,onRetry:onRetry,onStartNew:onStartNew,petRef:petRef,onFindVet:onFindVet,vet:vet,onOpenUrl:onOpenUrl,petName:petName}){let{styles:styles2}=useChatTheme(),motion=useChatMotion();useAnimateLayoutOn(messages.length,motion);let checkins=react.useMemo(()=>placeCheckins(messages),[messages]),awaiting=awaitingAssistant(messages,isStreaming),last=messages[messages.length-1],rows=react.useMemo(()=>messages.filter(message=>!(message.checkin&&checkins.get(message.id)?.kind==="folded")),[messages,checkins]),follow=useThreadFollow(rows,isStreaming),isEntering=useEnteringRows(rows);/* @__PURE__ */
309
- return jsxRuntime.jsxs(reactNative.ScrollView,{ref:follow.ref,style:styles2.list,contentContainerStyle:styles2.listContent,accessibilityLabel:CHAT_COPY.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,onLayout:follow.onLayout,onContentSizeChange:follow.onContentSizeChange,onScroll:follow.onScroll,scrollEventThrottle:SCROLL_EVENT_THROTTLE_MS,onScrollBeginDrag:follow.onScrollBeginDrag,onScrollEndDrag:follow.onScrollEnd,onMomentumScrollEnd:follow.onScrollEnd,children:[messages.map(message=>{let placement=message.checkin?checkins.get(message.id):void 0;return placement?.kind==="folded"?null:placement?.kind==="past"?/* @__PURE__ */jsxRuntime.jsx(CheckinPastAsk,{text:message.text,runDueDays:placement.runDueDays,openedAt:message.checkin?.openedAt,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&placement!==void 0?/* @__PURE__ */jsxRuntime.jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */jsxRuntime.jsx(MessageRow,{onLayout:follow.rowLayout(message.id),message:message,revealing:isStreaming&&message===last&&message.role==="assistant",onCopy:onCopy,sentiment:message.responseId===void 0?null:sentimentByMessage[String(message.responseId)]??null,onSentiment:onSentiment,thanks:thanksFor!==null&&message.responseId!==void 0&&String(message.responseId)===thanksFor,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id)},message.id)}),reconnecting?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsxRuntime.jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsxRuntime.jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,
310
- /* @__PURE__ */jsxRuntime.jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles2}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
389
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.errorText,children:error.displayMessage}),addPet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:addPet,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addPet,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.addPet})}):null,error.retryable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.retry})}):null]})}function PopulatedState({messages:messages,prompts:prompts,onSelectPrompt:onSelectPrompt,isStreaming:isStreaming,onAnswerCheckin:onAnswerCheckin,onCopy:onCopy,sentimentByMessage:sentimentByMessage,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:imagesByMessage,onPreview:onPreview,notice:notice,reconnecting:reconnecting,onRetry:onRetry,onStartNew:onStartNew,petRef:petRef,onFindVet:onFindVet,vet:vet,onOpenUrl:onOpenUrl,petName:petName,actions:actions,answerCards:answerCards,threadTop:threadTop}){let{styles:styles2}=useChatTheme(),motion=useChatMotion();useAnimateLayoutOn(messages.length,motion);let checkins=react.useMemo(()=>placeCheckins(messages),[messages]),awaiting=awaitingAssistant(messages,isStreaming),last=messages[messages.length-1],rows=react.useMemo(()=>messages.filter(message=>!(message.checkin&&checkins.get(message.id)?.kind==="folded")),[messages,checkins]),follow=useThreadFollow(rows,isStreaming),isEntering=useEnteringRows(rows);/* @__PURE__ */
390
+ return jsxRuntime.jsxs(reactNative.ScrollView,{ref:follow.ref,style:styles2.list,contentContainerStyle:styles2.listContent,accessibilityLabel:CHAT_COPY.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,onLayout:follow.onLayout,onContentSizeChange:follow.onContentSizeChange,onScroll:follow.onScroll,scrollEventThrottle:SCROLL_EVENT_THROTTLE_MS,onScrollBeginDrag:follow.onScrollBeginDrag,onScrollEndDrag:follow.onScrollEnd,onMomentumScrollEnd:follow.onScrollEnd,children:[threadTop??null,messages.map(message=>{let placement=message.checkin?checkins.get(message.id):void 0;return placement?.kind==="folded"?null:placement?.kind==="past"?/* @__PURE__ */jsxRuntime.jsx(CheckinPastAsk,{text:message.text,runDueDays:placement.runDueDays,openedAt:message.checkin?.openedAt,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&placement!==void 0?/* @__PURE__ */jsxRuntime.jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */jsxRuntime.jsx(MessageRow,{onLayout:follow.rowLayout(message.id),message:message,revealing:isStreaming&&message===last&&message.role==="assistant",onCopy:onCopy,sentiment:message.responseId===void 0?null:sentimentByMessage[String(message.responseId)]??null,onSentiment:onSentiment,thanks:thanksFor!==null&&message.responseId!==void 0&&String(message.responseId)===thanksFor,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id),answerCards:answerCards,messages:messages},message.id)}),reconnecting?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsxRuntime.jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsxRuntime.jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,answerCards!==null?/* @__PURE__ */jsxRuntime.jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,actions:actions,options:answerCards}):/* @__PURE__ */jsxRuntime.jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles2}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
311
391
  return jsxRuntime.jsxs(reactNative.View,{style:[styles2.turnNotice,error?styles2.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
312
392
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.turnNoticeTitle,error?styles2.turnNoticeTitleError:null],children:notice.title}),
313
393
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.turnNoticeBody,children:notice.body}),
314
- /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles2.turnNoticeAction,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=reactNative.Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,thanks:thanks,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=react.useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true;/* @__PURE__ */
315
- return jsxRuntime.jsxs(reactNative.View,{style:[styles2.rowBlock,isUser?styles2.rowBlockUser:styles2.rowBlockAssistant],onLayout:onLayout,children:[
316
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Animated.View,{style:[styles2.bubble,isUser?styles2.bubbleSideUser:null,enter],children:[isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsxRuntime.jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles2}):namesAssistant?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null,isVet?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.vetHeader,children:[
394
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles2.turnNoticeAction,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),NO_ACTIONS=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=reactNative.Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,thanks:thanks,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering,answerCards:answerCards,messages:messages}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=react.useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true,senderLine=isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsxRuntime.jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles2}):namesAssistant?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null;return isAssistant&&answerCards!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[styles2.rowBlock,enter],onLayout:onLayout,accessibilityLabel:`${sender}: ${message.text}`,children:/* @__PURE__ */jsxRuntime.jsx(CardsAnswer,{message:message,text:shown,streaming:revealing,messages:messages,options:answerCards,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,sender:senderLine,onOpenUrl:onOpenUrl,footer:withThumbs=>/* @__PURE__ */jsxRuntime.jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:withThumbs&&message.responseId!==void 0?rate:void 0,thanks:thanks})})}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles2.rowBlock,isUser?styles2.rowBlockUser:styles2.rowBlockAssistant],onLayout:onLayout,children:[
395
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Animated.View,{style:[styles2.bubble,isUser?styles2.bubbleSideUser:null,enter],children:[senderLine,isVet?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.vetHeader,children:[
317
396
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.vetSender,children:sender}),vetTime!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.vetTime,children:vetTime}):null]}):null,
318
397
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[isUser?styles2.bubbleUser:isVet?styles2.bubbleVet:styles2.bubbleAssistant,message.pending?styles2.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsxRuntime.jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
319
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:isUser?styles2.bubbleTextUser:isVet?styles2.bubbleTextVet:styles2.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles2.bubbleBold,italic:styles2.bubbleItalic,code:styles2.bubbleCode}):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsxRuntime.jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled?/* @__PURE__ */jsxRuntime.jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,thanks:thanks}):null]})}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),DEFAULT_MAX_PER_MESSAGE=1;function EverfurChat(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
320
- return jsxRuntime.jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsxRuntime.jsx(ChatBody,{...props})})}function ChatBody({petRef:petRef,conversationId:conversationId,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),chatOpts=react.useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),notice=turnNotice(chat),onCheckinFindVet=react.useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=react.useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=react.useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion),useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk);let seed=react.useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]);useChatLifecycle(lifecycle,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=react.useState(null),closePreview=react.useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=react.useState(null),[thanksFor,setThanksFor]=react.useState(null),thanksTimer=react.useRef(null);react.useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showThanks=react.useCallback(responseId=>{setThanksFor(String(responseId)),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=setTimeout(()=>{setThanksFor(null),thanksTimer.current=null},THANKS_VISIBLE_MS)},[]),onSentiment=react.useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];chat.feedback(responseId,sentiment),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat]),submitReasons=react.useCallback(async(reason,notes)=>feedbackTarget===null||!(await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showThanks(feedbackTarget),true),[chat,feedbackTarget,showThanks]),skipReasons=react.useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=react.useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=react.useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=reactNative.Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null};
398
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:isUser?styles2.bubbleTextUser:isVet?styles2.bubbleTextVet:styles2.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles2.bubbleBold,italic:styles2.bubbleItalic,code:styles2.bubbleCode}):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsxRuntime.jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled?/* @__PURE__ */jsxRuntime.jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,thanks:thanks}):null]})}function EverfurChat(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
399
+ return jsxRuntime.jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsxRuntime.jsx(ChatBody,{...props})})}function useOptionalEverfurContext(){try{return useEverfurContext()}catch{return null}}function hostPresentation(props){return definedPresentation({...props.presentation,chatComposerUpload:props.presentation?.chatComposerUpload??(props.attachments===void 0?void 0:true)})}function ChatBody(props){let context=useOptionalEverfurContext();return context===null?/* @__PURE__ */jsxRuntime.jsx(ChatBodyAlone,{...props}):/* @__PURE__ */jsxRuntime.jsx(ChatBodyInProvider,{...props,activePet:context.activePet})}function ChatBodyAlone(props){let client=hostPresentation(props),key=JSON.stringify(client),settings=react.useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:client}),isLocked:()=>false,planPage:null}),[key]);/* @__PURE__ */
400
+ return jsxRuntime.jsx(ChatSurface,{...props,settings:settings})}function ChatBodyInProvider({activePet:activePet,...props}){let{presentation:presentation,isLocked:isLocked}=useEverfurPresentationState(hostPresentation(props)),planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&props.topCard===void 0&&planEnabled,plan=useHealthPlanPage({petRef:props.petRef??activePet??null,enabled:wantsPlan}),planPage=wantsPlan&&plan.phase==="ready"?plan.page:null,settings=react.useMemo(()=>({presentation:presentation,isLocked:isLocked,planPage:planPage}),[presentation,isLocked,planPage]);/* @__PURE__ */
401
+ return jsxRuntime.jsx(ChatSurface,{...props,settings:settings})}function ChatSurface({settings:settings,petRef:petRef,conversationId:conversationId,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset,topCard:hostTopCard,onOpenHealthPlan:onOpenHealthPlan,answerCards:answerCards,historySheet:historySheet,historyBar:historyBar,starterPrompts:starterPrompts,emptyState:emptyState}){let{presentation:presentation,isLocked:isLocked,planPage:planPage}=settings,{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),chatOpts=react.useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),notice=turnNotice(chat),onCheckinFindVet=react.useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=react.useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=react.useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion),useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=react.useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]);useChatLifecycle(lifecycle,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=react.useState(null),closePreview=react.useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=react.useState(null),[thanksFor,setThanksFor]=react.useState(null),thanksTimer=react.useRef(null);react.useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showThanks=react.useCallback(responseId=>{setThanksFor(String(responseId)),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=setTimeout(()=>{setThanksFor(null),thanksTimer.current=null},THANKS_VISIBLE_MS)},[]),onSentiment=react.useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];chat.feedback(responseId,sentiment),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat]),submitReasons=react.useCallback(async(reason,notes)=>feedbackTarget===null||!(await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showThanks(feedbackTarget),true),[chat,feedbackTarget,showThanks]),skipReasons=react.useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=react.useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=react.useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=reactNative.Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),planCard=react.useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:onOpenHealthPlan}):void 0,[hostTopCard,planPage,onOpenHealthPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=react.useState(true),onCardAsk=react.useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=react.useMemo(()=>followUpPolicyFor(void 0,presentation,isLocked("chatFollowUpCount")),[presentation,isLocked]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsxRuntime.jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,barNode=historyBar!==void 0?/* @__PURE__ */jsxRuntime.jsx(HistoryBar,{bar:historyBar,history:history,empty:threadEmpty,unread:historyUnread,extra:pill}):null,barInThread=presentation.chatHistoryBar==="scroll"&&(view==="empty"||view==="populated"),cardNode=card===void 0?null:/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
402
+ /* @__PURE__ */jsxRuntime.jsx(TopCard,{card:card,open:cardOpen,onOpenChange:setCardOpen,ask:onCardAsk}),historyBar===void 0?pill:null]}),barShown=historyBar!==void 0,historyLoad=history.load,historyOpen=history.open;react.useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty"},uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general";
321
403
  /* @__PURE__ */
322
404
  return jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:[styles2.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
323
405
  /* @__PURE__ */jsxRuntime.jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
324
- /* @__PURE__ */jsxRuntime.jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}),pet!==void 0?/* @__PURE__ */jsxRuntime.jsx(PetSetupNotice,{petRef:petRef??null,pet:pet,onRegistered:pets.refresh}):null,
325
- /* @__PURE__ */jsxRuntime.jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
326
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation})}),attachments!==void 0?/* @__PURE__ */jsxRuntime.jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsxRuntime.jsx(Composer,{...composerProps,attachments:null}),
327
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.footnote,accessibilityRole:"text",children:CHAT_COPY.footnoteNative}),theme.meta.hidePoweredBy?null:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),
328
- /* @__PURE__ */jsxRuntime.jsx(HistoryDrawer,{chat:chat,history:history}),
406
+ /* @__PURE__ */jsxRuntime.jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}),pet!==void 0?/* @__PURE__ */jsxRuntime.jsx(PetSetupNotice,{petRef:petRef??null,pet:pet,onRegistered:pets.refresh}):null,barInThread?null:barNode,bannerHidden?null:/* @__PURE__ */jsxRuntime.jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
407
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation,threadTop:barInThread?barNode:null,topCard:cardNode,starterPrompts:starterPrompts,emptyState:emptyState,emptyCentered:presentation.chatAnswerStyle==="cards",followUpPolicy:followUpPolicy,answerCards:presentation.chatAnswerStyle==="cards"?answerCards??NO_ANSWER_CARDS:null})}),uploadOn&&attachments!==void 0?/* @__PURE__ */jsxRuntime.jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsxRuntime.jsx(Composer,{...composerProps,attachments:null}),
408
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.footnote,accessibilityRole:"text",children:CHAT_COPY.footnoteNative}),theme.meta.hidePoweredBy?null:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),sheet?/* @__PURE__ */jsxRuntime.jsx(HistorySheet,{chat:chat,history:history,sheet:historySheet}):/* @__PURE__ */jsxRuntime.jsx(HistoryDrawer,{chat:chat,history:history}),
329
409
  /* @__PURE__ */jsxRuntime.jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
330
410
  /* @__PURE__ */jsxRuntime.jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
331
411
  /* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]})}function PetSetupNotice({petRef:petRef,pet:pet,onRegistered:onRegistered}){let{styles:styles2}=useChatTheme(),setup=useChatPetRegistration(petRef,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.setupNotice,accessible:true,accessibilityRole:"alert",children:[
332
412
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.setupNoticeText,children:setup.error.displayMessage}),
333
- /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.setupNoticeAction,children:CHAT_COPY.retry})})]})}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=react.useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??DEFAULT_MAX_PER_MESSAGE,transport:transport}),bound=react.useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
334
- return jsxRuntime.jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed);usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft);let[pickerOpen,setPickerOpen]=react.useState(false),[pickFailed,setPickFailed]=react.useState(false);react.useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=theme.meta.placeholder??forPet(CHAT_COPY.placeholder,petName),uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=react.useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(text3,{imageS3Keys:keys}),attachments.state.clear()):send(text3),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,attachments,onStage]),onStop=react.useCallback(()=>{stop()},[stop]),pickFrom=react.useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),sendDisabled=react.useMemo(()=>[...draft.trim()].length>MESSAGE_MAX_CHARS,[draft])||sendBlocked,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk;/* @__PURE__ */
335
- return jsxRuntime.jsxs(reactNative.View,{style:styles2.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsxRuntime.jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
336
- /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.composer,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(AttachmentStrip,{attachments:rows,rejected:pickFailed?PICK_FAILED:attachments.state.rejected,uploadFailed:uploadFailed,onRetry:attachments.state.retry,onRemove:attachments.state.remove,onPreview:row=>onPreview({uri:row.previewUri,label:row.filename})}):null,
337
- /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.composerRow,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles2.attachControl,slotsFull?styles2.attachControlDisabled:null],onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsxRuntime.jsx(UploadGlyph,{size:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:theme.color.brandInk,strokeWidth:1.75})}):null,
338
- /* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles2.input,value:draft,onChangeText:setDraft,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",...SUBMIT_ON_RETURN,blurOnSubmit:false,multiline:true,editable:true}),isStreaming?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles2.sendControl,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsxRuntime.jsx(StopGlyph,{size:STOP_GLYPH_SIZE,color:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles2.sendControl,sendDisabled?styles2.sendControlDisabled:null],children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),SUBMIT_ON_RETURN=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});exports.EverfurChat=EverfurChat;exports.createRnChatAttachmentTransport=createRnChatAttachmentTransport;exports.useChatAttachments=useChatAttachments;exports.useEverfurChat=useEverfurChat;exports.useEverfurPets=useEverfurPets;
413
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.setupNoticeAction,children:CHAT_COPY.retry})})]})}var NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});exports.EverfurChat=EverfurChat;exports.createRnChatAttachmentTransport=createRnChatAttachmentTransport;exports.useChatAttachments=useChatAttachments;exports.useEverfurChat=useEverfurChat;exports.useEverfurPets=useEverfurPets;