@everfur/sdk 0.21.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/CHANGELOG.md +167 -3
  2. package/dist/{Chat.d-JDtlG_EW.d.cts → Chat.d-DDmNIlJn.d.cts} +1 -1
  3. package/dist/{Chat.d-CoGJrK3t.d.ts → Chat.d-DySDBc6L.d.ts} +1 -1
  4. package/dist/{DepthViews.d-XTv4s3ru.d.cts → DepthViews.d-BHb0Xb-C.d.cts} +1 -1
  5. package/dist/{DepthViews.d-CNQn-eEr.d.ts → DepthViews.d-BIfqdrvX.d.ts} +1 -1
  6. package/dist/{DepthViews.d-D31VlFKU.d.ts → DepthViews.d-BW3HrhnC.d.ts} +1 -1
  7. package/dist/{DepthViews.d-zxM_xbP9.d.cts → DepthViews.d-Dq8eWBvw.d.cts} +1 -1
  8. package/dist/{RecordsPage.d-D_y-ZB3S.d.ts → RecordsPage.d-Bs-dghTH.d.ts} +1 -1
  9. package/dist/{RecordsPage.d-CSZHrtWJ.d.cts → RecordsPage.d-CLrw-AvZ.d.cts} +1 -1
  10. package/dist/animations/index.cjs +2 -2
  11. package/dist/animations/index.d.cts +3 -3
  12. package/dist/animations/index.d.ts +3 -3
  13. package/dist/animations/index.js +2 -2
  14. package/dist/{attachments.d-D74wbmQU.d.cts → attachments.d-DTGYmW8Y.d.cts} +1 -1
  15. package/dist/{attachments.d-Dm6NUJTR.d.ts → attachments.d-DjxmIsNp.d.ts} +1 -1
  16. package/dist/{bookingCopy.d-DMmLKY5Q.d.ts → bookingCopy.d-CX-DMiwi.d.ts} +148 -148
  17. package/dist/{bookingCopy.d-iaYDPvPd.d.cts → bookingCopy.d-D952V8Tq.d.cts} +148 -148
  18. package/dist/{branding.d-DpNGEdDL.d.ts → branding.d-DC4imCYd.d.ts} +72 -4
  19. package/dist/{branding.d-BFauULV6.d.cts → branding.d-G7rpxDhI.d.cts} +72 -4
  20. package/dist/{casesRepository.d-CCJJQXnl.d.ts → casesRepository.d-CnJZlUZ4.d.ts} +1 -1
  21. package/dist/{casesRepository.d-G2dahIKO.d.cts → casesRepository.d-bWJHZD-_.d.cts} +1 -1
  22. package/dist/chat/index.cjs +59 -47
  23. package/dist/chat/index.d.cts +11 -11
  24. package/dist/chat/index.d.ts +11 -11
  25. package/dist/chat/index.js +59 -47
  26. package/dist/chat/lite/index.cjs +59 -47
  27. package/dist/chat/lite/index.d.cts +11 -11
  28. package/dist/chat/lite/index.d.ts +11 -11
  29. package/dist/chat/lite/index.js +59 -47
  30. package/dist/{chatHandoffToken.d-DVv9tl8h.d.ts → chatHandoffToken.d-BCEdhZpd.d.ts} +5 -5
  31. package/dist/{chatHandoffToken.d-xmnHrTA5.d.cts → chatHandoffToken.d-uKnSnIzN.d.cts} +5 -5
  32. package/dist/{chatTypes.d-CQC7GTdE.d.cts → chatTypes.d-CFyYBzps.d.cts} +4 -4
  33. package/dist/{chatTypes.d-hS1AilYl.d.ts → chatTypes.d-DbdF3ij5.d.ts} +4 -4
  34. package/dist/chunk-EMINPX6C.js +14 -0
  35. package/dist/{chunk-2NA7TPUA.js → chunk-NO7LYPKW.js} +1 -1
  36. package/dist/chunk-QG4ZH45Q.js +47 -0
  37. package/dist/chunk-VY5VTLFX.js +34 -0
  38. package/dist/client/index.cjs +9 -8
  39. package/dist/client/index.d.cts +18 -12
  40. package/dist/client/index.d.ts +18 -12
  41. package/dist/client/index.js +9 -8
  42. package/dist/{clinicBatch.d-BpP2NBb3.d.ts → clinicBatch.d-C_kZtYt-.d.ts} +2 -2
  43. package/dist/{clinicBatch.d-4PFwKJfw.d.cts → clinicBatch.d-e3Cn5HhA.d.cts} +2 -2
  44. package/dist/{config.d-D9igq-vT.d.ts → config.d--6siaeNg.d.ts} +14 -6
  45. package/dist/{config.d-cX5E6DAw.d.cts → config.d-Ba21AaZg.d.cts} +14 -6
  46. package/dist/consent/index.cjs +2 -2
  47. package/dist/consent/index.d.cts +5 -5
  48. package/dist/consent/index.d.ts +5 -5
  49. package/dist/consent/index.js +2 -2
  50. package/dist/{context.d-BrRRNw9I.d.cts → context.d-DLHTf-fV.d.cts} +7 -7
  51. package/dist/{context.d-hPfsEsNf.d.ts → context.d-TArU_9lj.d.ts} +7 -7
  52. package/dist/{copy.d-CDlirTR4.d.ts → copy.d-GokMma80.d.ts} +2 -2
  53. package/dist/{copy.d-DWjSkbrZ.d.cts → copy.d-zWWCn3wB.d.cts} +2 -2
  54. package/dist/core/index.cjs +4 -4
  55. package/dist/core/index.d.cts +17 -17
  56. package/dist/core/index.d.ts +17 -17
  57. package/dist/core/index.js +4 -4
  58. package/dist/{depth.d-CfBorxcQ.d.ts → depth.d-C_HL8yAz.d.ts} +2 -2
  59. package/dist/{depth.d-KkrGx98U.d.cts → depth.d-De5pT7vA.d.cts} +2 -2
  60. package/dist/{entitlementRepository.d-DpQrIgW6.d.ts → entitlementRepository.d-CoKN-Ksa.d.ts} +3 -3
  61. package/dist/{entitlementRepository.d-BvnWpcQH.d.cts → entitlementRepository.d-Tj7lvs4e.d.cts} +3 -3
  62. package/dist/{focus.d-CYwVLDvR.d.ts → focus.d-7G0BBmA9.d.ts} +3 -128
  63. package/dist/{focus.d-9loikWy8.d.cts → focus.d-B0qweva0.d.cts} +3 -128
  64. package/dist/health-plan/index.cjs +133 -92
  65. package/dist/health-plan/index.d.cts +33 -18
  66. package/dist/health-plan/index.d.ts +33 -18
  67. package/dist/health-plan/index.js +141 -100
  68. package/dist/healthPlanRepository.d-CdCyUWph.d.ts +131 -0
  69. package/dist/healthPlanRepository.d-fPbLceBr.d.cts +131 -0
  70. package/dist/{idempotency.d-DGQ_xML5.d.ts → idempotency.d-CoUlC-Yd.d.ts} +1 -1
  71. package/dist/{idempotency.d-CVKkUhY4.d.cts → idempotency.d-IDta7Jjj.d.cts} +1 -1
  72. package/dist/{identity.d-DR5YwO6E.d.ts → identity.d-B7dPRGqm.d.ts} +1 -1
  73. package/dist/{identity.d-Bnl5Z0MM.d.cts → identity.d-_MK9Y7a4.d.cts} +1 -1
  74. package/dist/inbox.d-ChNXTovj.d.cts +103 -0
  75. package/dist/inbox.d-CuuPTWyW.d.ts +103 -0
  76. package/dist/index.cjs +69 -56
  77. package/dist/index.d.cts +18 -18
  78. package/dist/index.d.ts +18 -18
  79. package/dist/index.js +69 -56
  80. package/dist/{introEvents.d-D_yL7lnE.d.ts → introEvents.d-D6Ay0ORN.d.ts} +1 -1
  81. package/dist/{introEvents.d-JmPqEqMQ.d.cts → introEvents.d-JvAWRKYu.d.cts} +1 -1
  82. package/dist/{usePresentation.d-CrobH0d_.d.cts → layout.d-ByfOEhpG.d.cts} +2 -136
  83. package/dist/{usePresentation.d-CDNK4MDY.d.ts → layout.d-D3d4QMeO.d.ts} +2 -136
  84. package/dist/notifications/inbox/index.cjs +24 -12
  85. package/dist/notifications/inbox/index.d.cts +87 -6
  86. package/dist/notifications/inbox/index.d.ts +87 -6
  87. package/dist/notifications/inbox/index.js +24 -12
  88. package/dist/notifications/index.d.cts +7 -7
  89. package/dist/notifications/index.d.ts +7 -7
  90. package/dist/{optInView.d-CZvKlq-o.d.ts → optInView.d-BpFTJaaX.d.ts} +2 -2
  91. package/dist/{optInView.d-BizcW_QG.d.cts → optInView.d-Bxvg0WLJ.d.cts} +2 -2
  92. package/dist/{pets.d-uCzgFbGi.d.ts → pets.d-Br960ekh.d.ts} +1 -1
  93. package/dist/{pets.d-C4CWxQPh.d.cts → pets.d-BtbJcf8T.d.cts} +1 -1
  94. package/dist/{petsRepository.d-DOcVv9bd.d.cts → petsRepository.d-Bj9rPnCr.d.cts} +1 -1
  95. package/dist/{petsRepository.d-DRW7NkKm.d.ts → petsRepository.d-CSOth5XE.d.ts} +1 -1
  96. package/dist/photo/index.cjs +1 -1
  97. package/dist/photo/index.js +1 -1
  98. package/dist/{presentation.d-Bs8xQ4gD.d.cts → presentation.d-BvZs_jN-.d.cts} +6 -0
  99. package/dist/{presentation.d-Bs8xQ4gD.d.ts → presentation.d-BvZs_jN-.d.ts} +6 -0
  100. package/dist/records/depth/index.cjs +10 -6
  101. package/dist/records/depth/index.d.cts +9 -9
  102. package/dist/records/depth/index.d.ts +9 -9
  103. package/dist/records/depth/index.js +10 -6
  104. package/dist/records/index.cjs +302 -207
  105. package/dist/records/index.d.cts +144 -17
  106. package/dist/records/index.d.ts +144 -17
  107. package/dist/records/index.js +302 -207
  108. package/dist/{requestFunnel.d-CQ0O8fMG.d.cts → requestFunnel.d-BwO-jFLX.d.cts} +2 -2
  109. package/dist/{requestFunnel.d-BYLycQMI.d.ts → requestFunnel.d-LSnmCusf.d.ts} +2 -2
  110. package/dist/{route.d-DFJ0gXj8.d.ts → route.d-Bzyamuxa.d.ts} +2 -2
  111. package/dist/{route.d-q9yndhFy.d.cts → route.d-D70-OHBc.d.cts} +2 -2
  112. package/dist/{runtimeTypes.d-3LRuzxr7.d.cts → runtimeTypes.d-BHdN-9aB.d.cts} +7 -7
  113. package/dist/{runtimeTypes.d-BJHYj2MI.d.ts → runtimeTypes.d-L_CbeCKS.d.ts} +7 -7
  114. package/dist/{screenProps.d-DfAmuKkr.d.cts → screenProps.d-DB5IMaGZ.d.cts} +1 -1
  115. package/dist/{screenProps.d-tVzlXGaN.d.ts → screenProps.d-HGSPNGHt.d.ts} +1 -1
  116. package/dist/server/events/index.cjs +1 -1
  117. package/dist/server/events/index.d.cts +2 -2
  118. package/dist/server/events/index.d.ts +2 -2
  119. package/dist/server/events/index.js +1 -1
  120. package/dist/server/index.cjs +1 -1
  121. package/dist/server/index.d.cts +3 -3
  122. package/dist/server/index.d.ts +3 -3
  123. package/dist/server/index.js +1 -1
  124. package/dist/shop/index.cjs +26 -13
  125. package/dist/shop/index.d.cts +3 -3
  126. package/dist/shop/index.d.ts +3 -3
  127. package/dist/shop/index.js +26 -13
  128. package/dist/slots/index.cjs +299 -0
  129. package/dist/slots/index.d.cts +155 -0
  130. package/dist/slots/index.d.ts +155 -0
  131. package/dist/slots/index.js +299 -0
  132. package/dist/slots/weather-glyphs/index.cjs +2 -0
  133. package/dist/slots/weather-glyphs/index.d.cts +11 -0
  134. package/dist/slots/weather-glyphs/index.d.ts +11 -0
  135. package/dist/slots/weather-glyphs/index.js +2 -0
  136. package/dist/tabs/index.cjs +43 -12
  137. package/dist/tabs/index.d.cts +79 -8
  138. package/dist/tabs/index.d.ts +79 -8
  139. package/dist/tabs/index.js +43 -12
  140. package/dist/televet/booking/index.cjs +54 -10
  141. package/dist/televet/booking/index.d.cts +51 -10
  142. package/dist/televet/booking/index.d.ts +51 -10
  143. package/dist/televet/booking/index.js +55 -11
  144. package/dist/televet/call/index.cjs +1 -1
  145. package/dist/televet/call/index.js +1 -1
  146. package/dist/televet/index.cjs +1 -1
  147. package/dist/televet/index.d.cts +2 -2
  148. package/dist/televet/index.d.ts +2 -2
  149. package/dist/televet/index.js +1 -1
  150. package/dist/testing/index.d.cts +1 -1
  151. package/dist/testing/index.d.ts +1 -1
  152. package/dist/testing/rn/index.cjs +1 -1
  153. package/dist/testing/rn/index.d.cts +13 -11
  154. package/dist/testing/rn/index.d.ts +13 -11
  155. package/dist/testing/rn/index.js +1 -1
  156. package/dist/testing/web/index.d.cts +10 -10
  157. package/dist/testing/web/index.d.ts +10 -10
  158. package/dist/texting/index.cjs +2 -2
  159. package/dist/texting/index.d.cts +5 -5
  160. package/dist/texting/index.d.ts +5 -5
  161. package/dist/texting/index.js +2 -2
  162. package/dist/{threadOptions.d-I6G3BdlP.d.cts → threadOptions.d-CS-Qu_rR.d.cts} +6 -6
  163. package/dist/{threadOptions.d-DfH26dy7.d.ts → threadOptions.d-FzFN0zsK.d.ts} +6 -6
  164. package/dist/{timelineRows.d-uSfr2IP3.d.cts → timelineRows.d-BJRCgmdv.d.cts} +1 -1
  165. package/dist/{timelineRows.d-CugnCOfZ.d.ts → timelineRows.d-CPS4admm.d.ts} +1 -1
  166. package/dist/{tokens.d-BUVqme2D.d.cts → tokens.d-DH1mYjZl.d.cts} +43 -1
  167. package/dist/{tokens.d-BUVqme2D.d.ts → tokens.d-DH1mYjZl.d.ts} +43 -1
  168. package/dist/{typeStyle.d-Ckdh_S-t.d.cts → typeStyle.d-BIDpuYpg.d.cts} +29 -3
  169. package/dist/{typeStyle.d-B9Jo5mDX.d.ts → typeStyle.d-aRhFhBpG.d.ts} +29 -3
  170. package/dist/ui/index.cjs +26 -13
  171. package/dist/ui/index.js +26 -13
  172. package/dist/{useHealthPlanSubscription.d-CVVQIFpG.d.ts → useHealthPlanSubscription.d-SQfx-45x.d.ts} +3 -2
  173. package/dist/{useHealthPlanSubscription.d-DylPMm_m.d.cts → useHealthPlanSubscription.d-zjsvvlhz.d.cts} +3 -2
  174. package/dist/useInboxUnread.d-7p3IWs_A.d.cts +109 -0
  175. package/dist/useInboxUnread.d-BxFKFU4o.d.ts +109 -0
  176. package/dist/usePresentation.d-BHO_uZ31.d.cts +140 -0
  177. package/dist/usePresentation.d-Dr7iD-4Y.d.ts +140 -0
  178. package/dist/{useRecordsDepth.d-BvBYIPii.d.ts → useRecordsDepth.d-BinUa8W9.d.ts} +1 -1
  179. package/dist/{useRecordsDepth.d-Cd5Vyb7D.d.cts → useRecordsDepth.d-Bk8BSerZ.d.cts} +1 -1
  180. package/dist/{useUnread.d-ElAEfgl1.d.ts → useUnread.d-CAeYh82_.d.ts} +10 -7
  181. package/dist/{useUnread.d-B4Yqcteg.d.cts → useUnread.d-DXcRBQw8.d.cts} +10 -7
  182. package/dist/video/index.cjs +1 -1
  183. package/dist/video/index.js +1 -1
  184. package/dist/{view.d-2RWoY9kd.d.ts → view.d-CaH6dZPJ.d.ts} +3 -3
  185. package/dist/{view.d-utmOR2ee.d.cts → view.d-DV4b1cov.d.cts} +3 -3
  186. package/dist/web/consent/index.cjs +1 -1
  187. package/dist/web/consent/index.d.cts +5 -5
  188. package/dist/web/consent/index.d.ts +5 -5
  189. package/dist/web/consent/index.js +1 -1
  190. package/dist/web/health-plan/index.cjs +15 -13
  191. package/dist/web/health-plan/index.d.cts +20 -13
  192. package/dist/web/health-plan/index.d.ts +20 -13
  193. package/dist/web/health-plan/index.js +7 -7
  194. package/dist/web/health-plan/styles.css +6 -2
  195. package/dist/web/inbox/index.cjs +1 -1
  196. package/dist/web/inbox/index.d.cts +7 -5
  197. package/dist/web/inbox/index.d.ts +7 -5
  198. package/dist/web/inbox/index.js +1 -1
  199. package/dist/web/index.cjs +71 -70
  200. package/dist/web/index.d.cts +53 -31
  201. package/dist/web/index.d.ts +53 -31
  202. package/dist/web/index.js +28 -27
  203. package/dist/web/intro/index.cjs +1 -1
  204. package/dist/web/intro/index.d.cts +7 -6
  205. package/dist/web/intro/index.d.ts +7 -6
  206. package/dist/web/intro/index.js +1 -1
  207. package/dist/web/notifications/index.cjs +1 -1
  208. package/dist/web/notifications/index.d.cts +6 -6
  209. package/dist/web/notifications/index.d.ts +6 -6
  210. package/dist/web/notifications/index.js +1 -1
  211. package/dist/web/records/depth/index.cjs +1 -1
  212. package/dist/web/records/depth/index.d.cts +9 -9
  213. package/dist/web/records/depth/index.d.ts +9 -9
  214. package/dist/web/records/depth/index.js +1 -1
  215. package/dist/web/records/index.cjs +1 -1
  216. package/dist/web/records/index.d.cts +11 -11
  217. package/dist/web/records/index.d.ts +11 -11
  218. package/dist/web/records/index.js +1 -1
  219. package/dist/web/records-sheet/index.cjs +3 -3
  220. package/dist/web/records-sheet/index.js +3 -3
  221. package/dist/web/shop/index.cjs +27 -8
  222. package/dist/web/shop/index.d.cts +4 -3
  223. package/dist/web/shop/index.d.ts +4 -3
  224. package/dist/web/shop/index.js +3 -3
  225. package/dist/web/televet/booking/index.cjs +53 -53
  226. package/dist/web/televet/booking/index.d.cts +44 -44
  227. package/dist/web/televet/booking/index.d.ts +44 -44
  228. package/dist/web/televet/booking/index.js +53 -53
  229. package/dist/web/televet/call/index.cjs +3 -3
  230. package/dist/web/televet/call/index.d.cts +7 -6
  231. package/dist/web/televet/call/index.d.ts +7 -6
  232. package/dist/web/televet/call/index.js +3 -3
  233. package/dist/web/televet/index.cjs +1 -1
  234. package/dist/web/televet/index.js +1 -1
  235. package/dist/web/texting/index.cjs +1 -1
  236. package/dist/web/texting/index.d.cts +5 -5
  237. package/dist/web/texting/index.d.ts +5 -5
  238. package/dist/web/texting/index.js +1 -1
  239. package/dist/web/ui/index.cjs +29 -10
  240. package/dist/web/ui/index.d.cts +32 -32
  241. package/dist/web/ui/index.d.ts +32 -32
  242. package/dist/web/ui/index.js +2 -2
  243. package/dist/web/ui/styles.css +46 -3
  244. package/package.json +36 -5
  245. package/slots/package.json +8 -0
  246. package/slots/weather-glyphs/package.json +8 -0
  247. package/dist/chunk-IJU5TV5N.js +0 -12
  248. package/dist/chunk-TFX6WMDN.js +0 -30
  249. package/dist/chunk-WZNPR5TY.js +0 -34
  250. package/dist/useInboxUnread.d-DDoSII8D.d.ts +0 -206
  251. package/dist/useInboxUnread.d-Dq3CCAa3.d.cts +0 -206
  252. package/dist/{IntakeMedia.d-Dqc5V_YH.d.cts → IntakeMedia.d-CO8weVGO.d.cts} +35 -35
  253. package/dist/{IntakeMedia.d-DNUAks9E.d.ts → IntakeMedia.d-DnUZJsbj.d.ts} +35 -35
@@ -1,6 +1,6 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import{createContext,forwardRef,createElement,useCallback,useMemo,useRef,useState,useEffect,useSyncExternalStore,useContext,Component,Fragment as Fragment$1}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,Text as Text$1,View,Linking,KeyboardAvoidingView,Dimensions,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as texting from"@everfur/sdk/texting";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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return 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 createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...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",chatTextingAsk:true}),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",chatTextingAsk:"chat_texting_ask"}),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","chatTextingAsk"]);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__ */
3
- return Object.freeze(out)}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";function ok(value,warning){/* @__PURE__ */
2
+ import{createContext,forwardRef,createElement,useCallback,useMemo,useRef,useState,useEffect,useSyncExternalStore,useContext,Component,Fragment as Fragment$1}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,Text as Text$1,View,Linking,KeyboardAvoidingView,Dimensions,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as texting from"@everfur/sdk/texting";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}}function weightBucket(weight){return weight<=450?"regular":weight<=650?"medium":"bold"}var MONO_OF={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(theme,role){let byRole=roleCache.get(theme);byRole===void 0&&(byRole=/* @__PURE__ */new Map,roleCache.set(theme,byRole));let hit=byRole.get(role);if(hit!==void 0)return hit;let style=buildRole(theme,role);return byRole.set(role,style),style}var roleCache=/* @__PURE__ */new WeakMap;function buildRole(theme,role){let r=theme.type.roles[role],weight=r.weight==="400"&&r.face!=="mono"?theme.type.weight.regular:r.weight,bucket=weightBucket(Number(weight)),f=r.face==="mono"?face(theme,MONO_OF[bucket]):r.face==="heading"?headingFace(theme,bucket):face(theme,bucket),faceWeight=r.face==="heading"?theme.type.headingWeight??weight:weight,faceStyle=f.fontWeight===void 0?f:{fontFamily:f.fontFamily,fontWeight:faceWeight},fontSize=r.size,out={...faceStyle,fontSize:fontSize,lineHeight:Math.round(fontSize*r.lineHeight*100)/100};return r.letterSpacing!==0&&(out.letterSpacing=Math.round(fontSize*r.letterSpacing*100)/100),r.uppercase&&(out.textTransform="uppercase"),/* @__PURE__ */Object.freeze(out)}var TYPE_ROLE_DEFAULTS=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});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});var 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,roles:TYPE_ROLE_DEFAULTS,typeScale:1}}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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier,variant:variant,...props}){let theme=useEverfurTheme(),role=variant===void 0?void 0:theme.type.roles[variant],cap=tierMultiplier(theme.type,tier??role?.tier??"content"),styled=variant===void 0?props:{...props,style:[{...textRole(theme,variant),color:theme.color.text.primary,flexShrink:1},props.style]};return createElement(Text$1,cap===void 0?styled:{maxFontSizeMultiplier:cap,...styled})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...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",chatTextingAsk:true,serverSlots:false}),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",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),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","chatTextingAsk","serverSlots"]);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__ */
3
+ return Object.freeze(out)}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",sourcesHeading:"Sources",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";function ok(value,warning){/* @__PURE__ */
4
4
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
5
5
  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 EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=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 RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__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",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),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 assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
6
6
  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 parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}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(
@@ -15,7 +15,7 @@ return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,pro
15
15
  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){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 followUpPolicyFor(host,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count2=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count2===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count2<=0)return{...host??{},count:1,exclude:NONE,fill:[]};let hostExclude=host?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host??{},count:count2,...exclude!==void 0?{exclude:exclude}:{}}}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_MAX2=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_MAX2,{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 str3=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=str3(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str3(o.ref),name:name,dose:str3(o.dose),frequency:str3(o.frequency),startDate:str3(o.start_date),endDate:str3(o.end_date),notes:str3(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
16
16
  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:str3(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str3(o.food_brand),foodType:str3(o.food_type),microchipId:str3(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str3(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str3(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str3(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str3(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str3(row.ref),conditionName:conditionName,diagnosedDate:str3(row.diagnosed_date),notes:str3(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 invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid2(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid2(`${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:invalid2(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid2("pet_ref must be a string");if(petRef.trim().length===0)return invalid2("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid2("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid2("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:invalid2(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid2("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:invalid2("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 str4=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__ */
17
17
  return Object.freeze({petRef:str4(o.pet_ref)??petRef,name:str4(o.name),species:str4(o.species),breed:str4(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=str4(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str4(o.pet_id),petRef:petRef,name:str4(o.name),species:str4(o.species),breed:str4(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str4(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__ */
18
- 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 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=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=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef===null||bodyKey===null?null:`${String(userRef)}|${scopeEpoch}|${petRef}|${bodyKey}`,run=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]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return 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]=useState(NONE2),pending=useRef(null),knownIds=useRef([]);knownIds.current=messages.map(message=>message.id),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=useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}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)}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 clean3=sanitizeSeedPrompt(prompt),id=clean3===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean3}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight2=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean3===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(clean3)).then(settle,()=>settle(void 0))},[clean3,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===null||state.activeConversationId.length===0?null:state.activeConversationId;return conversationId===null&&state.refreshesBlankThread!==true?{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}}var OPEN_UNREAD_HEAD=/* @__PURE__ */Object.freeze({openUnreadHead:true});function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh,refreshesBlankThread:refreshesBlankThread}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,refreshesBlankThread:refreshesBlankThread===true,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(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}var HANDOFF_TOKEN=/^efch_[A-Za-z0-9_-]{43}$/,FRAGMENT_KEY="efch";function isChatHandoffToken(value){return typeof value=="string"&&HANDOFF_TOKEN.test(value)}function chatHandoffTokenFromUrl(url){if(typeof url!="string")return null;let hash=url.indexOf("#");if(hash<0)return null;for(let pair of url.slice(hash+1).split("&")){if(!pair.startsWith(`${FRAGMENT_KEY}=`))continue;let value=pair.slice(FRAGMENT_KEY.length+1);return isChatHandoffToken(value)?value:null}return null}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 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}}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...{}})}var MAX_PET_REF_LENGTH=128,CONTROL_CHAR=/[\u0000-\u001f\u007f]/;function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function petRefOf(value){return typeof value!="string"||value.length===0||value.length>MAX_PET_REF_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")?null:value}function targetOf(body){if(body===null)return null;let conversationId=body.conversation_id,petRef=petRefOf(body.pet_ref);return typeof conversationId!="string"||!validConversationId(conversationId)||petRef===null?null:{conversationId:conversationId,petRef:petRef}}function redeemChatHandoff(auth,token,errorPolicy){return isChatHandoffToken(token)?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:token}},{maxAttempts:1}).then(result=>result.ok?ok(targetOf(record(result.value))):result.error.httpStatus===404?ok(null):err(result.error),()=>err(makeError("internalError",false))):Promise.resolve(ok(null))}function useChatHandoffTarget(token,context){let runtime=context?.runtime??null,userRef=context?.userRef??null,valid=isChatHandoffToken(token)?token:null,key=valid===null||userRef===null?null:`${String(userRef)}|${valid}`,[landed,setLanded]=useState(null);return useEffect(()=>{if(key===null||valid===null||userRef===null||runtime===null)return;let live=true,services=runtime.registry.services;return redeemChatHandoff(services.authFor(userRef),valid,services.errorPolicy).then(result=>{!live||!result.ok||result.value===null||setLanded({key:key,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:result.value.conversationId,petRef:result.value.petRef})})}),()=>{live=false}},[key,runtime,valid,userRef]),landed!==null&&landed.key===key?landed.target:void 0}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,scope){let key=targetKey(target),forChat=target?.kind==="chat",wanted=target?.petRef??null,elsewhere=forChat&&!scope.pinned&&wanted!==null&&scope.petRef!==null&&wanted!==scope.petRef,latest=useRef({openCheckin:openCheckin,target:target,selectPet:scope.selectPet});latest.current={openCheckin:openCheckin,target:target,selectPet:scope.selectPet};let opened=useRef(null),moved=useRef(null),petRef=scope.petRef;useEffect(()=>{if(key===null||opened.current===key)return;let{openCheckin:open,target:current,selectPet:selectPet}=latest.current;if(elsewhere&&wanted!==null){if(moved.current?.key!==key){moved.current={key:key,from:petRef},selectPet(wanted);return}petRef!==moved.current.from&&(opened.current=key);return}forChat&&!scope.ready||(opened.current=key,!(open===void 0||current===void 0)&&Promise.resolve(open(current)).catch(()=>{}))},[key,forChat,elsewhere,wanted,petRef,scope.ready])}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(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`: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]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=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=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]=useState(null),[expanded,setExpanded]=useState(false);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=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return 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 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 createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children: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=useMemo(()=>selectView2(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
18
+ 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 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=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=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef===null||bodyKey===null?null:`${String(userRef)}|${scopeEpoch}|${petRef}|${bodyKey}`,run=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]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return 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]=useState(NONE2),pending=useRef(null),knownIds=useRef([]);knownIds.current=messages.map(message=>message.id),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=useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}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)}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 clean3=sanitizeSeedPrompt(prompt),id=clean3===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean3}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight2=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean3===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(clean3)).then(settle,()=>settle(void 0))},[clean3,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===null||state.activeConversationId.length===0?null:state.activeConversationId;return conversationId===null&&state.refreshesBlankThread!==true?{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}}var OPEN_UNREAD_HEAD=/* @__PURE__ */Object.freeze({openUnreadHead:true});function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh,refreshesBlankThread:refreshesBlankThread}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,refreshesBlankThread:refreshesBlankThread===true,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(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}var HANDOFF_TOKEN=/^efch_[A-Za-z0-9_-]{43}$/,FRAGMENT_KEY="efch";function isChatHandoffToken(value){return typeof value=="string"&&HANDOFF_TOKEN.test(value)}function chatHandoffTokenFromUrl(url){if(typeof url!="string")return null;let hash=url.indexOf("#");if(hash<0)return null;for(let pair of url.slice(hash+1).split("&")){if(!pair.startsWith(`${FRAGMENT_KEY}=`))continue;let value=pair.slice(FRAGMENT_KEY.length+1);return isChatHandoffToken(value)?value:null}return null}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 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}}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...{}})}var MAX_PET_REF_LENGTH=128,CONTROL_CHAR=/[\u0000-\u001f\u007f]/;function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function petRefOf(value){return typeof value!="string"||value.length===0||value.length>MAX_PET_REF_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")?null:value}function targetOf(body){if(body===null)return null;let conversationId=body.conversation_id,petRef=petRefOf(body.pet_ref);return typeof conversationId!="string"||!validConversationId(conversationId)||petRef===null?null:{conversationId:conversationId,petRef:petRef}}function redeemChatHandoff(auth,token,errorPolicy){return isChatHandoffToken(token)?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:token}},{maxAttempts:1}).then(result=>result.ok?ok(targetOf(record(result.value))):result.error.httpStatus===404?ok(null):err(result.error),()=>err(makeError("internalError",false))):Promise.resolve(ok(null))}function useChatHandoffTarget(token,context){let runtime=context?.runtime??null,userRef=context?.userRef??null,valid=isChatHandoffToken(token)?token:null,key=valid===null||userRef===null?null:`${String(userRef)}|${valid}`,[landed,setLanded]=useState(null);return useEffect(()=>{if(key===null||valid===null||userRef===null||runtime===null)return;let live=true,services=runtime.registry.services;return redeemChatHandoff(services.authFor(userRef),valid,services.errorPolicy).then(result=>{!live||!result.ok||result.value===null||setLanded({key:key,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:result.value.conversationId,petRef:result.value.petRef})})}),()=>{live=false}},[key,runtime,valid,userRef]),landed!==null&&landed.key===key?landed.target:void 0}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,scope){let key=targetKey(target),forChat=target?.kind==="chat",wanted=target?.petRef??null,elsewhere=forChat&&!scope.pinned&&wanted!==null&&scope.petRef!==null&&wanted!==scope.petRef,latest=useRef({openCheckin:openCheckin,target:target,selectPet:scope.selectPet});latest.current={openCheckin:openCheckin,target:target,selectPet:scope.selectPet};let opened=useRef(null),moved=useRef(null),petRef=scope.petRef;useEffect(()=>{if(key===null||opened.current===key)return;let{openCheckin:open,target:current,selectPet:selectPet}=latest.current;if(elsewhere&&wanted!==null){if(moved.current?.key!==key){moved.current={key:key,from:petRef},selectPet(wanted);return}petRef!==moved.current.from&&(opened.current=key);return}forChat&&!scope.ready||(opened.current=key,!(open===void 0||current===void 0)&&Promise.resolve(open(current)).catch(()=>{}))},[key,forChat,elsewhere,wanted,petRef,scope.ready])}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(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`: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]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=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=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]=useState(null),[expanded,setExpanded]=useState(false);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=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return 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 HostRenderBoundary=class extends 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 createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children: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=useMemo(()=>selectView2(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
19
19
  return jsx(View,{style:[styles3.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles3.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
20
20
  return jsx(View,{style:[styles3.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles3.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth: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 EVERFUR_LINK_DOMAIN="everfur.com",MAX_LINK_LENGTH=2048,HOST_ENTRY=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function normalizeLinkHosts(hosts){if(!Array.isArray(hosts))return[];let out=/* @__PURE__ */new Set;for(let entry of hosts){if(typeof entry!="string")continue;let host=entry.trim().toLowerCase();host.length<=253&&HOST_ENTRY.test(host)&&out.add(host)}/* @__PURE__ */
21
21
  return Object.freeze([...out])}function isLinkHost(hostname,hosts){if(hostname===EVERFUR_LINK_DOMAIN||hostname.endsWith(`.${EVERFUR_LINK_DOMAIN}`))return true;for(let entry of hosts)if(entry.startsWith("*.")?hostname.endsWith(entry.slice(1)):hostname===entry)return true;return false}function linkHref(raw,hosts){if(typeof raw!="string"||raw.length===0||raw.length>MAX_LINK_LENGTH||!/^https:\/\//i.test(raw))return null;let url=parseUrl(raw);return url===null||url.protocol!=="https:"||url.username!==""||url.password!==""||url.port!==""?null:isLinkHost(url.hostname,hosts)?url.href:null}function openInBrowser(href){try{Promise.resolve(Linking.openURL(href)).catch(()=>{})}catch{}}var MessageLinksContext=createContext(null);function useMessageLinks(){return useContext(MessageLinksContext)??void 0}function MessageLinksScope({linkHosts:linkHosts,onOpenUrl:onOpenUrl,children:children}){let key=Array.isArray(linkHosts)?linkHosts.join(`\n`):null,value=useMemo(()=>{if(key===null)return null;let hosts=normalizeLinkHosts(key===""?[]:key.split(`\n`));/* @__PURE__ */
@@ -78,10 +78,15 @@ return jsxs(View,{style:box(size),testID:testID,...HIDDEN,children:[
78
78
  /* @__PURE__ */jsx(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__ */
79
79
  return jsxs(View,{style:box(size),...HIDDEN,children:[
80
80
  /* @__PURE__ */jsx(View,{style:{width:size*.8,height:size*.6,marginTop:-size*.12,borderWidth:w,borderColor:color,borderRadius:size*.14}}),
81
- /* @__PURE__ */jsx(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=useRef(null);return ref.current===null&&(ref.current=new 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 useEffect(()=>{if(durationMs<=0){value.setValue(1);return}let timing=Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?Animated.sequence([Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),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]=useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return useEffect(()=>{if(visible){setMounted(true);let animation2=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=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__ */jsx(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]=useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);useEffect(()=>{if(durationMs<=0)return;let animation=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 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=useRef(null),head=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 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=useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
81
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:size*.1,left:size*.22,width:size*.2,height:size*.2,borderLeftWidth:w,borderBottomWidth:w,borderColor:color}})]})}function HistoryGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),face2=size*.72,centre=size/2;/* @__PURE__ */
82
+ return jsxs(View,{style:box(size),...HIDDEN,children:[
83
+ /* @__PURE__ */jsx(View,{style:{width:face2,height:face2,borderRadius:face2/2,borderWidth:w,borderColor:color,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
84
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.16,left:size*.12,width:size*.2,height:size*.2,borderLeftWidth:w,borderBottomWidth:w,borderColor:color}}),
85
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:centre-size*.2,left:centre-w/2,width:w,height:size*.2+w/2,borderRadius:w,backgroundColor:color}}),
86
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:centre-w/2,left:centre-w/2,width:size*.15+w/2,height:w,borderRadius:w,backgroundColor: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=useRef(null);return ref.current===null&&(ref.current=new 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 useEffect(()=>{if(durationMs<=0){value.setValue(1);return}let timing=Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?Animated.sequence([Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),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]=useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return useEffect(()=>{if(visible){setMounted(true);let animation2=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=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__ */jsx(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]=useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);useEffect(()=>{if(durationMs<=0)return;let animation=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 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=useRef(null),head=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 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=useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
82
87
  return jsx(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__ */jsx(Animated.View,{style:[style,{transform:[{scale:scale}]}],children:children})})}function useRevealedText(text3,revealing,motion){let ticking=revealing&&motion.revealTickMs>0,[visible,setVisible]=useState(0),latest=useRef(text3);return latest.current=text3,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,Platform.OS==="android"&&typeof UIManager.setLayoutAnimationEnabledExperimental=="function"&&UIManager.setLayoutAnimationEnabledExperimental(true)),LayoutAnimation.configureNext({duration:motion.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function useAnimateLayoutOn(key,motion){let previous=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=useSafeAreaInsets();return uri===null?null:/* @__PURE__ */jsxs(Modal,{visible:true,animationType:theme.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:onClose,children:[
83
88
  /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,style:styles.backdrop,onPress:onClose,children:/* @__PURE__ */jsx(Image,{source:{uri:uri},style:styles.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:label,accessibilityIgnoresInvertColors:true})}),
84
- /* @__PURE__ */jsx(View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=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 noop=()=>{};function createAppStateLifecycle(){return{onForeground(listener){let subscription;try{let away=AppState.currentState==="background";subscription=AppState.addEventListener("change",next=>{next==="background"?away=!0:next==="active"&&away&&(away=!1,listener())})}catch{return noop}return()=>subscription.remove()}}}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 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 FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;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__ */
89
+ /* @__PURE__ */jsx(View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=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 noop=()=>{};function createAppStateLifecycle(){return{onForeground(listener){let subscription;try{let away=AppState.currentState==="background";subscription=AppState.addEventListener("change",next=>{next==="background"?away=!0:next==="active"&&away&&(away=!1,listener())})}catch{return noop}return()=>subscription.remove()}}}function slotBox(slot2,borderWidth){if(slot2===void 0)return{};let out={};return slot2.backgroundColor!==void 0&&(out.backgroundColor=slot2.backgroundColor),slot2.borderColor!==void 0&&(out.borderColor=slot2.borderColor,out.borderWidth=borderWidth??1),slot2.borderRadius!==void 0&&(out.borderRadius=slot2.borderRadius),out}function ownGroundSlot(slot2){return slot2===void 0||slot2.backgroundColor!==void 0?slot2:slot2.borderRadius===void 0?void 0:{borderRadius:slot2.borderRadius}}function slotText(slot2){return slot2?.textColor===void 0?{}:{color:slot2.textColor}}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 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 FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;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__ */
85
90
  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,str5=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str5(o.upload_id),uploadUrl=str5(o.upload_url),s3Key=str5(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__ */
86
91
  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:str5(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,snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed2=false,publish2=()=>{snapshot2=/* @__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:()=>snapshot2,get uploading(){return snapshot2.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot2.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(),snapshot2=/* @__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=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=useMemo(()=>options.queue??build(),[options.queue,build]),disposed2=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;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 snapshot2=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=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=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot2.attachments.some(row=>row.status==="uploading"),failed=snapshot2.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot2.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot2.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,snapshot2,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var DICTATION_ERROR_VISIBLE_MS=6e3;function composeDictatedText(base2,transcript,maxLength){let spoken=transcript.trim();if(!spoken)return base2;let separator=base2===""||/\s$/.test(base2)?"":" ",text3=`${base2}${separator}${spoken}`;return typeof maxLength=="number"&&maxLength>0?text3.slice(0,maxLength):text3}function formatDictationElapsed(elapsedMs){let totalSeconds=Math.max(0,Math.floor(elapsedMs/1e3)),minutes=Math.floor(totalSeconds/60),seconds=totalSeconds%60;return`${minutes}:${seconds.toString().padStart(2,"0")}`}function dictationErrorMessage(kind){switch(kind){case"permissionDenied":return CHAT_COPY.micBlocked;case"noSpeech":return CHAT_COPY.noSpeech;case"unavailable":return CHAT_COPY.dictationUnavailable}}function trackDictationEvent(telemetry,name,properties){if(telemetry)try{telemetry.track(name,{...properties})}catch{}}var DICTATION_VOCABULARY=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function buildDictationPhrases(pet={}){let seen=/* @__PURE__ */new Set,phrases=[];for(let candidate of[pet.name,pet.breed,...DICTATION_VOCABULARY]){let phrase=(candidate??"").trim();if(!phrase)continue;let key=phrase.toLowerCase();if(!seen.has(key)&&(seen.add(key),phrases.push(phrase),phrases.length>=100))break}return phrases}function useChatDraft(send,conversationId,seed){let[state,setState]=useState({send:send,conversationId:conversationId,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId);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=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,paused=false){let latest=useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=useRef(null),[settled,setSettled]=useState(null);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]),useEffect(()=>{store===void 0||paused||settled!==`${conversationId??""}`||callHost(()=>store.write(conversationId,draft))},[store,conversationId,draft,settled,paused])}function announceLine(line){if(!(Platform.OS!=="ios"||line===""))try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,line)}catch{}}function AnnounceLine({line:line}){return useEffect(()=>{announceLine(line)},[line]),null}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(),styles3=useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
87
92
  return jsxs(View,{style:styles3.anchor,pointerEvents:"box-none",children:[
@@ -91,23 +96,23 @@ return jsxs(View,{style:styles3.anchor,pointerEvents:"box-none",children:[
91
96
  /* @__PURE__ */jsx(View,{style:styles3.tileIconWrap,children:source==="photo"?/* @__PURE__ */jsx(PhotoGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */jsx(CameraGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5})}),
92
97
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.tileLabel,children:TILE_LABEL[source]})]},source))}),
93
98
  /* @__PURE__ */jsx(View,{style:styles3.tail}),
94
- /* @__PURE__ */jsx(View,{style:styles3.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(from.b,to.b));if(reads(candidate))return candidate}return pole}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxs(View,{style:styles3.strip,children:[attachments.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:attachments.map(row=>/* @__PURE__ */jsx(PreviewCard,{row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=useRef(row.status),[flash,setFlash]=useState(false);return useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxs(View,{style:styles3.card,children:[
99
+ /* @__PURE__ */jsx(View,{style:styles3.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxs(View,{style:styles3.strip,children:[attachments.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:attachments.map(row=>/* @__PURE__ */jsx(PreviewCard,{row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=useRef(row.status),[flash,setFlash]=useState(false);return useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxs(View,{style:styles3.card,children:[
95
100
  /* @__PURE__ */jsx(Pressable,{accessibilityRole:uploaded?"button":"image",accessibilityLabel:uploaded?fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}):row.filename,accessibilityState:{busy:uploading,disabled:!uploaded},disabled:!uploaded,style:styles3.thumbHit,onPress:()=>onPreview(row),children:/* @__PURE__ */jsxs(View,{style:styles3.thumb,children:[
96
101
  /* @__PURE__ */jsx(Image,{source:{uri:row.previewUri},style:styles3.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),uploading?/* @__PURE__ */jsx(View,{style:styles3.uploadingOverlay,children:/* @__PURE__ */jsx(ActivityIndicator,{size:"small",color:theme.color.surface})}):null,flash?/* @__PURE__ */jsx(SuccessFlash,{styles:styles3,onDone:()=>setFlash(false)}):null]})}),failed?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),style:styles3.failedOverlay,onPress:()=>onRetry(row.id),children:/* @__PURE__ */jsx(View,{style:styles3.failedInner,children:/* @__PURE__ */jsx(CloseGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}):null,
97
102
  /* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),hitSlop:6,containerStyle:styles3.removeSlot,style:styles3.removeButton,onPress:()=>onRemove(row.id),children:/* @__PURE__ */jsx(CloseGlyph,{size:REMOVE_GLYPH,color:theme.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:styles3,onDone:onDone}){let theme=useEverfurTheme(),motion=useChatMotion(),opacity=useRef(null);opacity.current===null&&(opacity.current=new Animated.Value(0));let value=opacity.current;return useEffect(()=>{let animation=Animated.sequence([Animated.timing(value,{toValue:1,duration:SUCCESS_FLASH_FADE_IN_MS,useNativeDriver:true}),Animated.delay(motion.uploadFlashMs),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__ */jsx(Animated.View,{pointerEvents:"none",style:[styles3.successOverlay,{opacity:value}],children:/* @__PURE__ */jsx(CheckGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}function SentImages({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
98
103
  return jsx(View,{style:single?styles3.sentSingle:styles3.sentGrid,children:images.map((image,index)=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onPress:()=>onPreview(image),children:/* @__PURE__ */jsx(Image,{source:{uri:image.uri},style:single?styles3.singleImage:styles3.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${image.uri}-${index}`))})}function makeStyles3(theme){let c=theme.color,t=theme.type;return 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: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__ */
99
- 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(slot2,borderWidth){if(slot2===void 0)return{};let out={};return slot2.backgroundColor!==void 0&&(out.backgroundColor=slot2.backgroundColor),slot2.borderColor!==void 0&&(out.borderColor=slot2.borderColor,out.borderWidth=borderWidth??1),slot2.borderRadius!==void 0&&(out.borderRadius=slot2.borderRadius),out}function ownGroundSlot(slot2){return slot2===void 0||slot2.backgroundColor!==void 0?slot2:slot2.borderRadius===void 0?void 0:{borderRadius:slot2.borderRadius}}function slotText(slot2){return slot2?.textColor===void 0?{}:{color:slot2.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,ASK_CHIP_EDGE_WIDTH=1.5,ASK_CHIP_LINE_HEIGHT=1.3,RULE_WIDTH=1,TURN_NOTICE_EDGE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,FOOTNOTE_IN_THREAD_LEAD=1.5,EMPTY_PADDING_TOP="12%",ASSISTANT_AVATAR_SIZE=20;function useChatTheme(){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles4(theme),[theme]);return{theme:theme,styles:styles3}}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 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},homeEmpty:{flexGrow:1},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.md,backgroundColor:c.surfaceCream,borderWidth:TURN_NOTICE_EDGE_WIDTH,borderColor:c.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight},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},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:s.xs,paddingVertical:s.md,paddingHorizontal:s.md+s.xs/2,backgroundColor:c.surfaceSubtle,borderRadius:r.md},readingDot:{width:6,height:6,borderRadius:r.pill,backgroundColor:c.brandInk},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:MIN_TOUCH_TARGET,justifyContent:"center",paddingHorizontal:s.md+s.xs/2},earlierLabel:{...face(theme,"monoBold"),color:c.linkInk,fontSize:t.size.caption},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)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.md},askChip:{minHeight:MIN_TOUCH_TARGET,maxWidth:"100%",justifyContent:"center",paddingVertical:s.sm,paddingHorizontal:s.lg,borderRadius:r.pill,borderWidth:ASK_CHIP_EDGE_WIDTH,borderColor:c.brandInk,backgroundColor:c.chatGround,...slotBox(slots.chip,ASK_CHIP_EDGE_WIDTH)},askChipText:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*ASK_CHIP_LINE_HEIGHT),...slotText(slots.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:s.md,marginTop:s.xs},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},dictationError:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger,paddingHorizontal:s.xs},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},footnoteInThread:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:Math.round(t.size.caption*FOOTNOTE_IN_THREAD_LEAD),textAlign:"left",marginTop:s.md,marginBottom:s.sm,paddingHorizontal:s.xs},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var MIC_GLYPH_SIZE=18,STOP_GLYPH_BOX=28,PULSE_INSET=6,PULSE_LOOP_MS=1200,PULSE_LOW=.4,DISABLED_OPACITY=.4;function DictationButton({active:active,listening:listening,elapsedMs:elapsedMs,disabled:disabled=false,onToggle:onToggle}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles5(theme),[theme]);return useEffect(()=>{if(listening)try{AccessibilityInfo.announceForAccessibility(CHAT_COPY.listening)}catch{}},[listening]),/* @__PURE__ */jsxs(View,{style:styles3.wrap,children:[listening?/* @__PURE__ */jsx(Text,{style:styles3.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:formatDictationElapsed(elapsedMs)}):null,
104
+ 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)}})}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,ASK_CHIP_EDGE_WIDTH=1.5,ASK_CHIP_LINE_HEIGHT=1.3,RULE_WIDTH=1,TURN_NOTICE_EDGE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,FOOTNOTE_IN_THREAD_LEAD=1.5,EMPTY_PADDING_TOP="12%",CARDS_THREAD_PAD_TOP=14,CARDS_THREAD_PAD_X=16,CARDS_THREAD_PAD_BOTTOM=28,CARDS_THREAD_GAP=18,CARDS_BUBBLE_MAX_WIDTH="84%",CARDS_BUBBLE_PAD_Y=10,CARDS_BUBBLE_PAD_X=15,CARDS_BUBBLE_LEAD=1.42,CARDS_DOT=4,CARDS_DOT_GAP=3,CARDS_BYLINE_MIN=14,ASSISTANT_AVATAR_SIZE=20;function useChatTheme(){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles4(theme),[theme]);return{theme:theme,styles:styles3}}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 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},homeEmpty:{flexGrow:1},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.md,backgroundColor:c.surfaceCream,borderWidth:TURN_NOTICE_EDGE_WIDTH,borderColor:c.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight},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},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:s.xs,paddingVertical:s.md,paddingHorizontal:s.md+s.xs/2,backgroundColor:c.surfaceSubtle,borderRadius:r.md},readingDot:{width:6,height:6,borderRadius:r.pill,backgroundColor:c.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:CARDS_DOT_GAP,minHeight:CARDS_BYLINE_MIN},readingDotInline:{width:CARDS_DOT,height:CARDS_DOT,borderRadius:r.pill,backgroundColor:c.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:MIN_TOUCH_TARGET,justifyContent:"center",paddingHorizontal:s.md+s.xs/2},earlierLabel:{...face(theme,"monoBold"),color:c.linkInk,fontSize:t.size.caption},listContent:{padding:s.lg,gap:s.xl},listContentCards:{paddingTop:CARDS_THREAD_PAD_TOP,paddingHorizontal:CARDS_THREAD_PAD_X,paddingBottom:CARDS_THREAD_PAD_BOTTOM,gap:CARDS_THREAD_GAP},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)},bubbleCards:{maxWidth:CARDS_BUBBLE_MAX_WIDTH},bubbleUserCards:{paddingVertical:CARDS_BUBBLE_PAD_Y,paddingHorizontal:CARDS_BUBBLE_PAD_X},bubbleTextUserCards:{fontSize:textRole(theme,"message").fontSize,lineHeight:Math.round(textRole(theme,"message").fontSize*CARDS_BUBBLE_LEAD)},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)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.md},askChip:{minHeight:MIN_TOUCH_TARGET,maxWidth:"100%",justifyContent:"center",paddingVertical:s.sm,paddingHorizontal:s.lg,borderRadius:r.pill,borderWidth:ASK_CHIP_EDGE_WIDTH,borderColor:c.brandInk,backgroundColor:c.chatGround,...slotBox(slots.chip,ASK_CHIP_EDGE_WIDTH)},askChipText:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*ASK_CHIP_LINE_HEIGHT),...slotText(slots.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:s.md,marginTop:s.xs},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},dictationError:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger,paddingHorizontal:s.xs},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},footnoteInThread:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:Math.round(t.size.caption*FOOTNOTE_IN_THREAD_LEAD),textAlign:"left",marginTop:s.md,marginBottom:s.sm,paddingHorizontal:s.xs},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var MIC_GLYPH_SIZE=18,STOP_GLYPH_BOX=28,PULSE_INSET=6,PULSE_LOOP_MS=1200,PULSE_LOW=.4,DISABLED_OPACITY=.4;function DictationButton({active:active,listening:listening,elapsedMs:elapsedMs,disabled:disabled=false,onToggle:onToggle}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles5(theme),[theme]);return useEffect(()=>{if(listening)try{AccessibilityInfo.announceForAccessibility(CHAT_COPY.listening)}catch{}},[listening]),/* @__PURE__ */jsxs(View,{style:styles3.wrap,children:[listening?/* @__PURE__ */jsx(Text,{style:styles3.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:formatDictationElapsed(elapsedMs)}):null,
100
105
  /* @__PURE__ */jsx(Pressable,{onPress:()=>onToggle(),disabled:disabled,accessibilityRole:"button",accessibilityLabel:active?CHAT_COPY.stopDictation:CHAT_COPY.dictate,accessibilityState:{selected:active,disabled:disabled},style:[styles3.button,disabled?styles3.buttonDisabled:null],testID:"everfur-dictation-button",children:active?/* @__PURE__ */jsxs(Fragment,{children:[
101
106
  /* @__PURE__ */jsx(Pulse,{style:styles3.pulse,reduced:theme.motion.reducedMotion}),
102
107
  /* @__PURE__ */jsx(StopGlyph,{size:STOP_GLYPH_BOX,color:theme.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */jsx(MicGlyph,{size:MIC_GLYPH_SIZE,color:theme.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:style,reduced:reduced}){let opacity=useRef(new Animated.Value(1)).current;return useEffect(()=>{if(reduced)return;let loop=Animated.loop(Animated.sequence([Animated.timing(opacity,{toValue:PULSE_LOW,duration:PULSE_LOOP_MS/2,useNativeDriver:true}),Animated.timing(opacity,{toValue:1,duration:PULSE_LOOP_MS/2,useNativeDriver:true})]));return loop.start(),()=>loop.stop()},[opacity,reduced]),/* @__PURE__ */jsx(Animated.View,{style:[style,{opacity:opacity}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function makeStyles5(theme){let c=theme.color,micro=theme.type.tierSizes.compact.micro;return StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...face(theme,"mono"),fontSize:micro,lineHeight:micro+2,fontVariant:["tabular-nums"],color:c.text.muted},button:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:theme.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:DISABLED_OPACITY},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:theme.radius.pill,backgroundColor:c.brandSofter}})}function optionalModule(name,load,validate2){let candidate;try{candidate=load()}catch(cause){return frozenUnavailable(`optional peer '${name}' is not installed: ${describe(cause)}`)}let resolved=unwrapDefault(candidate);return resolved==null?frozenUnavailable(`optional peer '${name}' resolved to no module`):validate2&&!validate2(resolved)?frozenUnavailable(`optional peer '${name}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:resolved})}function unwrapDefault(candidate){return typeof candidate=="object"&&candidate!==null&&"default"in candidate&&Object.keys(candidate).length<=2?candidate.default:candidate}function frozenUnavailable(reason){/* @__PURE__ */
103
- return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}var SLOT_KEY=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function slot(){let realm=globalThis,existing=realm[SLOT_KEY];if(existing!==void 0)return existing;let created={loader:null,memo:void 0};return realm[SLOT_KEY]=created,created}function registerEverfurDictation(next){let state=slot();state.loader=next,state.memo=void 0,state.version=(state.version??0)+1;for(let listener of[...state.listeners??[]])try{listener()}catch{}}function dictationRegistrationVersion(){return slot().version??0}function subscribeDictationRegistration(listener){let state=slot(),listeners2=state.listeners??/* @__PURE__ */new Set;state.listeners=listeners2;let entry=()=>listener();return listeners2.add(entry),()=>{listeners2.delete(entry)}}function isSpeechModule(candidate){if(typeof candidate!="object"||candidate===null)return false;let mod=candidate;return typeof mod.start=="function"&&typeof mod.isRecognitionAvailable=="function"&&typeof mod.addListener=="function"}function speechModuleOf(candidate){return typeof candidate!="object"||candidate===null?null:candidate.ExpoSpeechRecognitionModule??candidate}function loadNativeSpeech(){let state=slot();if(state.memo!==void 0)return state.memo;state.memo=null;let load=state.loader;if(load===null||Platform.OS!=="ios"&&Platform.OS!=="android")return state.memo;let loaded=optionalModule("expo-speech-recognition",()=>({box:speechModuleOf(load())}),box2=>typeof box2=="object"&&box2!==null&&isSpeechModule(box2.box));return loaded.available&&(state.memo=loaded.module.box),state.memo}function isNativeDictationAvailable(mod){if(mod===null)return false;try{return mod.isRecognitionAvailable()===!0}catch{return false}}function deviceLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale||FALLBACK_DICTATION_LOCALE}catch{return FALLBACK_DICTATION_LOCALE}}function normalizeTag(tag){return tag.replace(/_/g,"-").toLowerCase()}var FALLBACK_DICTATION_LOCALE="en-US";function resolveNativeDictationLocale(locale=deviceLocale()){let[base2=""]=locale.replace(/_/g,"-").split("-u-"),parts=base2.split("-");if(parts[0]?.toLowerCase()!=="en")return FALLBACK_DICTATION_LOCALE;let region=parts.slice(1).find(part=>/^[A-Za-z]{2}$/.test(part));return region?`en-${region.toUpperCase()}`:FALLBACK_DICTATION_LOCALE}function pickSupportedLocale(wanted,supported){if(supported.length===0)return null;let find=tag=>supported.find(locale=>normalizeTag(locale)===normalizeTag(tag));return find(wanted)??find(FALLBACK_DICTATION_LOCALE)??supported.find(locale=>normalizeTag(locale).startsWith("en-"))??null}async function resolveRecognizerLocale(mod,wanted){if(Platform.OS!=="ios")return wanted;try{let{locales:locales}=await mod.getSupportedLocales({});return pickSupportedLocale(wanted,locales??[])??wanted}catch{return wanted}}async function chooseNativeDictationMode(mod,lang){let onDevice=false;try{onDevice=mod.supportsOnDeviceRecognition()===!0}catch{onDevice=false}if(!onDevice)return"network";if(Platform.OS!=="android")return"on_device";try{let{installedLocales:installedLocales}=await mod.getSupportedLocales({}),wanted=normalizeTag(lang);return(installedLocales??[]).some(locale=>normalizeTag(locale)===wanted)?"on_device":"network"}catch{return"network"}}function supportsContinuous(){return Platform.OS!=="android"?true:Number(Platform.Version)>=ANDROID_13_API}var ANDROID_13_API=33;function buildStartOptions(mode,lang,phrases){return{lang:lang,interimResults:true,continuous:supportsContinuous(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:mode==="on_device",contextualStrings:phrases.slice(0,100),iosTaskHint:"dictation"}}var NOT_RETRYABLE=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),NATIVE_DICTATION_MAX_RETRIES=2;function nextDictationAttempt(mode,lang,code){return NOT_RETRYABLE.has(code)?null:code==="language-not-supported"&&normalizeTag(lang)!==normalizeTag(FALLBACK_DICTATION_LOCALE)?{mode:"network",lang:FALLBACK_DICTATION_LOCALE}:mode==="on_device"?{mode:"network",lang:lang}:null}function mapNativeDictationError(code){return code==="not-allowed"?"permissionDenied":code==="no-speech"||code==="speech-timeout"?"noSpeech":"unavailable"}async function requestNativeDictationPermission(mod){try{if((await mod.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await mod.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var NATIVE_DICTATION_AUTO_STOP_MS=55e3,END_GRACE_MS=3e3,STALE_END_WINDOW_MS=1e3,BENIGN_WITH_TEXT=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),EMPTY_TRANSCRIPT=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function clean2(text3){return text3.replace(/\s+/g," ").trim()}function applyResult(state,transcript,isFinal){let text3=clean2(transcript);return isFinal?text3?{committed:[...state.committed,text3],interim:""}:{committed:state.committed,interim:""}:{committed:state.committed,interim:text3}}function transcriptText(state){return clean2([...state.committed,state.interim].join(" "))}function createNativeDictationController(mod,events,telemetry,now=Date.now){let tokenSeq=0,attempt=null,lastAbortAt=Number.NEGATIVE_INFINITY,current=token=>attempt!==null&&attempt.token===token?attempt:null;function removeListeners(a){for(let subscription of a.subscriptions)try{subscription.remove()}catch{}a.subscriptions=[]}function teardown(a){removeListeners(a),a.autoStopTimer!==null&&clearTimeout(a.autoStopTimer),a.graceTimer!==null&&clearTimeout(a.graceTimer),a.autoStopTimer=null,a.graceTimer=null,attempt===a&&(attempt=null)}function isStaleEnd(a){return!a.sawStart&&a.errorCode===null&&a.pendingRetry===null&&transcriptText(a.transcript)===""&&a.launchedAt-lastAbortAt<STALE_END_WINDOW_MS}function modeOf(a){return a.mode??"none"}function trackCompleted(a,text3){trackDictationEvent(telemetry(),"chat_dictation_completed",{mode:modeOf(a),duration_ms:a.startedAt===null?0:Math.max(0,now()-a.startedAt),char_count:text3.length})}function fail(a,kind){trackDictationEvent(telemetry(),"chat_dictation_failed",{mode:modeOf(a),error:kind}),events.onStatus("idle"),events.onError(kind)}function finish(a){if(current(a.token)===null)return;teardown(a);let text3=transcriptText(a.transcript),code=a.errorCode;if(code!==null&&!(text3&&BENIGN_WITH_TEXT.has(code))){fail(a,mapNativeDictationError(code));return}if(!text3){fail(a,"noSpeech");return}trackCompleted(a,text3),events.onStatus("idle")}function subscribe2(a){a.subscriptions=[mod.addListener("start",()=>{current(a.token)!==null&&(a.sawStart=true,a.startedAt===null&&(a.startedAt=now()),trackDictationEvent(telemetry(),"chat_dictation_started",{mode:modeOf(a)}),events.onStatus("listening"))}),mod.addListener("result",event=>{if(current(a.token)===null)return;let first=event?.results?.[0]?.transcript??"";a.transcript=applyResult(a.transcript,first,event?.isFinal===true),events.onText(transcriptText(a.transcript))}),mod.addListener("error",event=>{if(current(a.token)===null)return;let code=event?.error??"unknown";if(code==="aborted"&&a.userStopped)return;let nothingYet=transcriptText(a.transcript)==="",retry=a.mode!==null&&!a.userStopped&&nothingYet&&a.retries<NATIVE_DICTATION_MAX_RETRIES?nextDictationAttempt(a.mode,a.lang,code):null;if(retry!==null){a.pendingRetry=retry;return}a.errorCode===null&&(a.errorCode=code)}),mod.addListener("end",()=>{if(current(a.token)!==null&&!isStaleEnd(a)){if(a.pendingRetry!==null){let retry=a.pendingRetry;a.pendingRetry=null,a.retries+=1,a.lang=retry.lang,launch(a,retry.mode);return}finish(a)}})]}function launch(a,mode){removeListeners(a),a.mode=mode,a.sawStart=false,a.launchedAt=now(),a.transcript=EMPTY_TRANSCRIPT,a.errorCode=null,subscribe2(a);try{mod.start(buildStartOptions(mode,a.lang,a.phrases))}catch{a.errorCode="unknown",finish(a)}}async function prepare(a){let permission=await requestNativeDictationPermission(mod);if(current(a.token)===null)return;if(permission!=="granted"){teardown(a),fail(a,permission==="denied"?"permissionDenied":"unavailable");return}if(a.lang=await resolveRecognizerLocale(mod,a.lang),current(a.token)===null)return;let mode=await chooseNativeDictationMode(mod,a.lang);current(a.token)!==null&&(a.autoStopTimer=setTimeout(()=>stopAttempt(a),NATIVE_DICTATION_AUTO_STOP_MS),launch(a,mode))}function stopAttempt(a){if(!(current(a.token)===null||a.userStopped)){if(a.userStopped=true,a.pendingRetry=null,a.mode===null){teardown(a),events.onStatus("idle");return}a.graceTimer=setTimeout(()=>finish(a),END_GRACE_MS);try{mod.stop()}catch{finish(a)}}}return{start(phrases){if(attempt!==null)return;let a={token:++tokenSeq,phrases:phrases,lang:resolveNativeDictationLocale(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:EMPTY_TRANSCRIPT,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null};attempt=a,events.onStatus("starting"),prepare(a)},stop(){attempt!==null&&stopAttempt(attempt)},cancel(){let a=attempt;if(a===null)return;let launched=a.mode!==null,text3=transcriptText(a.transcript);if(teardown(a),events.onStatus("idle"),!!launched){text3&&trackCompleted(a,text3),lastAbortAt=now();try{mod.abort()}catch{}}},isActive:()=>attempt!==null,isPreparing:()=>attempt!==null&&attempt.mode===null}}function useNativeDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry}){let registration=useSyncExternalStore(subscribeDictationRegistration,dictationRegistrationVersion,dictationRegistrationVersion),mod=useMemo(()=>enabled?loadNativeSpeech():null,[enabled,registration]),available=useMemo(()=>isNativeDictationAvailable(mod),[mod]),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let baseRef=useRef(""),maxRef=useRef(maxLength);maxRef.current=maxLength;let controllerRef=useRef(null);mod!==null&&controllerRef.current?.mod!==mod&&(controllerRef.current?.controller.cancel(),controllerRef.current={mod:mod,controller:createNativeDictationController(mod,{onStatus:next=>{setStatus(previous=>next==="idle"&&previous==="error"?previous:next)},onText:dictated=>setInputRef.current(composeDictatedText(baseRef.current,dictated,maxRef.current)),onError:kind=>{setError(kind),setStatus("error")}},()=>telemetryRef.current)});let controller=mod===null?null:controllerRef.current?.controller??null,cancel=useCallback(()=>{controller?.cancel()},[controller]),toggle=useCallback(()=>{if(controller!==null){if(controller.isActive()){controller.stop();return}setError(null),setElapsedMs(0),baseRef.current=inputRef.current,controller.start(phrases)}},[controller,phrases]);useEffect(()=>{if(status!=="listening")return;let startedAt=Date.now();setElapsedMs(0);let handle=setInterval(()=>setElapsedMs(Date.now()-startedAt),1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>{if(controller===null)return;let subscription=null;try{subscription=AppState.addEventListener("change",next=>{next==="background"&&!controller.isPreparing()&&controller.cancel()})}catch{}return()=>{subscription?.remove(),controller.cancel()}},[controller]);let supported=enabled&&available;return useEffect(()=>{supported||controller?.cancel()},[supported,controller]),{supported:supported,status:status,active:status==="starting"||status==="listening",error:error,elapsedMs:elapsedMs,toggle:toggle,cancel:cancel}}var KEY=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function shared(){let g=globalThis,existing=g[KEY];if(existing!==void 0)return existing;let fresh2=createContext(true);return g[KEY]=fresh2,fresh2}var ChatPaneShownContext=shared();function useChatPaneShown(){return useContext(ChatPaneShownContext)}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),COMPACT_HEIGHT=52,COMPACT_RING=1.5,COMPACT_INSET_TOP=10,COMPACT_INSET_SIDE=14,COMPACT_INSET_FOOT=10,COMPACT_DISC=40,COMPACT_ARROW=20,COMPACT_DIM_OPACITY=.3;function composerPlaceholder(branded,petName,petPlaceholder,mood="ask"){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,transport:transport}),bound=useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
104
- return 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,petBreed:petBreed=null,mood:mood="ask",dictation:dictation=false,telemetry:telemetry=null,compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false}){let{theme:theme,styles:styles3}=useChatTheme(),compactStyles=useMemo(()=>makeCompactStyles(theme),[theme]),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed),[pickerOpen,setPickerOpen]=useState(false),[pickFailed,setPickFailed]=useState(false);useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=composerPlaceholder(theme.meta.placeholder,petName,petPlaceholder,mood),phrases=useMemo(()=>buildDictationPhrases({name:petName,breed:petBreed}),[petName,petBreed]),voice=useNativeDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active;usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft,dictating);let seenConversation=useRef(conversationId);useEffect(()=>{seenConversation.current!==conversationId&&(seenConversation.current=conversationId,cancelDictation())},[conversationId,cancelDictation]);let paneShown=useChatPaneShown();useEffect(()=>{paneShown||cancelDictation()},[paneShown,cancelDictation]);let 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=useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;dictating&&cancelDictation();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,dictating,cancelDictation,attachments,onStage]),onChangeText=useCallback(next=>{dictating&&cancelDictation(),setDraft(next)},[dictating,cancelDictation,setDraft]),onStop=useCallback(()=>{stop()},[stop]),pickFrom=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=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__ */
108
+ return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}var SLOT_KEY=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function slot(){let realm=globalThis,existing=realm[SLOT_KEY];if(existing!==void 0)return existing;let created={loader:null,memo:void 0};return realm[SLOT_KEY]=created,created}function registerEverfurDictation(next){let state=slot();state.loader=next,state.memo=void 0,state.version=(state.version??0)+1;for(let listener of[...state.listeners??[]])try{listener()}catch{}}function dictationRegistrationVersion(){return slot().version??0}function subscribeDictationRegistration(listener){let state=slot(),listeners2=state.listeners??/* @__PURE__ */new Set;state.listeners=listeners2;let entry=()=>listener();return listeners2.add(entry),()=>{listeners2.delete(entry)}}function isSpeechModule(candidate){if(typeof candidate!="object"||candidate===null)return false;let mod=candidate;return typeof mod.start=="function"&&typeof mod.isRecognitionAvailable=="function"&&typeof mod.addListener=="function"}function speechModuleOf(candidate){return typeof candidate!="object"||candidate===null?null:candidate.ExpoSpeechRecognitionModule??candidate}function loadNativeSpeech(){let state=slot();if(state.memo!==void 0)return state.memo;state.memo=null;let load=state.loader;if(load===null||Platform.OS!=="ios"&&Platform.OS!=="android")return state.memo;let loaded=optionalModule("expo-speech-recognition",()=>({box:speechModuleOf(load())}),box2=>typeof box2=="object"&&box2!==null&&isSpeechModule(box2.box));return loaded.available&&(state.memo=loaded.module.box),state.memo}function isNativeDictationAvailable(mod){if(mod===null)return false;try{return mod.isRecognitionAvailable()===!0}catch{return false}}function deviceLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale||FALLBACK_DICTATION_LOCALE}catch{return FALLBACK_DICTATION_LOCALE}}function normalizeTag(tag){return tag.replace(/_/g,"-").toLowerCase()}var FALLBACK_DICTATION_LOCALE="en-US";function resolveNativeDictationLocale(locale=deviceLocale()){let[base2=""]=locale.replace(/_/g,"-").split("-u-"),parts=base2.split("-");if(parts[0]?.toLowerCase()!=="en")return FALLBACK_DICTATION_LOCALE;let region=parts.slice(1).find(part=>/^[A-Za-z]{2}$/.test(part));return region?`en-${region.toUpperCase()}`:FALLBACK_DICTATION_LOCALE}function pickSupportedLocale(wanted,supported){if(supported.length===0)return null;let find=tag=>supported.find(locale=>normalizeTag(locale)===normalizeTag(tag));return find(wanted)??find(FALLBACK_DICTATION_LOCALE)??supported.find(locale=>normalizeTag(locale).startsWith("en-"))??null}async function resolveRecognizerLocale(mod,wanted){if(Platform.OS!=="ios")return wanted;try{let{locales:locales}=await mod.getSupportedLocales({});return pickSupportedLocale(wanted,locales??[])??wanted}catch{return wanted}}async function chooseNativeDictationMode(mod,lang){let onDevice=false;try{onDevice=mod.supportsOnDeviceRecognition()===!0}catch{onDevice=false}if(!onDevice)return"network";if(Platform.OS!=="android")return"on_device";try{let{installedLocales:installedLocales}=await mod.getSupportedLocales({}),wanted=normalizeTag(lang);return(installedLocales??[]).some(locale=>normalizeTag(locale)===wanted)?"on_device":"network"}catch{return"network"}}function supportsContinuous(){return Platform.OS!=="android"?true:Number(Platform.Version)>=ANDROID_13_API}var ANDROID_13_API=33;function buildStartOptions(mode,lang,phrases){return{lang:lang,interimResults:true,continuous:supportsContinuous(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:mode==="on_device",contextualStrings:phrases.slice(0,100),iosTaskHint:"dictation"}}var NOT_RETRYABLE=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),NATIVE_DICTATION_MAX_RETRIES=2;function nextDictationAttempt(mode,lang,code){return NOT_RETRYABLE.has(code)?null:code==="language-not-supported"&&normalizeTag(lang)!==normalizeTag(FALLBACK_DICTATION_LOCALE)?{mode:"network",lang:FALLBACK_DICTATION_LOCALE}:mode==="on_device"?{mode:"network",lang:lang}:null}function mapNativeDictationError(code){return code==="not-allowed"?"permissionDenied":code==="no-speech"||code==="speech-timeout"?"noSpeech":"unavailable"}async function requestNativeDictationPermission(mod){try{if((await mod.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await mod.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var NATIVE_DICTATION_AUTO_STOP_MS=55e3,END_GRACE_MS=3e3,STALE_END_WINDOW_MS=1e3,BENIGN_WITH_TEXT=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),EMPTY_TRANSCRIPT=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function clean2(text3){return text3.replace(/\s+/g," ").trim()}function applyResult(state,transcript,isFinal){let text3=clean2(transcript);return isFinal?text3?{committed:[...state.committed,text3],interim:""}:{committed:state.committed,interim:""}:{committed:state.committed,interim:text3}}function transcriptText(state){return clean2([...state.committed,state.interim].join(" "))}function createNativeDictationController(mod,events,telemetry,now=Date.now){let tokenSeq=0,attempt=null,lastAbortAt=Number.NEGATIVE_INFINITY,current=token=>attempt!==null&&attempt.token===token?attempt:null;function removeListeners(a){for(let subscription of a.subscriptions)try{subscription.remove()}catch{}a.subscriptions=[]}function teardown(a){removeListeners(a),a.autoStopTimer!==null&&clearTimeout(a.autoStopTimer),a.graceTimer!==null&&clearTimeout(a.graceTimer),a.autoStopTimer=null,a.graceTimer=null,attempt===a&&(attempt=null)}function isStaleEnd(a){return!a.sawStart&&a.errorCode===null&&a.pendingRetry===null&&transcriptText(a.transcript)===""&&a.launchedAt-lastAbortAt<STALE_END_WINDOW_MS}function modeOf(a){return a.mode??"none"}function trackCompleted(a,text3){trackDictationEvent(telemetry(),"chat_dictation_completed",{mode:modeOf(a),duration_ms:a.startedAt===null?0:Math.max(0,now()-a.startedAt),char_count:text3.length})}function fail(a,kind){trackDictationEvent(telemetry(),"chat_dictation_failed",{mode:modeOf(a),error:kind}),events.onStatus("idle"),events.onError(kind)}function finish(a){if(current(a.token)===null)return;teardown(a);let text3=transcriptText(a.transcript),code=a.errorCode;if(code!==null&&!(text3&&BENIGN_WITH_TEXT.has(code))){fail(a,mapNativeDictationError(code));return}if(!text3){fail(a,"noSpeech");return}trackCompleted(a,text3),events.onStatus("idle")}function subscribe2(a){a.subscriptions=[mod.addListener("start",()=>{current(a.token)!==null&&(a.sawStart=true,a.startedAt===null&&(a.startedAt=now()),trackDictationEvent(telemetry(),"chat_dictation_started",{mode:modeOf(a)}),events.onStatus("listening"))}),mod.addListener("result",event=>{if(current(a.token)===null)return;let first=event?.results?.[0]?.transcript??"";a.transcript=applyResult(a.transcript,first,event?.isFinal===true),events.onText(transcriptText(a.transcript))}),mod.addListener("error",event=>{if(current(a.token)===null)return;let code=event?.error??"unknown";if(code==="aborted"&&a.userStopped)return;let nothingYet=transcriptText(a.transcript)==="",retry=a.mode!==null&&!a.userStopped&&nothingYet&&a.retries<NATIVE_DICTATION_MAX_RETRIES?nextDictationAttempt(a.mode,a.lang,code):null;if(retry!==null){a.pendingRetry=retry;return}a.errorCode===null&&(a.errorCode=code)}),mod.addListener("end",()=>{if(current(a.token)!==null&&!isStaleEnd(a)){if(a.pendingRetry!==null){let retry=a.pendingRetry;a.pendingRetry=null,a.retries+=1,a.lang=retry.lang,launch(a,retry.mode);return}finish(a)}})]}function launch(a,mode){removeListeners(a),a.mode=mode,a.sawStart=false,a.launchedAt=now(),a.transcript=EMPTY_TRANSCRIPT,a.errorCode=null,subscribe2(a);try{mod.start(buildStartOptions(mode,a.lang,a.phrases))}catch{a.errorCode="unknown",finish(a)}}async function prepare(a){let permission=await requestNativeDictationPermission(mod);if(current(a.token)===null)return;if(permission!=="granted"){teardown(a),fail(a,permission==="denied"?"permissionDenied":"unavailable");return}if(a.lang=await resolveRecognizerLocale(mod,a.lang),current(a.token)===null)return;let mode=await chooseNativeDictationMode(mod,a.lang);current(a.token)!==null&&(a.autoStopTimer=setTimeout(()=>stopAttempt(a),NATIVE_DICTATION_AUTO_STOP_MS),launch(a,mode))}function stopAttempt(a){if(!(current(a.token)===null||a.userStopped)){if(a.userStopped=true,a.pendingRetry=null,a.mode===null){teardown(a),events.onStatus("idle");return}a.graceTimer=setTimeout(()=>finish(a),END_GRACE_MS);try{mod.stop()}catch{finish(a)}}}return{start(phrases){if(attempt!==null)return;let a={token:++tokenSeq,phrases:phrases,lang:resolveNativeDictationLocale(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:EMPTY_TRANSCRIPT,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null};attempt=a,events.onStatus("starting"),prepare(a)},stop(){attempt!==null&&stopAttempt(attempt)},cancel(){let a=attempt;if(a===null)return;let launched=a.mode!==null,text3=transcriptText(a.transcript);if(teardown(a),events.onStatus("idle"),!!launched){text3&&trackCompleted(a,text3),lastAbortAt=now();try{mod.abort()}catch{}}},isActive:()=>attempt!==null,isPreparing:()=>attempt!==null&&attempt.mode===null}}function useNativeDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry}){let registration=useSyncExternalStore(subscribeDictationRegistration,dictationRegistrationVersion,dictationRegistrationVersion),mod=useMemo(()=>enabled?loadNativeSpeech():null,[enabled,registration]),available=useMemo(()=>isNativeDictationAvailable(mod),[mod]),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let baseRef=useRef(""),maxRef=useRef(maxLength);maxRef.current=maxLength;let controllerRef=useRef(null);mod!==null&&controllerRef.current?.mod!==mod&&(controllerRef.current?.controller.cancel(),controllerRef.current={mod:mod,controller:createNativeDictationController(mod,{onStatus:next=>{setStatus(previous=>next==="idle"&&previous==="error"?previous:next)},onText:dictated=>setInputRef.current(composeDictatedText(baseRef.current,dictated,maxRef.current)),onError:kind=>{setError(kind),setStatus("error")}},()=>telemetryRef.current)});let controller=mod===null?null:controllerRef.current?.controller??null,cancel=useCallback(()=>{controller?.cancel()},[controller]),toggle=useCallback(()=>{if(controller!==null){if(controller.isActive()){controller.stop();return}setError(null),setElapsedMs(0),baseRef.current=inputRef.current,controller.start(phrases)}},[controller,phrases]);useEffect(()=>{if(status!=="listening")return;let startedAt=Date.now();setElapsedMs(0);let handle=setInterval(()=>setElapsedMs(Date.now()-startedAt),1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>{if(controller===null)return;let subscription=null;try{subscription=AppState.addEventListener("change",next=>{next==="background"&&!controller.isPreparing()&&controller.cancel()})}catch{}return()=>{subscription?.remove(),controller.cancel()}},[controller]);let supported=enabled&&available;return useEffect(()=>{supported||controller?.cancel()},[supported,controller]),{supported:supported,status:status,active:status==="starting"||status==="listening",error:error,elapsedMs:elapsedMs,toggle:toggle,cancel:cancel}}var KEY=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function shared(){let g=globalThis,existing=g[KEY];if(existing!==void 0)return existing;let fresh2=createContext(true);return g[KEY]=fresh2,fresh2}var ChatPaneShownContext=shared();function useChatPaneShown(){return useContext(ChatPaneShownContext)}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),COMPACT_HEIGHT=52,COMPACT_RING=1.5,COMPACT_INSET_TOP=10,COMPACT_INSET_SIDE=14,COMPACT_INSET_FOOT=10,COMPACT_DISC=40,COMPACT_ARROW=20,COMPACT_DIM_OPACITY=.3,COMPACT_RING_FOCUSED=2.5,COMPACT_INPUT_STEP=1,COMPACT_INPUT_LEAD=1.5,COMPACT_ADD=38,COMPACT_ADD_GLYPH=22,COMPACT_ADD_SLOP=3;function composerPlaceholder(branded,petName,petPlaceholder,mood="ask"){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,transport:transport}),bound=useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
109
+ return 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,petBreed:petBreed=null,mood:mood="ask",dictation:dictation=false,telemetry:telemetry=null,compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false}){let{theme:theme,styles:styles3}=useChatTheme(),compactStyles=useMemo(()=>makeCompactStyles(theme),[theme]),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed),[pickerOpen,setPickerOpen]=useState(false),[focused,setFocused]=useState(false),onFocus=useCallback(()=>setFocused(true),[]),onBlur=useCallback(()=>setFocused(false),[]),[pickFailed,setPickFailed]=useState(false);useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=composerPlaceholder(theme.meta.placeholder,petName,petPlaceholder,mood),phrases=useMemo(()=>buildDictationPhrases({name:petName,breed:petBreed}),[petName,petBreed]),voice=useNativeDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active;usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft,dictating);let seenConversation=useRef(conversationId);useEffect(()=>{seenConversation.current!==conversationId&&(seenConversation.current=conversationId,cancelDictation())},[conversationId,cancelDictation]);let paneShown=useChatPaneShown();useEffect(()=>{paneShown||cancelDictation()},[paneShown,cancelDictation]);let 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=useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;dictating&&cancelDictation();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,dictating,cancelDictation,attachments,onStage]),onChangeText=useCallback(next=>{dictating&&cancelDictation(),setDraft(next)},[dictating,cancelDictation,setDraft]),onStop=useCallback(()=>{stop()},[stop]),pickFrom=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=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__ */
105
110
  return jsxs(View,{style:styles3.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
106
- /* @__PURE__ */jsxs(View,{style:compact?[styles3.composer,compactStyles.bar]:styles3.composer,children:[attachments!==null?/* @__PURE__ */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,voice.supported&&voice.error!==null?/* @__PURE__ */jsxs(Fragment,{children:[
111
+ /* @__PURE__ */jsxs(View,{style:compact?[styles3.composer,compactStyles.bar,focused?compactStyles.barFocused:null]:styles3.composer,children:[attachments!==null?/* @__PURE__ */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,voice.supported&&voice.error!==null?/* @__PURE__ */jsxs(Fragment,{children:[
107
112
  /* @__PURE__ */jsx(Text,{style:styles3.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:dictationErrorMessage(voice.error)}),
108
113
  /* @__PURE__ */jsx(AnnounceLine,{line:dictationErrorMessage(voice.error)})]}):null,
109
- /* @__PURE__ */jsxs(View,{style:styles3.composerRow,children:[attachments!==null?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles3.attachControl,slotsFull?styles3.attachControlDisabled:null],onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsx(UploadGlyph,{size:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:theme.color.brandInk,strokeWidth:1.75})}):null,
110
- /* @__PURE__ */jsx(TextInput,{style:styles3.input,value:draft,onChangeText:onChangeText,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}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx(Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles3.sendControl,children:/* @__PURE__ */jsx(View,{style:compact?compactStyles.disc:styles3.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsx(StopGlyph,{size:compact?COMPACT_ARROW:STOP_GLYPH_SIZE,color:compact?compactInk:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsx(Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles3.sendControl,sendDimmed?compact?compactStyles.dimmed:styles3.sendControlDisabled:null],children:compact?/* @__PURE__ */jsx(View,{style:compactStyles.disc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(ArrowUpGlyph,{size:COMPACT_ARROW,color:compactInk,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */jsx(View,{style:styles3.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */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,slot2=theme.slots.sendButton;return StyleSheet.create({bar:{marginTop:COMPACT_INSET_TOP,marginHorizontal:COMPACT_INSET_SIDE,marginBottom:COMPACT_INSET_FOOT,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:slot2?.backgroundColor??c.text.primary},dimmed:{opacity:COMPACT_DIM_OPACITY}})}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 useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=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]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return 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 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}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)}var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}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_URL2=/^([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_URL2.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]=useState(null);if(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=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=useRef(controller);preflightController.current=controller;let scope=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]=useState(IDLE2),inFlight2=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=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=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=useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=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=>Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=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 VetVisitButtonCore(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(),styles3=useMemo(()=>makeStyles6(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
114
+ /* @__PURE__ */jsxs(View,{style:styles3.composerRow,children:[attachments!==null?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles3.attachControl,compact?compactStyles.add:null,slotsFull?styles3.attachControlDisabled:null],hitSlop:compact?COMPACT_ADD_SLOP:void 0,onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsx(UploadGlyph,{size:compact?COMPACT_ADD_GLYPH:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:compact?theme.color.text.primary:theme.color.brandInk,strokeWidth:1.75})}):null,
115
+ /* @__PURE__ */jsx(TextInput,{style:compact?[styles3.input,compactStyles.input]:styles3.input,onFocus:onFocus,onBlur:onBlur,value:draft,onChangeText:onChangeText,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",...SUBMIT_ON_RETURN,...compact?ONE_ROW_WEB:null,blurOnSubmit:false,multiline:true,editable:true}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx(Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles3.sendControl,children:/* @__PURE__ */jsx(View,{style:compact?compactStyles.disc:styles3.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsx(StopGlyph,{size:compact?COMPACT_ARROW:STOP_GLYPH_SIZE,color:compact?compactInk:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsx(Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles3.sendControl,sendDimmed?compact?compactStyles.dimmed:styles3.sendControlDisabled:null],children:compact?/* @__PURE__ */jsx(View,{style:compactStyles.disc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(ArrowUpGlyph,{size:COMPACT_ARROW,color:compactInk,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */jsx(View,{style:styles3.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */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"}),ONE_ROW_WEB=/* @__PURE__ */Object.freeze(Platform.OS==="web"?{rows:1}:{}),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function makeCompactStyles(theme){let c=theme.color,slot2=theme.slots.sendButton,inputSize=textRole(theme,"body").fontSize+COMPACT_INPUT_STEP;return StyleSheet.create({bar:{marginTop:COMPACT_INSET_TOP,marginHorizontal:COMPACT_INSET_SIDE,marginBottom:COMPACT_INSET_FOOT,minHeight:COMPACT_HEIGHT,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:COMPACT_RING,borderColor:theme.slots.composerInput?.borderColor??c.text.primary},barFocused:{borderWidth:COMPACT_RING_FOCUSED,paddingLeft:8-(COMPACT_RING_FOCUSED-COMPACT_RING),paddingRight:6-(COMPACT_RING_FOCUSED-COMPACT_RING)},input:{fontSize:inputSize,lineHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),minHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),...Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:COMPACT_ADD,height:COMPACT_ADD,borderRadius:COMPACT_ADD/2},disc:{width:COMPACT_DISC,height:COMPACT_DISC,borderRadius:COMPACT_DISC/2,alignItems:"center",justifyContent:"center",backgroundColor:slot2?.backgroundColor??c.text.primary,...slotBox(slot2)},dimmed:{opacity:COMPACT_DIM_OPACITY}})}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 useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=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]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return 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 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}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)}var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}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_URL2=/^([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_URL2.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]=useState(null);if(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=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=useRef(controller);preflightController.current=controller;let scope=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]=useState(IDLE2),inFlight2=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=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=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=useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=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=>Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=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 VetVisitButtonCore(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(),styles3=useMemo(()=>makeStyles6(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
111
116
  return jsxs(Fragment,{children:[null,
112
117
  /* @__PURE__ */jsx(TelevetHostOutlet,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
113
118
  return jsxs(Fragment,{children:[
@@ -170,12 +175,12 @@ return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:option.lab
170
175
  /* @__PURE__ */jsx(TextInput,{style:styles3.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__ */jsx(Text,{tier:"compact",style:[styles3.counter,overLimit?styles3.counterOver:null],children:`${[...note].length}/${FEEDBACK_NOTES_MAX_CHARS}`}):null]}),failed?/* @__PURE__ */jsx(Text,{style:styles3.failed,accessibilityRole:"alert",children:CHAT_COPY.feedbackFailed}):null,
171
176
  /* @__PURE__ */jsxs(View,{style:styles3.actions,children:[
172
177
  /* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSubmit,accessibilityState:{busy:pending,disabled:pending||overLimit},disabled:pending||overLimit,style:[styles3.submit,pending||overLimit?styles3.submitDisabled:null],onPress:()=>{submit()},children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.submitLabel,children:CHAT_COPY.feedbackSubmit})}),
173
- /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles3.skip,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles10(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return 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:StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,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 KEY2=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function shared2(){let g=globalThis,hit=g[KEY2];if(hit!==void 0)return hit;let fresh2={factory:createContext(null),home:createContext(null)};return g[KEY2]=fresh2,fresh2}var AskHomeFactoryContext=shared2().factory,AskHomeContext=shared2().home;function useAskHomeFactory(){return useContext(AskHomeFactoryContext)}function useAskHome(){return useContext(AskHomeContext)?.kit??null}function useAskHomeTitle(){return useContext(AskHomeContext)}var BAR_SIZE=15,UNREAD_DOT=8;function HistoryBar({bar:bar,history:history,empty:empty,unread:unread,extra:extra}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles(theme,home):makeStyles11(theme),[theme,home]),count2=history.cursor===null?history.rows.length:0,icon=name=>{let render=bar.renderIcon;return render===void 0?null:/* @__PURE__ */jsx(HostRender,{render:()=>render(name),fallback:null})};/* @__PURE__ */
178
+ /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles3.skip,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles10(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return 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:StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,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 KEY2=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function shared2(){let g=globalThis,hit=g[KEY2];if(hit!==void 0)return hit;let fresh2={factory:createContext(null),home:createContext(null)};return g[KEY2]=fresh2,fresh2}var AskHomeFactoryContext=shared2().factory,AskHomeContext=shared2().home;function useAskHomeFactory(){return useContext(AskHomeFactoryContext)}function useAskHome(){return useContext(AskHomeContext)?.kit??null}function useAskHomeTitle(){return useContext(AskHomeContext)}var BAR_SIZE=15,UNREAD_DOT=8;function HistoryBar({bar:bar,history:history,empty:empty,unread:unread,extra:extra}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles(theme,home):makeStyles11(theme),[theme,home]),count2=history.cursor===null?history.rows.length:0,icon=name=>{let render=bar.renderIcon;if(render!==void 0)/* @__PURE__ */return jsx(HostRender,{render:()=>render(name),fallback:null});if(home===null)return null;let ink=String(StyleSheet.flatten(styles3.label).color??theme.color.linkInk);return name==="history"?/* @__PURE__ */jsx(HistoryGlyph,{size:HOME_GLYPH,color:ink,strokeWidth:1.8}):/* @__PURE__ */jsx(EditGlyph,{size:HOME_GLYPH,color:ink,strokeWidth:1.8})};/* @__PURE__ */
174
179
  return jsxs(View,{style:styles3.bar,testID:"everfur-history-bar",children:[
175
180
  /* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:count2>0?`${bar.chats} ${count2}`:bar.chats,accessibilityState:{expanded:history.open},onPress:history.open?history.close:history.show,style:styles3.control,hitSlop:home!==null?HOME_SLOP:void 0,children:[icon("history"),
176
181
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.chats}),count2>0?/* @__PURE__ */jsx(View,{style:styles3.count,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles3.countText,children:String(count2)})}):null,unread?/* @__PURE__ */jsx(View,{style:styles3.dot,testID:"everfur-chat-history-bar-unread"}):null]}),bar.extra??null,extra??null,
177
182
  /* @__PURE__ */jsx(View,{style:styles3.spacer}),empty?null:/* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:bar.newChat,onPress:history.newConversation,style:styles3.control,hitSlop:home!==null?HOME_SLOP:void 0,children:[icon("edit"),
178
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.newChat})]})]})}var HOME_SLOP=4;function homeStyles(theme,home){return{...makeStyles11(theme),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm},control:home.view(".thread__hist"),label:home.text(".thread__hist"),count:home.view(".thread__count"),countText:home.text(".thread__count")}}function makeStyles11(theme){let c=theme.color,s=theme.space;return 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]=useState(history.open),onHidden=useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles12(theme),[theme]),motion=useChatMotion(),insets=useSafeAreaInsets(),{width:width}=useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=useRef(null);progress.current===null&&(progress.current=new Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=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__ */jsxs(View,{style:styles3.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
183
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.newChat})]})]})}var HOME_SLOP=4,HOME_GLYPH=18;function homeStyles(theme,home){return{...makeStyles11(theme),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm},control:home.view(".thread__hist"),label:home.text(".thread__hist"),count:home.view(".thread__count"),countText:home.text(".thread__count")}}function makeStyles11(theme){let c=theme.color,s=theme.space;return 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]=useState(history.open),onHidden=useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles12(theme),[theme]),motion=useChatMotion(),insets=useSafeAreaInsets(),{width:width}=useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=useRef(null);progress.current===null&&(progress.current=new Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=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__ */jsxs(View,{style:styles3.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
179
184
  /* @__PURE__ */jsx(ActivityIndicator,{color:styles3.emptyTitle.color}),
180
185
  /* @__PURE__ */jsx(Text,{style:styles3.emptyBody,children:HISTORY_COPY.loading})]}):hasNoConversations&&history.error!==null?/* @__PURE__ */jsxs(View,{style:styles3.emptyCard,children:[
181
186
  /* @__PURE__ */jsx(Text,{style:styles3.emptyTitle,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
@@ -198,7 +203,7 @@ return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestCl
198
203
  /* @__PURE__ */jsx(FlatList,{data:rows,keyExtractor:row=>row.id,renderItem:({item:item})=>/* @__PURE__ */jsx(Row,{row:item,active:item.id===chat.conversationId,disabled:history.loading,styles:styles3,onPress:()=>{history.resume(item.id)}}),contentContainerStyle:rows.length===0?styles3.listEmpty:styles3.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:empty,ListFooterComponent:footer,onEndReached:history.loadMore,onEndReachedThreshold:END_REACHED_THRESHOLD})]})})]})})}function Row({row:row,active:active,disabled:disabled,styles:styles3,onPress:onPress}){let unread=row.unreadCount!==null&&row.unreadCount>0,meta=conversationMeta(row);/* @__PURE__ */
199
204
  return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:active,disabled:disabled},disabled:disabled,style:[styles3.item,active?styles3.itemActive:null],onPress:onPress,children:[
200
205
  /* @__PURE__ */jsxs(View,{style:styles3.itemRow,children:[
201
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsx(View,{style:styles3.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary,cardText=slotText(slots.card);return 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:StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md,...drawerSlotBox(slots.dialog,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: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:StyleSheet.hairlineWidth,borderColor:c.borderRingCream,...slotBox(slots.card,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__ */jsx(HostRender,{render:()=>render(name),fallback:fallback})}function HistorySheet({chat:chat,history:history,sheet:sheet}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles13(theme),[theme]),insets=useSafeAreaInsets(),groups=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__ */
206
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsx(View,{style:styles3.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary,cardText=slotText(slots.card);return 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:StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md,...drawerSlotBox(slots.dialog,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: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:StyleSheet.hairlineWidth,borderColor:c.borderRingCream,...slotBox(slots.card,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=48,FIRST_DAY_TOP=2,TITLE_LEAD=1.3,ICON_WASH_ALPHA=.12,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__ */jsx(HostRender,{render:()=>render(name),fallback:fallback})}function HistorySheet({chat:chat,history:history,sheet:sheet}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles13(theme),[theme]),insets=useSafeAreaInsets(),groups=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__ */
202
207
  return jsx(Modal,{visible:true,transparent:true,animationType:"slide",onRequestClose:history.close,children:/* @__PURE__ */jsxs(View,{style:styles3.root,children:[
203
208
  /* @__PURE__ */jsx(Pressable,{style:[ABSOLUTE_FILL,styles3.scrim],onPress:history.close,accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.closeA11y}),
204
209
  /* @__PURE__ */jsxs(View,{style:[styles3.sheet,{paddingBottom:Math.max(40,insets.bottom+theme.space.lg)}],accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
@@ -210,15 +215,15 @@ return jsx(Modal,{visible:true,transparent:true,animationType:"slide",onRequestC
210
215
  /* @__PURE__ */jsx(ActivityIndicator,{color:c.brandInk}),
211
216
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.mono,children:HISTORY_COPY.loading})]}):null,history.error!==null?/* @__PURE__ */jsxs(View,{style:styles3.state,children:[
212
217
  /* @__PURE__ */jsx(Text,{style:styles3.stateText,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
213
- /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.retry,onPress:()=>{history.load()},style:styles3.link,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.linkText,children:HISTORY_COPY.retry})})]}):null,!history.loading&&history.error===null&&history.rows.length===0?/* @__PURE__ */jsx(Text,{style:[styles3.stateText,styles3.state],children:HISTORY_COPY.empty}):null,groups.map(group=>/* @__PURE__ */jsxs(Fragment$1,{children:[group.day?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.mono,styles3.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__ */
218
+ /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.retry,onPress:()=>{history.load()},style:styles3.link,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.linkText,children:HISTORY_COPY.retry})})]}):null,!history.loading&&history.error===null&&history.rows.length===0?/* @__PURE__ */jsx(Text,{style:[styles3.stateText,styles3.state],children:HISTORY_COPY.empty}):null,groups.map((group,groupIndex)=>/* @__PURE__ */jsxs(Fragment$1,{children:[group.day?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.mono,styles3.day,groupIndex===0?styles3.dayFirst:null],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__ */
214
219
  return jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:current},onPress:()=>{history.resume(row.id)},style:[styles3.row,current?styles3.rowCurrent:null],children:[
215
- /* @__PURE__ */jsx(View,{style:styles3.icon,children:sheetIcon(sheet,"chat",/* @__PURE__ */jsx(ChatBubbleGlyph,{size:19,color:c.brandInk,strokeWidth:1.75}))}),
220
+ /* @__PURE__ */jsx(View,{style:styles3.icon,children:sheetIcon(sheet,"chat",/* @__PURE__ */jsx(ChatBubbleGlyph,{size:19,color:c.linkInk,strokeWidth:1.75}))}),
216
221
  /* @__PURE__ */jsxs(View,{style:styles3.rowWords,children:[
217
222
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.rowTitle,numberOfLines:1,children:conversationTitle(row.title)}),row.preview!==void 0?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.preview,numberOfLines:1,children:row.preview}):null]}),
218
223
  /* @__PURE__ */jsxs(View,{style:styles3.rowEnd,children:[time!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.mono,styles3.time,unread?styles3.timeUnread:null],children:time}):null,unread?/* @__PURE__ */jsx(View,{style:styles3.unreadDot,testID:`everfur-history-sheet-unread-${String(row.id)}`}):null]})]},String(row.id))})]},group.day)),history.cursor!==null&&!history.loadingMore?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.more,onPress:history.loadMore,style:styles3.link,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.linkText,children:HISTORY_COPY.more})}):null]}),
219
- /* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.newChat,onPress:history.newConversation,style:styles3.newChat,children:[sheetIcon(sheet,"edit",/* @__PURE__ */jsx(EditGlyph,{size:18,color:c.onPrimary,strokeWidth:1.75})),
220
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.newChatText,children:HISTORY_COPY.newChat})]})]})]})})}function makeStyles13(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 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 CLOSE_FALLBACK="Close",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`,resultsKicker:who=>who.possessive===null?null:`${capital(who.possessive)} results`,resultsClose:who=>who.possessive===null?null:`Close ${who.possessive} results`,resultsTopRisk:"Top risk"});function capital(word){return word.charAt(0).toUpperCase()+word.slice(1)}function healthPlanPossessive(pet){let sex=typeof pet.sex=="string"?pet.sex.trim().toLowerCase():null;if(sex==="female")return"her";if(sex==="male")return"his";let name=typeof pet.name=="string"?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,onOpenPlan=options.onOpenPlan,action=onOpenPlan===void 0?null:copy.action(who),close=copy.close(who),ask=copy.ask.trim(),results=options.results!==void 0&&focus.report!==void 0?options.results:void 0;if(results!==void 0){let kicker=copy.resultsKicker(who)?.trim()||focus.kicker,shut=copy.resultsClose(who),onTop=results.onTopRisk??onOpenPlan,top={key:"top-risk",label:copy.resultsTopRisk,title:focus.title,...focus.risk?.lead?{line:focus.risk.lead}:{},tone:"risk",...onTop===void 0?{}:{onPress:onTop}};return{kicker:kicker,...badge===void 0?{}:{badge:badge},title:focus.title,results:[top,...results.rows??[]],...action===null||action.trim()===""||onOpenPlan===void 0?{}:{action:{label:action,onPress:onOpenPlan}},...ask===""?{}:{ask:{label:ask,prompt:copy.askPrompt(focus,ask)}},closeLabel:shut===null||shut.trim()===""?CLOSE_FALLBACK:shut,pill:kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon}}}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()===""?CLOSE_FALLBACK:close,pill:focus.kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon}}}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(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles2(home):makeStyles14(theme),[theme,home]);if(!open)return null;let closeLabel=card.closeLabel===void 0?null:card.closeLabel.trim()!==""?card.closeLabel:CHAT_COPY.close,action=card.action,question=card.ask,glyph=/* @__PURE__ */jsx(CloseGlyph,{size:home!==null?HOME_CLOSE_GLYPH(home):CLOSE_GLYPH3,color:home!==null?String(home.text(".ask-focus__x").color):theme.color.text.primary,strokeWidth:2});/* @__PURE__ */
221
- return jsxs(View,{style:styles3.card,testID:"everfur-top-card",children:[
224
+ /* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.newChat,onPress:history.newConversation,style:styles3.newChat,children:[sheetIcon(sheet,"edit",/* @__PURE__ */jsx(EditGlyph,{size:18,color:theme.slots.primaryButton?.textColor??c.onPrimary,strokeWidth:1.75})),
225
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.newChatText,children:HISTORY_COPY.newChat})]})]})]})})}function makeStyles13(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 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},dayFirst:{marginTop:FIRST_DAY_TOP},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:withAlpha(c.linkInk,ICON_WASH_ALPHA)??c.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(theme,"bold"),fontSize:TITLE_SIZE,lineHeight:TITLE_SIZE*TITLE_LEAD,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,...slotBox(theme.slots.primaryButton)},newChatText:{...face(theme,"bold"),fontSize:NEW_CHAT_SIZE,color:c.onPrimary,...slotText(theme.slots.primaryButton)}})}var CLOSE_FALLBACK="Close",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`,resultsKicker:who=>who.possessive===null?null:`${capital(who.possessive)} results`,resultsClose:who=>who.possessive===null?null:`Close ${who.possessive} results`,resultsTopRisk:"Top risk"});function capital(word){return word.charAt(0).toUpperCase()+word.slice(1)}function healthPlanPossessive(pet){let sex=typeof pet.sex=="string"?pet.sex.trim().toLowerCase():null;if(sex==="female")return"her";if(sex==="male")return"his";let name=typeof pet.name=="string"?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,onOpenPlan=options.onOpenPlan,action=onOpenPlan===void 0?null:copy.action(who),close=copy.close(who),ask=copy.ask.trim(),results=options.results!==void 0&&focus.report!==void 0?options.results:void 0;if(results!==void 0){let kicker=copy.resultsKicker(who)?.trim()||focus.kicker,shut=copy.resultsClose(who),onTop=results.onTopRisk??onOpenPlan,top={key:"top-risk",label:copy.resultsTopRisk,title:focus.title,...focus.risk?.lead?{line:focus.risk.lead}:{},tone:"risk",...onTop===void 0?{}:{onPress:onTop}};return{kicker:kicker,...badge===void 0?{}:{badge:badge},title:focus.title,results:[top,...results.rows??[]],...action===null||action.trim()===""||onOpenPlan===void 0?{}:{action:{label:action,onPress:onOpenPlan}},...ask===""?{}:{ask:{label:ask,prompt:copy.askPrompt(focus,ask)}},closeLabel:shut===null||shut.trim()===""?CLOSE_FALLBACK:shut,pill:kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon}}}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()===""?CLOSE_FALLBACK:close,pill:focus.kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon}}}function semiboldFace(theme){let f=face(theme,"medium");return f.fontWeight===void 0?f:{fontFamily:f.fontFamily,fontWeight:"600"}}function heavyFace(theme){let f=face(theme,"bold");return f.fontWeight===void 0?f:{fontFamily:f.fontFamily,fontWeight:"800"}}var CARD_RADIUS3=20,CARD_PAD_TOP=14,CARD_PAD=16,TITLE_SIZE2=18,TITLE_LINE=22,KICKER_SIZE2=15,BADGE_SIZE2=12,BADGE_HEIGHT=24,BODY_SIZE=15,FINDING_SIZE=14.5,FINDING_LINE=21,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;function TopCard({card:card,open:open,onOpenChange:onOpenChange,ask:ask}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles2(home):makeStyles14(theme),[theme,home]),cardSlot=useMemo(()=>slotBox(theme.slots.card),[theme.slots.card]);if(!open)return null;let closeLabel=card.closeLabel===void 0?null:card.closeLabel.trim()!==""?card.closeLabel:CHAT_COPY.close,action=card.action,question=card.ask,glyph=/* @__PURE__ */jsx(CloseGlyph,{size:home!==null?HOME_CLOSE_GLYPH(home):CLOSE_GLYPH3,color:home!==null?String(home.text(".ask-focus__x").color):theme.color.text.primary,strokeWidth:2});/* @__PURE__ */
226
+ return jsxs(View,{style:[styles3.card,cardSlot],testID:"everfur-top-card",children:[
222
227
  /* @__PURE__ */jsxs(View,{style:styles3.kickerRow,children:[
223
228
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.kicker,children:card.kicker}),card.badge!==void 0?/* @__PURE__ */jsx(View,{style:styles3.badge,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.badgeText,numberOfLines:1,children:card.badge})}):null,closeLabel!==null?/* @__PURE__ */jsx(Pressable,{onPress:()=>onOpenChange(false),accessibilityRole:"button",accessibilityLabel:closeLabel,style:styles3.close,hitSlop:home!==null?HOME_SLOP2:void 0,testID:"everfur-top-card-close",children:card.renderIcon!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>card.renderIcon?.("close"),fallback:glyph}):glyph}):null]}),
224
229
  /* @__PURE__ */jsx(Text,{tier:"heading",style:styles3.title,accessibilityRole:"header",children:card.title}),card.lead!==void 0||card.body!==void 0?/* @__PURE__ */jsxs(View,{style:styles3.finding,children:[
@@ -226,7 +231,12 @@ return jsxs(View,{style:styles3.card,testID:"everfur-top-card",children:[
226
231
  /* @__PURE__ */jsxs(Text,{style:styles3.findingText,children:[card.lead!==void 0?/* @__PURE__ */jsx(Text,{style:styles3.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__ */jsxs(View,{style:styles3.actions,children:[action!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:()=>{callHost(action.onPress)},accessibilityRole:"button",accessibilityLabel:action.label,style:styles3.action,hitSlop:home!==null?HOME_SLOP2:void 0,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.actionText,children:action.label})}):null,question!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:()=>ask(question.prompt),accessibilityRole:"button",accessibilityLabel:question.label,style:styles3.ask,hitSlop:home!==null?HOME_SLOP2:void 0,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.askText,children:question.label})}):null]}):null]})}function TopCardPill({card:card,open:open,onOpenChange:onOpenChange}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles2(home):makeStyles14(theme),[theme,home]);if(open||card.closeLabel===void 0)return null;let words2=card.pill??card.kicker;/* @__PURE__ */
227
232
  return jsxs(Pressable,{onPress:()=>onOpenChange(true),accessibilityRole:"button",accessibilityLabel:words2,accessibilityState:{expanded:false},style:styles3.pill,hitSlop:home!==null?HOME_SLOP2:void 0,testID:"everfur-top-card-pill",children:[
228
233
  /* @__PURE__ */jsx(View,{style:styles3.pillDot}),
229
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.pillText,numberOfLines:1,children:words2})]})}var HOME_SLOP2=4,HOME_CLOSE_GLYPH=home=>{let w=home.icon(".ask-focus__x svg").width;return typeof w=="number"?w:CLOSE_GLYPH3};function homeStyles2(home){let finding=home.text(".hp-need__s",".ask-focus .hp-need__s"),lh=typeof finding.lineHeight=="number"?finding.lineHeight:21,dot=home.view(".dot",".dot--risk"),dotSize=typeof dot.height=="number"?dot.height:DOT;return{card:home.view(".ask-focus"),kickerRow:home.view(".hp-need__k"),kicker:[home.text(".hp-need__k"),{flexShrink:1}],badge:[home.view(".hp-srcs"),home.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:home.text(".hp-src",".hp-src--dna"),close:home.view(".ask-focus__x"),title:[home.view(".ask-focus h3"),home.text(".ask-focus h3")],finding:[home.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[home.col(".hp-need__s",0),dot,{marginTop:Math.round((lh-dotSize)/2)}],findingText:[home.col(".hp-need__s",1),finding],lead:(({fontFamily:fontFamily,fontWeight:fontWeight,color:color})=>({fontFamily:fontFamily,fontWeight:fontWeight,color:color}))(home.strong(".hp-need__s b")),actions:home.view(".ask-focus__acts"),action:home.view(".emb-btn",".emb-btn--sm"),actionText:home.text(".emb-btn",".emb-btn--sm"),ask:[home.view(".ask-focus__q"),{justifyContent:"center"}],askText:home.text(".ask-focus__q"),pill:home.view(".ask-focus-pill"),pillDot:home.view(".ask-focus-pill i"),pillText:[home.text(".ask-focus-pill"),{flexShrink:1}]}}function makeStyles14(theme){let c=theme.color,s=theme.space;return 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 KEY3=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function placed(){let g=globalThis,hit=g[KEY3];if(hit!==void 0)return hit;let fresh2={count:0,listeners:/* @__PURE__ */new Set};return g[KEY3]=fresh2,fresh2}var subscribe=listener=>{let p=placed();return p.listeners.add(listener),()=>p.listeners.delete(listener)},snapshot=()=>placed().count>0;function useHostPoweredBy(){return useSyncExternalStore(subscribe,snapshot,snapshot)}function EverfurPoweredBy({children:children,style:style}){let hidden=useEverfurTheme().meta.hidePoweredBy;return useEffect(()=>{if(hidden)return;let p=placed();return p.count+=1,p.listeners.forEach(listener=>listener()),()=>{p.count-=1,p.listeners.forEach(listener=>listener())}},[hidden]),hidden?null:children??/* @__PURE__ */jsx(Text,{tier:"compact",style:style,accessibilityRole:"text",children:CHAT_COPY.poweredBy})}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=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=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,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=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return 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__ */jsx(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]=useState(false);return useEffect(()=>{let keyboard=Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=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__ */
234
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.pillText,numberOfLines:1,children:words2})]})}var HOME_SLOP2=4,HOME_CLOSE_GLYPH=home=>{let w=home.icon(".ask-focus__x svg").width;return typeof w=="number"?w:CLOSE_GLYPH3};function homeStyles2(home){let finding=home.text(".hp-need__s",".ask-focus .hp-need__s"),lh=typeof finding.lineHeight=="number"?finding.lineHeight:21,dot=home.view(".dot",".dot--risk"),dotSize=typeof dot.height=="number"?dot.height:DOT;return{card:home.view(".ask-focus"),kickerRow:home.view(".hp-need__k"),kicker:[home.text(".hp-need__k"),{flexShrink:1}],badge:[home.view(".hp-srcs"),home.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:home.text(".hp-src",".hp-src--dna"),close:home.view(".ask-focus__x"),title:[home.view(".ask-focus h3"),home.text(".ask-focus h3")],finding:[home.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[home.col(".hp-need__s",0),dot,{marginTop:Math.round((lh-dotSize)/2)}],findingText:[home.col(".hp-need__s",1),finding],lead:(({fontFamily:fontFamily,fontWeight:fontWeight,color:color})=>({fontFamily:fontFamily,fontWeight:fontWeight,color:color}))(home.strong(".hp-need__s b")),actions:home.view(".ask-focus__acts"),action:[home.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:home.text(".emb-btn",".emb-btn--sm"),ask:[home.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:home.text(".ask-focus__q"),pill:[home.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:home.view(".ask-focus-pill i"),pillText:[home.text(".ask-focus-pill"),{flexShrink:1}]}}function makeStyles14(theme){let c=theme.color,s=theme.space;return 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:{...heavyFace(theme),fontSize:KICKER_SIZE2,color:c.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:BADGE_HEIGHT,justifyContent:"center",paddingHorizontal:9,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,flexShrink:1},badgeText:{...face(theme,"bold"),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:{...heavyFace(theme),fontSize:TITLE_SIZE2,lineHeight:TITLE_LINE,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:FINDING_SIZE,lineHeight:FINDING_LINE,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 DESIGN_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...DESIGN_V3_LIGHT},textOn=(ink,grounds2)=>pushToContrast(ink,grounds2,poleForGrounds(grounds2),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}function mix(color,share,ground){let over=withAlpha(color,share);return(over===null?null:flattenOnto(over,ground))??ground}function askIntroColors(theme){let v=v3Palette(theme),c=theme.color,card=v.card;return{ink:v.ink,ink2:v.ink2,ink3:v.ink3,paper:v.paper,tile:v.tile,line:v.line,card:card,onInk:v.dark?c.background:"#FFFFFF",primary:v.primary,onPrimary:v.onPrimary,accent:v.accent,onAccent:v3InkOn(v.accent,[v.ink,v.onAccent]),accent2:mix(v.accent,.75,card),accent4:mix(v.accent,.17,card),accentChip:mix(v.accent,.47,card),link:v.link,linkChip:mix(v.link,.2,card),riskDot:v.riskDot,riskChip:v.dark?c.badgeBgCritical:"#FFD8D6",clearBg:v.clearBg,clearInk:v.clearInk,clearChip:v.dark?c.badgeBgPositive:"#DDEFC4",byInk:c.brandInk}}var TEXT_KEYS=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),RUNTIME_KEYS=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),PAD=["paddingTop","paddingRight","paddingBottom","paddingLeft"],ROOT_SIZE=17,ROOT_LH=1.5,ROOT_WEIGHT=400,BOLD_WEIGHT=700;function faceKeyFor(weight){return weight<=450?"regular":weight<=650?"medium":"bold"}function asWeight(value){let clamped=Math.min(900,Math.max(100,Math.round(value/100)*100));return String(clamped)}function designFace(theme,family,weight){if(family==="$mono"){let mono=weight<=450?"mono":weight<=650?"monoMedium":"monoBold",f2=face(theme,mono);return f2.fontWeight===void 0?{fontFamily:f2.fontFamily}:{fontFamily:f2.fontFamily,fontWeight:asWeight(weight)}}let f=family==="$serif"?headingFace(theme,faceKeyFor(weight)):face(theme,faceKeyFor(weight));return f.fontWeight===void 0?{fontFamily:f.fontFamily}:{fontFamily:f.fontFamily,fontWeight:asWeight(weight)}}function createDesignKit(theme,table,reducedTable={}){let colors=askIntroColors(theme),dark=theme.brightness==="dark",reduced=theme.motion.reducedMotion,fill=value=>{if(typeof value=="string"&&value.startsWith("$")){let key=value.slice(1);return key.startsWith("n_")?dark?colors.line??value:`#${key.slice(2)}`:key==="sans"||key==="serif"||key==="mono"?value:colors[key]??value}return Array.isArray(value)?value.map(v=>fill(v)):value},merged=/* @__PURE__ */new Map,merge=selectors=>{let keys=selectors.filter(s=>typeof s=="string"&&s!==""),id=keys.join("|"),hit=merged.get(id);if(hit!==void 0)return hit;let out={},put=rule=>{if(rule!==void 0)for(let[k,v]of Object.entries(rule))out[k]=fill(v)};for(let key of keys)put(table[key]),reduced&&put(reducedTable[key]);let frozen=/* @__PURE__ */Object.freeze(out);return merged.set(id,frozen),frozen},viewCache=/* @__PURE__ */new Map,view=(...selectors)=>{let id=selectors.filter(Boolean).join("|"),hit=viewCache.get(id);if(hit!==void 0)return hit;let r=merge(selectors),out={};for(let[k,v]of Object.entries(r))TEXT_KEYS.has(k)||RUNTIME_KEYS.has(k)||k==="ring"||k==="edge"||k==="shadow"||k==="round"||k==="zIndex"&&typeof v=="number"&&v<0||v!==null&&(out[k]=v);if((typeof r.fontSize=="number"||r.flexDirection==="row")&&r.position!=="absolute"&&typeof r.height=="number"&&typeof r.width!="number"){let h=out.height;delete out.height,typeof out.minHeight!="number"&&(out.minHeight=h)}let ring=r.ring;if(Array.isArray(ring)){let[w,color]=ring;out.borderWidth=w,out.borderColor=color;for(let side of PAD){let p=out[side];typeof p=="number"&&(out[side]=Math.max(0,p-w))}}let edge=r.edge;if(Array.isArray(edge)){let[w,color]=edge;out.borderBottomWidth=w,out.borderBottomColor=color}let shadow=r.shadow;if(Array.isArray(shadow)){let[x,y,blur,color]=shadow;out.shadowColor=color,out.shadowOffset={width:x,height:y},out.shadowOpacity=1,out.shadowRadius=blur/2}if(r.round===1){let size=typeof r.width=="number"?r.width:typeof r.height=="number"?r.height:999;out.borderRadius=size/2}let style=/* @__PURE__ */Object.freeze(out);return viewCache.set(id,style),style},textCache=/* @__PURE__ */new Map,textOf=(base2,selectors)=>{let id=`${base2}|${selectors.filter(Boolean).join("|")}`,hit=textCache.get(id);if(hit!==void 0)return hit;let r=merge(selectors),size=typeof r.fontSize=="number"?r.fontSize:ROOT_SIZE,lh=typeof r.lh=="number"?r.lh:ROOT_LH,weight=typeof r.fontWeight=="string"?Number(r.fontWeight):base2,family=typeof r.family=="string"?r.family:"$sans",out={...designFace(theme,family,weight),fontSize:size,lineHeight:Math.round(size*lh*100)/100,color:typeof r.color=="string"?r.color:colors.ink};typeof r.ls=="number"&&(out.letterSpacing=Math.round(r.ls*size*100)/100);for(let k of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof r[k]=="string"&&(out[k]=r[k]);let style=/* @__PURE__ */Object.freeze(out);return textCache.set(id,style),style};return{reduced:reduced,colors:colors,view:view,text:(...selectors)=>textOf(ROOT_WEIGHT,selectors),strong:(...selectors)=>textOf(BOLD_WEIGHT,selectors),icon:(...selectors)=>{let r=merge(selectors),out={tintColor:typeof r.color=="string"?r.color:colors.ink};for(let k of["width","height","opacity"])typeof r[k]=="number"&&(out[k]=r[k]);return out},col:(selector,index)=>{let cols=merge([selector]).cols;if(!Array.isArray(cols))return{};let c=cols[Math.min(index,cols.length-1)];if(typeof c=="number")return{width:c,flexShrink:0};let share=typeof c=="string"?Number.parseFloat(c):1;return{flex:Number.isFinite(share)?share:1,minWidth:0}},motion:(...selectors)=>{let r=merge(selectors),ease=r.ease;return{dur:typeof r.dur=="number"?r.dur:0,delay:typeof r.delay=="number"?r.delay:0,stagger:typeof r.stagger=="number"?r.stagger:0,ease:Array.isArray(ease)&&ease.length===4?ease:null}},raw:(key,...selectors)=>merge(selectors)[key]}}var ASK_HOME_RN={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},ASK_HOME_TITLE_CH=16;var PROBE_ROOM=4e3,HALF=.5;function linesAt(words2,space,width){let lines=1,line=-1;for(let w of words2)line<0?line=w:line+space+w<=width?line+=space+w:(lines+=1,line=w);return lines}function balancedWidth(words2,space,measure){if(words2.length===0)return measure;let lines=linesAt(words2,space,measure),widths=[];for(let i=0;i<words2.length;i+=1){let run=0;for(let j=i;j<words2.length;j+=1)run+=(j>i?space:0)+words2[j],run<=measure&&widths.push(run)}widths.sort((a,b)=>a-b);let slack=HALF*words2.length+1;for(let w of widths)if(linesAt(words2,space,w)<=lines)return Math.min(measure,w+slack);return measure}function BalancedTitle({text:text3,style:style,measureCh:measureCh}){let words2=useMemo(()=>text3.split(/\s+/).filter(w=>w!==""),[text3]),flat=StyleSheet.flatten(style),key=[text3,flat.fontFamily,flat.fontSize,flat.fontWeight,flat.letterSpacing].join("|"),sizes=useRef({key:"",ch:null,line:null,words:[]});sizes.current.key!==key&&(sizes.current={key:key,ch:null,line:null,words:words2.map(()=>null)});let[width,setWidth]=useState(null),capped=width!==null&&width.key===key?width.value:null,settle=()=>{let s=sizes.current;if(s.ch===null||s.line===null||s.words.some(w=>w===null))return;let ws=s.words,sum=ws.reduce((a,b)=>a+b,0),space=ws.length>1?Math.max(0,(s.line-sum)/(ws.length-1)):0,value=balancedWidth(ws,space,(s.ch+HALF)*measureCh);setWidth(previous=>previous!==null&&previous.key===s.key&&previous.value===value?previous:{key:s.key,value:value})},measure=set=>event=>{sizes.current.key===key&&(set(sizes.current,event.nativeEvent.layout.width),settle())};/* @__PURE__ */
235
+ return jsxs(View,{style:styles2.wrap,children:[
236
+ /* @__PURE__ */jsx(Text,{tier:"heading",style:capped===null?style:[style,{maxWidth:capped}],accessibilityRole:"header",children:text3}),
237
+ /* @__PURE__ */jsx(View,{style:styles2.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsxs(View,{style:styles2.probeRow,children:[
238
+ /* @__PURE__ */jsx(Text,{tier:"heading",style:style,onLayout:measure((s,w)=>{s.ch=w}),children:"0"}),
239
+ /* @__PURE__ */jsx(Text,{tier:"heading",style:style,onLayout:measure((s,w)=>{s.line=w}),children:words2.join(" ")}),words2.map((word,index)=>/* @__PURE__ */jsx(Text,{tier:"heading",style:style,onLayout:measure((s,w)=>{s.words[index]=w}),children:word},`${index}:${word}`))]})})]})}var styles2=StyleSheet.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:PROBE_ROOM,flexDirection:"row",alignItems:"flex-start"}});function createAskHome(theme){return{kit:createDesignKit(theme,ASK_HOME_RN),Title:BalancedTitle,titleCh:ASK_HOME_TITLE_CH}}var KEY3=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function placed(){let g=globalThis,hit=g[KEY3];if(hit!==void 0)return hit;let fresh2={count:0,listeners:/* @__PURE__ */new Set};return g[KEY3]=fresh2,fresh2}var subscribe=listener=>{let p=placed();return p.listeners.add(listener),()=>p.listeners.delete(listener)},snapshot=()=>placed().count>0;function useHostPoweredBy(){return useSyncExternalStore(subscribe,snapshot,snapshot)}function EverfurPoweredBy({children:children,style:style}){let hidden=useEverfurTheme().meta.hidePoweredBy;return useEffect(()=>{if(hidden)return;let p=placed();return p.count+=1,p.listeners.forEach(listener=>listener()),()=>{p.count-=1,p.listeners.forEach(listener=>listener())}},[hidden]),hidden?null:children??/* @__PURE__ */jsx(Text,{tier:"compact",style:style,accessibilityRole:"text",children:CHAT_COPY.poweredBy})}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=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=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,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=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return 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__ */jsx(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]=useState(false);return useEffect(()=>{let keyboard=Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=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__ */
230
240
  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,slot2){if(slot2===void 0)return tier;let next={...tier};return slot2.backgroundColor!==void 0&&(next.backgroundColor=slot2.backgroundColor),slot2.borderColor!==void 0&&(next.borderColor=slot2.borderColor),slot2.textColor!==void 0&&(next.textColor=slot2.textColor,next.reasonColor=slot2.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(),styles3=useMemo(()=>makeStyles15(theme),[theme]),motion=useChatMotion(),tier=surface.tier===null?null:themedUrgencyTier(surface.tier,theme),source=surface.source;/* @__PURE__ */
231
241
  return jsxs(Fragment,{children:[
232
242
  /* @__PURE__ */jsx(FadePresence,{visible:surface.showBanner&&tier!==null,inMs:motion.bannerInMs,outMs:motion.bannerOutMs,style:styles3.pinned,children:tier!==null&&source!==null?/* @__PURE__ */jsx(BannerCard,{tier:tier,reason:source.reason,surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles3,compact:compact}):null}),
@@ -243,10 +253,10 @@ return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.
243
253
  /* @__PURE__ */jsx(BrandImage,{uri:avatarUrl,decorative:true,style:styles3.assistantAvatar,resizeMode:"cover",onError:image.onError,testID:"everfur-assistant-avatar"}),named?/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.assistantName,styles3.assistantNameInRow],children:CHAT_COPY.assistantName}):null]}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.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 httpsUrl2(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__ */
244
254
  return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl2(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(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}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,LINK_TOKEN=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${MAX_LINK_LENGTH}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${MAX_LINK_LENGTH}})`,"gi"),HAS_ADDRESS=/https:\/\//i,SENTENCE_END=`.,;:!?'"`;function hasInlineMarkup(text3,linkHosts){return text3.includes("*")||text3.includes("`")||linkHosts!==void 0&&HAS_ADDRESS.test(text3)}function tokenizeInlineMarkdown(text3,linkHosts){let runs=[],plain=slice=>{linkHosts===void 0?runs.push({kind:"text",text:slice}):pushLinked(runs,slice,linkHosts)},cursor=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor&&plain(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&&plain(text3.slice(cursor)),runs}function trimAddress(address){let end=address.length;for(;;){let last=address[end-1];if(last===void 0)break;if(SENTENCE_END.includes(last))end-=1;else if(last===")"&&count(address,"(",end)<count(address,")",end))end-=1;else break}return address.slice(0,end)}function count(value,char,end){let n=0;for(let i=0;i<end;i+=1)value[i]===char&&(n+=1);return n}function pushLinked(runs,slice,linkHosts){if(!HAS_ADDRESS.test(slice)){runs.push({kind:"text",text:slice});return}let cursor=0;LINK_TOKEN.lastIndex=0;for(let match=LINK_TOKEN.exec(slice);match!==null;match=LINK_TOKEN.exec(slice)){let label=match[1],labelled=match[2],raw=match[3],text3,href,consumed;if(label!==void 0&&labelled!==void 0)text3=label.trim(),href=text3.length>0?linkHref(labelled,linkHosts):null,consumed=match[0].length;else if(raw!==void 0)text3=trimAddress(raw),href=linkHref(text3,linkHosts),consumed=text3.length;else continue;href!==null&&(match.index>cursor&&runs.push({kind:"text",text:slice.slice(cursor,match.index)}),runs.push({kind:"link",text:text3,href:href}),cursor=match.index+consumed,LINK_TOKEN.lastIndex=cursor)}cursor<slice.length&&runs.push({kind:"text",text:slice.slice(cursor)})}var LINK_STYLE=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function hasMessageLink(text3,links){return links===void 0||!hasInlineMarkup(text3,links.hosts)?false:tokenizeInlineMarkdown(text3,links.hosts).some(run=>run.kind==="link")}function renderInlineMarkdown(text3,styles3,links){let hosts=links?.hosts;return hasInlineMarkup(text3,hosts)?tokenizeInlineMarkdown(text3,hosts).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
245
255
  return jsx(Text,{style:styles3.bold,children:run.text},key);case"italic":return styles3.italic?/* @__PURE__ */jsx(Text,{style:styles3.italic,children:run.text},key):run.text;case"code":return styles3.code?/* @__PURE__ */jsx(Text,{style:styles3.code,children:run.text},key):run.text;case"link":{if(links===void 0)return run.text;let{href:href}=run;/* @__PURE__ */
246
- return jsx(Text,{style:LINK_STYLE,accessibilityRole:"link",accessibilityLabel:run.text,onPress:()=>links.open(href),children:run.text},key)}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(),styles3=useMemo(()=>makeStyles16(theme),[theme]);return{theme:theme,styles:styles3}}function Chevron({options:options,color:color}){let glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:CHEVRON,color:color,strokeWidth:2,direction:"right"}),render=options?.renderIcon;return render===void 0?glyph:/* @__PURE__ */jsx(HostRender,{render:()=>render("chevron"),fallback:glyph})}function AnswerCard({card:card,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(card.render!==void 0){let render=card.render;/* @__PURE__ */
256
+ return jsx(Text,{style:LINK_STYLE,accessibilityRole:"link",accessibilityLabel:run.text,onPress:()=>links.open(href),children:run.text},key)}default:return run.text}}):text3}var MONO_SIZE2=10.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=21,ROW_MIN=42,ROW_SLOP=1,RING_ALPHA=.06,SHADOW_ALPHA=.07,TILE_WASH_ALPHA=.12,PILL_MAX_SHARE="45%";function useCardStyles(){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles16(theme),[theme]);return{theme:theme,styles:styles3}}function Chevron({options:options,color:color}){let glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:CHEVRON,color:color,strokeWidth:2,direction:"right"}),render=options?.renderIcon;return render===void 0?glyph:/* @__PURE__ */jsx(HostRender,{render:()=>render("chevron"),fallback:glyph})}function AnswerCard({card:card,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(card.render!==void 0){let render=card.render;/* @__PURE__ */
247
257
  return jsx(View,{style:[styles3.card,card.variant!==void 0?options?.styles?.cardVariant?.[card.variant]:null],accessible:false,accessibilityLabel:card.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */jsx(HostRender,{render:render,fallback:null})})}let stat=card.value!==void 0,host=options?.styles,cardStyle=[styles3.card,stat?host?.cardStat:null,card.variant!==void 0?host?.cardVariant?.[card.variant]:null],tileTone=card.tile?.tone,pillTone=card.pill?.tone,image=card.tile?.imageUrl!==void 0?tileImageUrl(card.tile.imageUrl):null,body=/* @__PURE__ */jsxs(Fragment,{children:[stat?null:/* @__PURE__ */jsx(View,{style:[styles3.tile,tileTone!==void 0?host?.tileTone?.[tileTone]:null],children:image!==null?/* @__PURE__ */jsx(Image,{source:{uri:image},style:styles3.tileImage,accessibilityIgnoresInvertColors:true}):card.tile?.icon??null}),
248
258
  /* @__PURE__ */jsxs(View,{style:styles3.cardWords,children:[
249
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.cardTitle,children:card.title}),card.meta!==void 0?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.cardMeta,children:card.meta}):null]}),stat?/* @__PURE__ */jsxs(Text,{tier:"control",style:styles3.stat,children:[card.value?.amount,card.value?.unit!==void 0?/* @__PURE__ */jsx(Text,{style:styles3.statUnit,children:card.value.unit}):null]}):/* @__PURE__ */jsxs(Fragment,{children:[card.pill!==void 0?/* @__PURE__ */jsx(View,{style:[styles3.pill,pillTone!==void 0?host?.pillTone?.[pillTone]:null],children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles3.pillText,pillTone!==void 0?host?.pillToneText?.[pillTone]:null],numberOfLines:1,children:card.pill.label})}):null,card.onPress!==void 0?/* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.text.muted}):null]})]});if(card.onPress!==void 0){let onPress=card.onPress;/* @__PURE__ */
259
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.cardTitle,children:card.title}),card.meta!==void 0?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.cardMeta,children:card.meta}):null]}),stat?/* @__PURE__ */jsxs(Text,{tier:"control",style:styles3.stat,children:[card.value?.amount,card.value?.unit!==void 0?/* @__PURE__ */jsx(Text,{style:styles3.statUnit,children:card.value.unit}):null]}):/* @__PURE__ */jsxs(Fragment,{children:[card.pill!==void 0?/* @__PURE__ */jsx(View,{style:[styles3.pill,pillTone!==void 0?host?.pillTone?.[pillTone]:null],children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles3.pillText,pillTone!==void 0?host?.pillToneText?.[pillTone]:null],numberOfLines:1,ellipsizeMode:"tail",children:card.pill.label})}):null,card.onPress!==void 0?/* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.text.muted}):null]})]});if(card.onPress!==void 0){let onPress=card.onPress;/* @__PURE__ */
250
260
  return jsx(Pressable,{onPress:()=>{callHost(onPress)},accessibilityRole:"button",accessibilityLabel:card.title,style:cardStyle,children:body})}/* @__PURE__ */
251
261
  return jsx(View,{style:cardStyle,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:styles3}=useCardStyles(),context=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=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:styles3.bold,italic:styles3.italic,code:styles3.code},messageLinks=useMessageLinks(),links=settled?messageLinks:void 0;/* @__PURE__ */
252
262
  return jsxs(View,{style:styles3.answer,testID:"everfur-answer-cards",children:[byline!==void 0?/* @__PURE__ */jsxs(View,{style:styles3.byline,children:[byline.icon??null,
@@ -254,22 +264,24 @@ return jsxs(View,{style:styles3.answer,testID:"everfur-answer-cards",children:[b
254
264
  /* @__PURE__ */jsx(View,{style:styles3.body,children:answerParagraphs(text3).flatMap((paragraph,index)=>answerBlocks(paragraph).map((block,at)=>{let key=`${index}-${at}`;return block.kind==="text"?/* @__PURE__ */jsx(Text,{style:styles3.paragraph,children:renderInlineMarkdown(block.text,inline,links)},key):/* @__PURE__ */jsx(View,{style:styles3.list,children:block.items.map((item,n)=>/* @__PURE__ */jsxs(View,{style:styles3.listItem,children:[
255
265
  /* @__PURE__ */jsx(Text,{style:styles3.paragraph,children:block.ordered?`${block.start+n}.`:"•"}),
256
266
  /* @__PURE__ */jsx(Text,{style:[styles3.paragraph,styles3.listText],children:renderInlineMarkdown(item,inline,links)})]},n))},key)}))}),hostCards.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:hostCards.map(card=>/* @__PURE__ */jsx(AnswerCard,{card:card,options:options},card.key))}):null,sources.length>0?/* @__PURE__ */jsxs(View,{style:styles3.cards,accessibilityLabel:sourcesLabel(sources.length),children:[
257
- /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.label,children:sourcesLabel(sources.length)}),sources.map(source=>{let url=source.url;/* @__PURE__ */
267
+ /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.label,children:CHAT_COPY.sourcesHeading}),sources.map(source=>{let url=source.url;/* @__PURE__ */
258
268
  return jsx(AnswerCard,{card:{key:source.key,title:source.title,...source.meta!==null?{meta:source.meta}:{},tile:{icon:/* @__PURE__ */jsx(SourceTileGlyph,{})},...onOpenUrl!==void 0&&url!==null?{onPress:()=>onOpenUrl(url)}:{}},options:options},source.key)})]}):null,settled&&chips!==null&&onSentiment!==void 0?/* @__PURE__ */jsxs(View,{style:[styles3.feedback,options?.styles?.feedback],children:[
259
269
  /* @__PURE__ */jsx(FeedbackChip,{label:chips.helpful,on:sentiment==="up",onPress:()=>onSentiment("up"),styles:styles3,host:options?.styles}),
260
270
  /* @__PURE__ */jsx(FeedbackChip,{label:chips.notHelpful,on:sentiment==="down",onPress:()=>onSentiment("down"),styles:styles3,host:options?.styles})]}):null,settled?footer(chips===null):null]})}function SourceTileGlyph(){let theme=useEverfurTheme();/* @__PURE__ */
261
- return jsx(BookGlyph,{size:TILE_GLYPH2,color:theme.color.brandInk,strokeWidth:1.5})}function FeedbackChip({label:label,on:on,onPress:onPress,styles:styles3,host:host}){/* @__PURE__ */
262
- return jsx(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:on},style:[styles3.chip,host?.feedbackChip,on?styles3.chipOn:null],hitSlop:(MIN_TOUCH_TARGET-CHIP_HEIGHT)/2,children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.chipText,host?.feedbackChipText],children:label})})}function CardsFollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt,label:label,actions:actions,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(prompts.length===0&&actions.length===0)return null;let host=options?.styles;/* @__PURE__ */
263
- return jsxs(View,{style:[styles3.followUps,host?.followUps],accessibilityLabel:label??CHAT_COPY.followUpsHeadingNative,testID:"everfur-cards-follow-ups",children:[label!==void 0?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.label,host?.followUpsLabel],accessibilityRole:"header",children:label}):null,actions.map(action=>/* @__PURE__ */jsxs(Pressable,{onPress:()=>{callHost(action.onPress)},accessibilityRole:"button",accessibilityLabel:action.label,style:[styles3.row,styles3.rowAction,host?.followUp,host?.followUpAction],children:[action.icon??null,
271
+ return jsx(BookGlyph,{size:TILE_GLYPH2,color:theme.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:label,on:on,onPress:onPress,styles:styles3,host:host}){/* @__PURE__ */
272
+ return jsx(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:on},style:[styles3.chip,host?.feedbackChip,on?styles3.chipOn:null],hitSlop:(MIN_TOUCH_TARGET-CHIP_HEIGHT)/2,children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.chipText,host?.feedbackChipText],children:label})})}function CardsFollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt,label:label,actions:actions,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(prompts.length===0&&actions.length===0)return null;let host=options?.styles,shown=label??CHAT_COPY.followUpsHeadingNative;/* @__PURE__ */
273
+ return jsxs(View,{style:[styles3.followUps,host?.followUps],accessibilityLabel:shown,testID:"everfur-cards-follow-ups",children:[
274
+ /* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.label,host?.followUpsLabel],accessibilityRole:"header",children:shown}),actions.map(action=>/* @__PURE__ */jsxs(Pressable,{onPress:()=>{callHost(action.onPress)},accessibilityRole:"button",accessibilityLabel:action.label,hitSlop:ROW_SLOP,style:[styles3.row,styles3.rowAction,host?.followUp,host?.followUpAction],children:[action.icon??null,
264
275
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.rowText,styles3.rowTextAction,host?.followUpText,host?.followUpActionText],children:action.label}),
265
- /* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.text.primary})]},`action:${action.key}`)),prompts.map(prompt=>/* @__PURE__ */jsxs(Pressable,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,style:[styles3.row,host?.followUp],children:[
276
+ /* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.text.primary})]},`action:${action.key}`)),prompts.map(prompt=>/* @__PURE__ */jsxs(Pressable,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,hitSlop:ROW_SLOP,style:[styles3.row,host?.followUp],children:[
266
277
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.rowText,host?.followUpText],children:prompt}),
267
- /* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.brandInk})]},prompt))]})}function makeStyles16(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 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]=useState(null),[error,setError]=useState(null),[tapped,setTapped]=useState(null),choose=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(),styles3=useMemo(()=>makeStyles17(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__ */
278
+ /* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.linkInk})]},prompt))]})}function CardsByline({label:label}){let{styles:styles3}=useCardStyles();/* @__PURE__ */
279
+ return jsx(View,{style:styles3.byline,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.bylineText,children:label})})}function makeStyles16(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},hairline={borderWidth:1,borderColor:withAlpha(c.text.primary,RING_ALPHA)??c.borderRingCream},lift={shadowColor:c.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:SHADOW_ALPHA,shadowRadius:2,elevation:1},message=textRole(theme,"message"),chipInk=slotText(theme.slots.chip);return 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:message.fontSize,lineHeight:Math.round(message.lineHeight),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,...hairline,...lift,minHeight:MIN_TOUCH_TARGET,...slotBox(theme.slots.card)},tile:{width:TILE,height:TILE,borderRadius:TILE_RADIUS,backgroundColor:withAlpha(c.linkInk,TILE_WASH_ALPHA)??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,...slotText(theme.slots.card)},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:1,maxWidth:PILL_MAX_SHARE},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:{...semiboldFace(theme),fontSize:CHIP_SIZE,color:c.text.primary,...chipInk},followUps:{gap:s.sm,alignSelf:"stretch",marginTop:s.xs},label:{...face(theme,"bold"),fontSize:LABEL_SIZE2,lineHeight:Math.round(LABEL_SIZE2*1.5),color:c.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:ROW_MIN,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:ROW_RADIUS2,backgroundColor:c.surface,...hairline},rowAction:{},rowText:{...semiboldFace(theme),flex:1,fontSize:ROW_SIZE,lineHeight:Math.round(ROW_SIZE*1.3),color:c.linkInk},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]=useState(null),[error,setError]=useState(null),[tapped,setTapped]=useState(null),choose=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(),styles3=useMemo(()=>makeStyles17(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__ */
268
280
  return jsxs(View,{style:styles3.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onLayout:onLayout,children:[
269
281
  /* @__PURE__ */jsxs(View,{style:styles3.head,children:[
270
282
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.eyebrow,children:CHECKIN_COPY.eyebrow}),day!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.headDay,children:fillCopy(CHECKIN_COPY.day,{day:day})}):null]}),
271
283
  /* @__PURE__ */jsx(Text,{style:styles3.question,accessibilityRole:"text",children:message.text}),answerable?/* @__PURE__ */jsx(View,{style:[styles3.row,state.pending?styles3.rowPending:null],children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
272
- return jsx(Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles3.pill,selected?styles3.pillSelected:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.pillLabel,selected?styles3.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsx(Text,{style:styles3.logged,children:CHECKIN_COPY.logged}):null,state.escalated?/* @__PURE__ */jsx(CheckinFindVet,{petRef:petRef??null,onFindVet:onFindVet,vet:vet,styles:styles3}):null,checkin.resolutionText?/* @__PURE__ */jsx(Text,{style:styles3.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsx(Text,{style:styles3.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function CheckinFindVet({petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles3}){return useVetVisit(chatVetVisitOptions(petRef,vet)).available&&petRef!==null?/* @__PURE__ */jsx(VetVisitButtonCore,{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:styles3.findVet,labelStyle:styles3.findVetLabel}):onFindVet===void 0?null:/* @__PURE__ */jsx(Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles3.findVet,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.findVetLabel,children:CHECKIN_COPY.findVet})})}function makeStyles17(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,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 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(),styles3=useMemo(()=>makeStyles18(theme),[theme]),cards=useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=useState(false);if(cards.length===0)return null;let count2=cards.length;/* @__PURE__ */
284
+ return jsx(Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles3.pill,selected?styles3.pillSelected:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.pillLabel,selected?styles3.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsx(Text,{style:styles3.logged,children:CHECKIN_COPY.logged}):null,state.escalated?/* @__PURE__ */jsx(CheckinFindVet,{petRef:petRef??null,onFindVet:onFindVet,vet:vet,styles:styles3}):null,checkin.resolutionText?/* @__PURE__ */jsx(Text,{style:styles3.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsx(Text,{style:styles3.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function CheckinFindVet({petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles3}){return useVetVisit(chatVetVisitOptions(petRef,vet)).available&&petRef!==null?/* @__PURE__ */jsx(VetVisitButtonCore,{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:styles3.findVet,labelStyle:styles3.findVetLabel}):onFindVet===void 0?null:/* @__PURE__ */jsx(Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles3.findVet,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.findVetLabel,children:CHECKIN_COPY.findVet})})}function makeStyles17(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,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 CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE2=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles18(theme),[theme]),cards=useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=useState(false);if(cards.length===0)return null;let count2=cards.length;/* @__PURE__ */
273
285
  return jsxs(View,{style:styles3.block,children:[
274
286
  /* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count2,expanded),accessibilityState:{expanded:expanded},containerStyle:styles3.toggleSlot,style:styles3.togglePill,onPress:()=>setExpanded(current=>!current),children:[
275
287
  /* @__PURE__ */jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
@@ -280,14 +292,14 @@ return jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(ScrollView,{hor
280
292
  /* @__PURE__ */jsx(View,{style:[styles3.tierDot,{backgroundColor:card.tierColor}]}),
281
293
  /* @__PURE__ */jsx(Text,{style:[styles3.cardTitle,linked?styles3.cardTitleLink:null],numberOfLines:2,children:card.title}),linked?/* @__PURE__ */jsx(ArrowUpRightGlyph,{size:LINK_GLYPH,color:theme.color.linkInk,strokeWidth:1.5}):null]}),card.meta!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.cardMeta,numberOfLines:1,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsx(Text,{style:styles3.cardExcerpt,numberOfLines:3,children:card.excerpt}):null]});if(card.url!==null&&open!==void 0){let url=card.url;/* @__PURE__ */
282
294
  return jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:label,style:styles3.card,onPress:()=>open(url),children:inner})}/* @__PURE__ */
283
- return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles3.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 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_BOX=44,ROW_HEIGHT=16,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,note:note=null}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles19(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=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]=useState(false),resetTimer=useRef(null);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__ */jsxs(View,{style:styles3.wrap,children:[
295
+ return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles3.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 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_LINE2,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_BOX=44,ROW_HEIGHT=16,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,note:note=null}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles19(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=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]=useState(false),resetTimer=useRef(null);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__ */jsxs(View,{style:styles3.wrap,children:[
284
296
  /* @__PURE__ */jsxs(View,{style:[styles3.row,isUser?styles3.rowUser:styles3.rowAssistant],children:[timeLabel!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.timestamp,children:timeLabel}):null,canCopy?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:justCopied?CHAT_COPY.copied:isUser?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,onPress:copy,style:styles3.iconHit,children:justCopied?/* @__PURE__ */jsx(CheckGlyph,{size:ICON_SIZE,color:theme.color.success,strokeWidth:2}):/* @__PURE__ */jsx(CopyGlyph,{size:ICON_SIZE,color:theme.color.text.timestamp,strokeWidth:1.5})}):null,thumbs?SENTIMENT_OPTIONS.map(({sentiment:kind,label:label})=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:sentiment===kind},onPress:()=>onSentiment?.(kind),style:styles3.iconHit,children:/* @__PURE__ */jsx(ThumbGlyph,{size:ICON_SIZE,color:sentiment===kind?theme.color.sentiment[kind]:theme.color.text.timestamp,active:sentiment===kind,rotate:SENTIMENT_ROTATE[kind],strokeWidth:1.5})},kind)):null]}),note==="thanks"?/* @__PURE__ */jsx(Text,{style:styles3.thanks,accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackThanks}):null,note==="failed"?/* @__PURE__ */jsxs(Fragment,{children:[
285
297
  /* @__PURE__ */jsx(Text,{style:styles3.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackFailed}),
286
- /* @__PURE__ */jsx(AnnounceLine,{line:CHAT_COPY.feedbackFailed})]}):null]})}function makeStyles19(theme){let t=theme.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:ROW_HEIGHT,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_BOX,height:ICON_BOX,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.danger}})}var CARD_PAD3=14,CARD_GAP=12,LINE_GAP=2;function OpeningCard({card:card,onLayout:onLayout}){let theme=useEverfurTheme(),c=theme.color,host=card.styles;/* @__PURE__ */
287
- return jsxs(View,{testID:"everfur-opening-card",onLayout:onLayout,accessible:true,accessibilityLabel:[card.kicker,card.title,card.body].filter(part=>part!==void 0).join(", "),style:[styles2.card,{borderRadius:theme.radius.lg,backgroundColor:c.surfaceSubtle},host?.card],children:[card.icon!==void 0?/* @__PURE__ */jsx(View,{style:[styles2.icon,host?.icon],children:card.icon}):null,
288
- /* @__PURE__ */jsxs(View,{style:styles2.words,children:[
289
- /* @__PURE__ */jsx(Text,{tier:"compact",style:[face(theme,"regular"),{color:c.text.secondary},host?.kicker],children:card.kicker}),
290
- /* @__PURE__ */jsx(Text,{tier:"control",style:[face(theme,"bold"),{color:c.text.primary},host?.title],children:card.title}),card.body!==void 0?/* @__PURE__ */jsx(Text,{style:[face(theme,"regular"),{color:c.text.primary},host?.body],children:card.body}):null]})]})}var styles2=StyleSheet.create({card:{flexDirection:"row",gap:CARD_GAP,padding:CARD_PAD3,alignSelf:"stretch"},icon:{flexShrink:0},words:{flex:1,minWidth:0,gap:LINE_GAP}});var QUICK_PROMPT_BRAND_EDGE="#10462E",VET_PREP_LABEL_WEB="Book a video visit",QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
298
+ /* @__PURE__ */jsx(AnnounceLine,{line:CHAT_COPY.feedbackFailed})]}):null]})}function makeStyles19(theme){let t=theme.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:ROW_HEIGHT,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_BOX,height:ICON_BOX,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.danger}})}var CARD_RADIUS5=16,CARD_PAD_Y=10,CARD_PAD_X=12,CARD_GAP=10,LINE_GAP=2,RING_ALPHA2=.06,TILE2=34,TILE_RADIUS2=9,KICKER_SIZE3=10.5,KICKER_TRACKING=.06,TITLE_SIZE3=15,TITLE_LINE3=19.5,BODY_SIZE2=14,BODY_LINE=19.6;function OpeningCard({card:card,onLayout:onLayout}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles20(theme),[theme]),host=card.styles;/* @__PURE__ */
299
+ return jsxs(View,{testID:"everfur-opening-card",onLayout:onLayout,accessible:true,accessibilityLabel:[card.kicker,card.title,card.body].filter(part=>part!==void 0).join(", "),style:[styles3.card,host?.card],children:[card.icon!==void 0?/* @__PURE__ */jsx(View,{style:[styles3.icon,host?.icon],children:card.icon}):null,
300
+ /* @__PURE__ */jsxs(View,{style:styles3.words,children:[
301
+ /* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.kicker,host?.kicker],children:card.kicker}),
302
+ /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.title,host?.title],children:card.title}),card.body!==void 0?/* @__PURE__ */jsx(Text,{style:[styles3.body,host?.body],children:card.body}):null]})]})}function makeStyles20(theme){let c=theme.color;return StyleSheet.create({card:{flexDirection:"row",alignItems:"flex-start",gap:CARD_GAP,paddingVertical:CARD_PAD_Y,paddingHorizontal:CARD_PAD_X,alignSelf:"stretch",borderRadius:CARD_RADIUS5,backgroundColor:c.surface,borderWidth:1,borderColor:withAlpha(c.text.primary,RING_ALPHA2)??c.borderRingCream},icon:{flexShrink:0,width:TILE2,height:TILE2,borderRadius:TILE_RADIUS2,backgroundColor:c.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:LINE_GAP},kicker:{...face(theme,"mono"),fontSize:KICKER_SIZE3,letterSpacing:KICKER_SIZE3*KICKER_TRACKING,textTransform:"uppercase",color:c.text.muted},title:{...face(theme,"bold"),fontSize:TITLE_SIZE3,lineHeight:TITLE_LINE3,color:c.text.primary},body:{...face(theme,"regular"),fontSize:BODY_SIZE2,lineHeight:BODY_LINE,color:c.text.secondary}})}var QUICK_PROMPT_BRAND_EDGE="#10462E",VET_PREP_LABEL_WEB="Book a video visit",QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
291
303
  /* @__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}),
292
304
  /* @__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}),
293
305
  /* @__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}),
@@ -296,9 +308,9 @@ return Object.freeze(PROMPTS.flatMap(template=>{let own=template.intent==="vet_r
296
308
  /* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
297
309
  /* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
298
310
  /* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
299
- /* @__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(),styles3=useMemo(()=>makeStyles20(theme),[theme]),hostChips=useMemo(()=>resolveStarterPrompts(starterPrompts),[starterPrompts]),drawn=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,{vetPrepLabel:VET_PREP_LABEL_WEB}).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=useMemo(()=>(emptyState?.chipTints??(theme.brightness==="light"?DESIGN_CHIP_TINTS:[])).filter(t=>typeof t.tint=="string"&&t.tint.trim()!==""),[emptyState?.chipTints,theme.brightness]),chips=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=useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),hostChipThemed=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),home=useAskHome(),homeTitle=useAskHomeTitle(),titleNode=home!==null&&homeTitle!==null?/* @__PURE__ */jsx(homeTitle.Title,{text:title,style:[styles3.title,home.text(".serif",".ask-empty h2"),styles3.centerText],measureCh:homeTitle.titleCh}):/* @__PURE__ */jsx(Text,{tier:"heading",style:centered?[styles3.title,styles3.centerText]:styles3.title,accessibilityRole:"header",children:title});/* @__PURE__ */
311
+ /* @__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(),styles3=useMemo(()=>makeStyles21(theme),[theme]),hostChips=useMemo(()=>resolveStarterPrompts(starterPrompts),[starterPrompts]),drawn=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,{vetPrepLabel:VET_PREP_LABEL_WEB}).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=useMemo(()=>(emptyState?.chipTints??(theme.brightness==="light"?DESIGN_CHIP_TINTS:[])).filter(t=>typeof t.tint=="string"&&t.tint.trim()!==""),[emptyState?.chipTints,theme.brightness]),chips=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=useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),hostChipThemed=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),home=useAskHome(),homeTitle=useAskHomeTitle(),titleNode=home!==null&&homeTitle!==null?/* @__PURE__ */jsx(homeTitle.Title,{text:title,style:[styles3.title,home.text(".serif",".ask-empty h2"),styles3.centerText],measureCh:homeTitle.titleCh}):/* @__PURE__ */jsx(Text,{tier:"heading",style:centered?[styles3.title,styles3.centerText]:styles3.title,accessibilityRole:"header",children:title});/* @__PURE__ */
300
312
  return jsxs(View,{style:home!==null?styles3.homeBlock:styles3.block,children:[titleNode,
301
- /* @__PURE__ */jsx(View,{style:home!==null?[styles3.list,styles3.listCentered,home.view(".ask-chips",".ask-empty .ask-chips")]:centered?[styles3.list,styles3.listCentered]:styles3.list,accessibilityLabel:CHAT_COPY.suggestions,children:chips.map(({prompt:prompt,send:send,paint:paint,cycleDefault:cycleDefault},index)=>/* @__PURE__ */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:styles3,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:styles3,tinted:tinted,soft:soft,centered:centered}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),home=useAskHome(),edge=home!==null?[styles3.chipHome,home.view(".chip")]:centered&&soft?styles3.chipNoEdge:styles3.chipEdge,fill={backgroundColor:themed?.fill??prompt.background},paint=styles3.chipSlot===null?fill:tinted?{...styles3.chipSlot,...fill}:{...fill,...styles3.chipSlot},base2=home!==null?[styles3.chipLabel,home.text(".chip")]:centered?[styles3.chipLabel,styles3.centerText]:[styles3.chipLabel],slop=home!==null?CHIP_HOME_SLOP:CHIP_HIT_SLOP,label=themed===null?styles3.chipSlotLabel===null?base2:[...base2,styles3.chipSlotLabel]:tinted?[...base2,...styles3.chipSlotLabel===null?[]:[styles3.chipSlotLabel],{color:themed.ink}]:[...base2,{color:themed.ink},...styles3.chipSlotLabel===null?[]:[styles3.chipSlotLabel]];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:slop,style:[styles3.chip,edge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef===null?null:/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(VetVisitButtonCore,{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:[styles3.chip,edge,paint],labelStyle:label})}):/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:slop,style:[styles3.chip,edge,paint],onPress:()=>onSend(send),children:/* @__PURE__ */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 StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},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"}})}var LOOP_MS=1e3,STAGGER_MS=150,OPACITY_REST=.25,OPACITY_STATIC=.5,DOT_COUNT=3;function TypingIndicator({petName:petName=null}){let{theme:theme,styles:styles3}=useChatTheme(),reducedMotion=theme.motion.reducedMotion,line=forPet(CHAT_COPY.reading,petName),values=useRef(Array.from({length:DOT_COUNT},()=>new Animated.Value(0))).current;return useEffect(()=>{if(reducedMotion)return;let loops=values.map((value,index)=>Animated.loop(Animated.sequence([Animated.delay(index*STAGGER_MS),Animated.timing(value,{toValue:1,duration:LOOP_MS*.4,useNativeDriver:true}),Animated.timing(value,{toValue:0,duration:LOOP_MS*.6,useNativeDriver:true}),Animated.delay((DOT_COUNT-index-1)*STAGGER_MS)])));for(let loop of loops)loop.start();return()=>{for(let loop of loops)loop.stop()}},[reducedMotion,values]),/* @__PURE__ */jsx(View,{style:styles3.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:line,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:values.map((value,index)=>/* @__PURE__ */jsx(Animated.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[styles3.readingDot,reducedMotion?{opacity:OPACITY_STATIC}:{opacity:value.interpolate({inputRange:[0,1],outputRange:[OPACITY_REST,1]}),transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},index))})}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}var ASIDE_REVEAL_MARGIN=16;function useThreadFollow(rows,isStreaming,aside=null){let ref=useRef(null),following=useRef(true),wasStreaming=useRef(isStreaming),offset=useRef(0),viewport=useRef(0),content=useRef(0),tops=useRef(/* @__PURE__ */new Map),asideBottom=useRef(null),asideOwed=useRef(false),firstId=rows[0]?.id??null,previousFirst=useRef(firstId),keep=useRef(null);useEffect(()=>{let before=previousFirst.current;if(previousFirst.current=firstId,before===null||before===firstId||(keep.current=null,following.current||!rows.some(row=>row.id===before)))return;let top=tops.current.get(before);top!==void 0&&(keep.current={id:before,top:top,offset:offset.current})},[firstId,rows]);let 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=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);if(next!==null&&(offset.current=next,view.scrollTo({y:next,animated:false})),!asideOwed.current||asideBottom.current===null)return;let reveal=nextFollowOffset(asideBottom.current+ASIDE_REVEAL_MARGIN-viewport.current,offset.current,content.current-viewport.current);reveal!==null&&(offset.current=reveal,view.scrollTo({y:reveal,animated:false}))},[assistantId,userId]);useEffect(()=>{asideOwed.current=aside!==null,aside===null&&(asideBottom.current=null),follow()},[aside,follow]),useEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true,asideOwed.current=false),wasStreaming.current=isStreaming,follow()},[rows,isStreaming,follow]);let onLayout=useCallback(event=>{viewport.current=event.nativeEvent.layout.height,follow()},[follow]),onContentSizeChange=useCallback((_width,height)=>{content.current=height,viewport.current>0&&(offset.current=Math.min(offset.current,Math.max(0,height-viewport.current))),follow()},[follow]),onScroll=useCallback(event=>{offset.current=event.nativeEvent.contentOffset.y},[]),onScrollBeginDrag=useCallback(()=>{following.current=false,asideOwed.current=false},[]),onScrollEnd=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=useCallback(id=>event=>{let y=event.nativeEvent.layout.y;tops.current.set(id,y);let held=keep.current;if(held!==null&&held.id===id&&y!==held.top){keep.current=null;let next=Math.max(0,held.offset+y-held.top);offset.current=next,ref.current?.scrollTo({y:next,animated:false})}(id===assistantId||id===userId)&&follow()},[assistantId,userId,follow]),asideLayout=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;asideBottom.current=y+height,follow()},[follow]);return{ref:ref,onLayout:onLayout,onContentSizeChange:onContentSizeChange,onScroll:onScroll,onScrollBeginDrag:onScrollBeginDrag,onScrollEnd:onScrollEnd,rowLayout:rowLayout,asideLayout:asideLayout}}function renderView(view,chat,extras){switch(view){case"loading":return extras.renderPending?/* @__PURE__ */jsx(HostRender,{render:extras.renderPending,fallback:/* @__PURE__ */jsx(LoadingState,{})}):/* @__PURE__ */jsx(LoadingState,{});case"empty":/* @__PURE__ */
313
+ /* @__PURE__ */jsx(View,{style:home!==null?[styles3.list,styles3.listCentered,home.view(".ask-chips",".ask-empty .ask-chips")]:centered?[styles3.list,styles3.listCentered]:styles3.list,accessibilityLabel:CHAT_COPY.suggestions,children:chips.map(({prompt:prompt,send:send,paint:paint,cycleDefault:cycleDefault},index)=>/* @__PURE__ */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:styles3,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:styles3,tinted:tinted,soft:soft,centered:centered}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),home=useAskHome(),edge=home!==null?[styles3.chipHome,home.view(".chip")]:centered&&soft?styles3.chipNoEdge:styles3.chipEdge,fill={backgroundColor:themed?.fill??prompt.background},paint=styles3.chipSlot===null?fill:tinted?{...styles3.chipSlot,...fill}:{...fill,...styles3.chipSlot},base2=home!==null?[styles3.chipLabel,home.text(".chip")]:centered?[styles3.chipLabel,styles3.centerText]:[styles3.chipLabel],slop=home!==null?CHIP_HOME_SLOP:CHIP_HIT_SLOP,label=themed===null?styles3.chipSlotLabel===null?base2:[...base2,styles3.chipSlotLabel]:tinted?[...base2,...styles3.chipSlotLabel===null?[]:[styles3.chipSlotLabel],{color:themed.ink}]:[...base2,{color:themed.ink},...styles3.chipSlotLabel===null?[]:[styles3.chipSlotLabel]];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:slop,style:[styles3.chip,edge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef===null?null:/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(VetVisitButtonCore,{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:[styles3.chip,edge,paint],labelStyle:label})}):/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:slop,style:[styles3.chip,edge,paint],onPress:()=>onSend(send),children:/* @__PURE__ */jsx(Text,{tier:"compact",style:label,children:prompt.label})})})}function makeStyles21(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 StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},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"}})}var LOOP_MS=1e3,STAGGER_MS=150,OPACITY_REST=.25,OPACITY_STATIC=.5,DOT_COUNT=3;function TypingIndicator({petName:petName=null,inline:inline=false}){let{theme:theme,styles:styles3}=useChatTheme(),reducedMotion=theme.motion.reducedMotion,line=forPet(CHAT_COPY.reading,petName),values=useRef(Array.from({length:DOT_COUNT},()=>new Animated.Value(0))).current;return useEffect(()=>{if(reducedMotion)return;let loops=values.map((value,index)=>Animated.loop(Animated.sequence([Animated.delay(index*STAGGER_MS),Animated.timing(value,{toValue:1,duration:LOOP_MS*.4,useNativeDriver:true}),Animated.timing(value,{toValue:0,duration:LOOP_MS*.6,useNativeDriver:true}),Animated.delay((DOT_COUNT-index-1)*STAGGER_MS)])));for(let loop of loops)loop.start();return()=>{for(let loop of loops)loop.stop()}},[reducedMotion,values]),/* @__PURE__ */jsx(View,{style:inline?styles3.readingInline:styles3.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:line,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:values.map((value,index)=>/* @__PURE__ */jsx(Animated.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[inline?styles3.readingDotInline:styles3.readingDot,reducedMotion?{opacity:OPACITY_STATIC}:{opacity:value.interpolate({inputRange:[0,1],outputRange:[OPACITY_REST,1]}),transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},index))})}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}var ASIDE_REVEAL_MARGIN=16;function useThreadFollow(rows,isStreaming,aside=null){let ref=useRef(null),following=useRef(true),wasStreaming=useRef(isStreaming),offset=useRef(0),viewport=useRef(0),content=useRef(0),tops=useRef(/* @__PURE__ */new Map),asideBottom=useRef(null),asideOwed=useRef(false),firstId=rows[0]?.id??null,previousFirst=useRef(firstId),keep=useRef(null);useEffect(()=>{let before=previousFirst.current;if(previousFirst.current=firstId,before===null||before===firstId||(keep.current=null,following.current||!rows.some(row=>row.id===before)))return;let top=tops.current.get(before);top!==void 0&&(keep.current={id:before,top:top,offset:offset.current})},[firstId,rows]);let 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=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);if(next!==null&&(offset.current=next,view.scrollTo({y:next,animated:false})),!asideOwed.current||asideBottom.current===null)return;let reveal=nextFollowOffset(asideBottom.current+ASIDE_REVEAL_MARGIN-viewport.current,offset.current,content.current-viewport.current);reveal!==null&&(offset.current=reveal,view.scrollTo({y:reveal,animated:false}))},[assistantId,userId]);useEffect(()=>{asideOwed.current=aside!==null,aside===null&&(asideBottom.current=null),follow()},[aside,follow]),useEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true,asideOwed.current=false),wasStreaming.current=isStreaming,follow()},[rows,isStreaming,follow]);let onLayout=useCallback(event=>{viewport.current=event.nativeEvent.layout.height,follow()},[follow]),onContentSizeChange=useCallback((_width,height)=>{content.current=height,viewport.current>0&&(offset.current=Math.min(offset.current,Math.max(0,height-viewport.current))),follow()},[follow]),onScroll=useCallback(event=>{offset.current=event.nativeEvent.contentOffset.y},[]),onScrollBeginDrag=useCallback(()=>{following.current=false,asideOwed.current=false},[]),onScrollEnd=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=useCallback(id=>event=>{let y=event.nativeEvent.layout.y;tops.current.set(id,y);let held=keep.current;if(held!==null&&held.id===id&&y!==held.top){keep.current=null;let next=Math.max(0,held.offset+y-held.top);offset.current=next,ref.current?.scrollTo({y:next,animated:false})}(id===assistantId||id===userId)&&follow()},[assistantId,userId,follow]),asideLayout=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;asideBottom.current=y+height,follow()},[follow]);return{ref:ref,onLayout:onLayout,onContentSizeChange:onContentSizeChange,onScroll:onScroll,onScrollBeginDrag:onScrollBeginDrag,onScrollEnd:onScrollEnd,rowLayout:rowLayout,asideLayout:asideLayout}}function renderView(view,chat,extras){switch(view){case"loading":return extras.renderPending?/* @__PURE__ */jsx(HostRender,{render:extras.renderPending,fallback:/* @__PURE__ */jsx(LoadingState,{})}):/* @__PURE__ */jsx(LoadingState,{});case"empty":/* @__PURE__ */
302
314
  return 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,foot:extras.threadFoot??null,renderEmptyHeader:extras.renderEmptyHeader});case"error":/* @__PURE__ */
303
315
  return jsx(ErrorState,{error:chat.error,onRetry:chat.retryLast,onAddPet:extras.onAddPet});case"populated":/* @__PURE__ */
304
316
  return 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,threadAside:extras.threadAside,threadAsideKey:extras.threadAsideKey??null,threadFoot:extras.threadFoot??null,onSelectPrompt:extras.onSelectPrompt,isStreaming:chat.isStreaming,onAnswerCheckin:chat.petRef?chat.answerCheckin:null,onCopy:extras.onCopy,sentimentByMessage:chat.sentimentByMessage,onSentiment:extras.onSentiment,feedbackNote:extras.feedbackNote,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,followUpLabel:extras.followUpPolicy?.label,openingCard:extras.openingCard,earlier:chat.historyCursor?{loading:chat.isLoadingHistory,load:chat.loadOlderMessages}:null});default:return assertNever(view)}}function LoadingState(){let{theme:theme,styles:styles3}=useChatTheme(),[visible,setVisible]=useState(false);return useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsx(View,{style:styles3.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:CHAT_COPY.loading,children:visible?/* @__PURE__ */jsx(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,foot:foot,renderEmptyHeader:renderEmptyHeader}){let{styles:styles3}=useChatTheme(),home=useAskHome(),header=renderEmptyHeader===void 0?null:/* @__PURE__ */jsx(View,{testID:"everfur-empty-header",children:/* @__PURE__ */jsx(HostRender,{render:()=>renderEmptyHeader({ask:onSelectPrompt}),fallback:null})});if(home!==null){let{minHeight:minHeight,...box2}=home.view(".ask-empty");/* @__PURE__ */
@@ -313,29 +325,29 @@ return jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsxs(PressScale,{on
313
325
  /* @__PURE__ */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:styles3}=useChatTheme(),addPet=isPetNotRegistered(error)?guardHost(onAddPet):void 0;/* @__PURE__ */
314
326
  return jsxs(View,{style:styles3.centered,accessible:true,accessibilityRole:"alert",children:[
315
327
  /* @__PURE__ */jsx(Text,{style:styles3.errorText,children:error.displayMessage}),addPet!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:addPet,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addPet,style:styles3.retryButton,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.retryLabel,children:CHAT_COPY.addPet})}):null,error.retryable?/* @__PURE__ */jsx(Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,style:styles3.retryButton,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.retryLabel,children:CHAT_COPY.retry})}):null]})}function PopulatedState({messages:messages,prompts:prompts,onSelectPrompt:onSelectPrompt,isStreaming:isStreaming,onAnswerCheckin:onAnswerCheckin,onCopy:onCopy,sentimentByMessage:sentimentByMessage,onSentiment:onSentiment,feedbackNote:feedbackNote,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,threadAside:threadAside,threadAsideKey:threadAsideKey,threadFoot:threadFoot,followUpLabel:followUpLabel,openingCard:openingCard,earlier:earlier}){let{styles:styles3}=useChatTheme(),motion=useChatMotion();useAnimateLayoutOn(messages.length,motion);let liveCheckins=useMemo(()=>liveCheckinIds(placeCheckins(messages)),[messages]),awaiting=awaitingAssistant(messages,isStreaming),last=messages[messages.length-1],aside=threadAside??null,follow=useThreadFollow(messages,isStreaming,aside===null?null:threadAsideKey??"shown"),isEntering=useEnteringRows(messages),first=messages[0],openingId=openingCard!==void 0&&first!==void 0&&first.role==="user"&&first.text.trim()===openingCard.prompt?first.id:null;/* @__PURE__ */
316
- return jsxs(ScrollView,{ref:follow.ref,style:styles3.list,contentContainerStyle:styles3.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,earlier!==null?/* @__PURE__ */jsx(Pressable,{onPress:()=>{earlier.load()},disabled:earlier.loading,accessibilityRole:"button",accessibilityLabel:earlier.loading?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier,accessibilityState:{disabled:earlier.loading,busy:earlier.loading},hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.earlierButton,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.earlierLabel,children:earlier.loading?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier})}):null,messages.map(message=>message.id===openingId&&openingCard!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:openingCard.card,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */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,note:message.responseId!==void 0&&feedbackNote?.responseId===String(message.responseId)?feedbackNote.kind:null,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id),answerCards:answerCards,messages:messages},message.id)),reconnecting?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,answerCards!==null?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:followUpLabel,actions:actions,options:answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:followUpLabel}),aside!==null?/* @__PURE__ */jsx(View,{onLayout:follow.asideLayout,children:aside}):null,threadFoot]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles3}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
328
+ return jsxs(ScrollView,{ref:follow.ref,style:styles3.list,contentContainerStyle:answerCards!==null?styles3.listContentCards:styles3.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,earlier!==null?/* @__PURE__ */jsx(Pressable,{onPress:()=>{earlier.load()},disabled:earlier.loading,accessibilityRole:"button",accessibilityLabel:earlier.loading?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier,accessibilityState:{disabled:earlier.loading,busy:earlier.loading},hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.earlierButton,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.earlierLabel,children:earlier.loading?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier})}):null,messages.map(message=>message.id===openingId&&openingCard!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:openingCard.card,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */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,note:message.responseId!==void 0&&feedbackNote?.responseId===String(message.responseId)?feedbackNote.kind:null,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id),answerCards:answerCards,messages:messages},message.id)),reconnecting?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName,inline:answerCards!==null}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,answerCards!==null?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:followUpLabel,actions:actions,options:answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:followUpLabel}),aside!==null?/* @__PURE__ */jsx(View,{onLayout:follow.asideLayout,children:aside}):null,threadFoot]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles3}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
317
329
  return jsxs(View,{style:[styles3.turnNotice,error?styles3.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
318
330
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.turnNoticeTitle,error?styles3.turnNoticeTitleError:null],children:notice.title}),
319
331
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.turnNoticeBody,children:notice.body}),
320
- /* @__PURE__ */jsx(Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.turnNoticeAction,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),NO_ACTIONS=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,note:note,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering,answerCards:answerCards,messages:messages}){let{theme:theme,styles:styles3}=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",messageLinks=useMessageLinks(),links=isAssistant&&!revealing?messageLinks:void 0,linked=links!==void 0&&hasMessageLink(message.text,links),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=useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true,senderLine=isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles3}):namesAssistant?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;return isAssistant&&answerCards!==null?/* @__PURE__ */jsx(Animated.View,{style:[styles3.rowBlock,enter],onLayout:onLayout,accessibilityLabel:`${sender}: ${message.text}`,children:/* @__PURE__ */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__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:withThumbs&&message.responseId!==void 0?rate:void 0,note:note})})}):/* @__PURE__ */jsxs(View,{style:[styles3.rowBlock,isUser?styles3.rowBlockUser:styles3.rowBlockAssistant],onLayout:onLayout,children:[
321
- /* @__PURE__ */jsx(View,{style:[styles3.row,isUser?styles3.rowUser:styles3.rowAssistant],accessible:!linked,accessibilityRole:linked?void 0:"text",accessibilityLabel:linked?void 0:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxs(Animated.View,{style:[styles3.bubble,isUser?styles3.bubbleSideUser:null,enter],children:[senderLine,isVet?/* @__PURE__ */jsxs(View,{style:styles3.vetHeader,children:[
332
+ /* @__PURE__ */jsx(Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.turnNoticeAction,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),NO_ACTIONS=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,note:note,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering,answerCards:answerCards,messages:messages}){let{theme:theme,styles:styles3}=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",messageLinks=useMessageLinks(),links=isAssistant&&!revealing?messageLinks:void 0,linked=links!==void 0&&hasMessageLink(message.text,links),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=useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true,senderLine=isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles3}):namesAssistant?answerCards!==null?/* @__PURE__ */jsx(CardsByline,{label:CHAT_COPY.assistantName}):/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null,cards=answerCards!==null;return isAssistant&&answerCards!==null?/* @__PURE__ */jsx(Animated.View,{style:[styles3.rowBlock,enter],onLayout:onLayout,accessibilityLabel:`${sender}: ${message.text}`,children:/* @__PURE__ */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__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:withThumbs&&message.responseId!==void 0?rate:void 0,note:note})})}):/* @__PURE__ */jsxs(View,{style:[styles3.rowBlock,isUser?styles3.rowBlockUser:styles3.rowBlockAssistant],onLayout:onLayout,children:[
333
+ /* @__PURE__ */jsx(View,{style:[styles3.row,isUser?styles3.rowUser:styles3.rowAssistant],accessible:!linked,accessibilityRole:linked?void 0:"text",accessibilityLabel:linked?void 0:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxs(Animated.View,{style:[styles3.bubble,cards?styles3.bubbleCards:null,isUser?styles3.bubbleSideUser:null,enter],children:[senderLine,isVet?/* @__PURE__ */jsxs(View,{style:styles3.vetHeader,children:[
322
334
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.vetSender,children:sender}),vetTime!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.vetTime,children:vetTime}):null]}):null,
323
- /* @__PURE__ */jsxs(View,{style:[isUser?styles3.bubbleUser:isVet?styles3.bubbleVet:styles3.bubbleAssistant,message.pending?styles3.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
324
- /* @__PURE__ */jsx(Text,{style:isUser?styles3.bubbleTextUser:isVet?styles3.bubbleTextVet:styles3.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles3.bubbleBold,italic:styles3.bubbleItalic,code:styles3.bubbleCode},links):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled&&!(isUser&&answerCards!==null)?/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,note:note}):null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false){let[ask,setAsk]=useState(null);if(!enabled)return NOTHING;let runner=/* @__PURE__ */jsx(AskRunner,{ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chip=headerEntry&&ask!==null&&ask.canOpen?{label:texting.textingAskLines(ask).accept,onOpen:ask.open}:null;if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=texting.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(texting.ChatTextingAskComposer,{ask:ask}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function AskRunner({ready:ready,onAsk:onAsk,entry:entry}){let{userRef:userRef}=useEverfurContext(),granted=useTextingGranted(),wanted=userRef!==null&&granted;return useEffect(()=>{wanted||onAsk(null)},[wanted,onAsk]),wanted?/* @__PURE__ */jsx(texting.ChatTextingAskController,{enabled:true,ready:ready,onAsk:onAsk,entry:entry}):null}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles3}=useChatTheme(),named=!theme.meta.hidePoweredBy,sender=named?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,senderLine=theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:named,styles:styles3}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;/* @__PURE__ */
335
+ /* @__PURE__ */jsxs(View,{style:[isUser?styles3.bubbleUser:isVet?styles3.bubbleVet:styles3.bubbleAssistant,isUser&&cards?styles3.bubbleUserCards:null,message.pending?styles3.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
336
+ /* @__PURE__ */jsx(Text,{style:isUser?cards?[styles3.bubbleTextUser,styles3.bubbleTextUserCards]:styles3.bubbleTextUser:isVet?styles3.bubbleTextVet:styles3.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles3.bubbleBold,italic:styles3.bubbleItalic,code:styles3.bubbleCode},links):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled&&!(isUser&&answerCards!==null)?/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,note:note}):null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false){let[ask,setAsk]=useState(null);if(!enabled)return NOTHING;let runner=/* @__PURE__ */jsx(AskRunner,{ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chip=headerEntry&&ask!==null&&ask.canOpen?{label:texting.textingAskLines(ask).accept,onOpen:ask.open}:null;if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=texting.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(texting.ChatTextingAskComposer,{ask:ask}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function AskRunner({ready:ready,onAsk:onAsk,entry:entry}){let{userRef:userRef}=useEverfurContext(),granted=useTextingGranted(),wanted=userRef!==null&&granted;return useEffect(()=>{wanted||onAsk(null)},[wanted,onAsk]),wanted?/* @__PURE__ */jsx(texting.ChatTextingAskController,{enabled:true,ready:ready,onAsk:onAsk,entry:entry}):null}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles3}=useChatTheme(),named=!theme.meta.hidePoweredBy,sender=named?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,senderLine=theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:named,styles:styles3}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;/* @__PURE__ */
325
337
  return jsxs(View,{style:[styles3.rowBlock,styles3.rowBlockAssistant],testID:`everfur-texting-ask-${stage}`,children:[
326
338
  /* @__PURE__ */jsx(View,{style:[styles3.row,styles3.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${text3}`,children:/* @__PURE__ */jsxs(View,{style:styles3.bubble,children:[senderLine,
327
339
  /* @__PURE__ */jsx(View,{style:styles3.bubbleAssistant,children:/* @__PURE__ */jsx(Text,{style:styles3.bubbleTextAssistant,children:text3})})]})}),stage==="offered"?/* @__PURE__ */jsx(View,{style:styles3.askChips,children:[{label:accept,onPress:onAccept,testID:"everfur-texting-ask-accept"},{label:dismiss,onPress:onDismiss,testID:"everfur-texting-ask-dismiss"}].map(answer=>/* @__PURE__ */jsx(PressScale,{onPress:answer.onPress,accessibilityRole:"button",accessibilityLabel:answer.label,style:styles3.askChip,testID:answer.testID,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.askChipText,children:answer.label})},answer.testID))}):null]})}function EverfurChatCore(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
328
340
  return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(MessageLinksScope,{linkHosts:props.linkHosts,onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatBody,{...props})})})}function useOptionalEverfurContext(){try{return useEverfurContext()}catch{return null}}function hostPresentation(props){return definedPresentation({...props.presentation,chatComposerMic:props.presentation?.chatComposerMic??(props.dictation===void 0?void 0:props.dictation!==false),chatComposerUpload:props.presentation?.chatComposerUpload??(props.attachments===void 0?void 0:true)})}function ChatBody(props){let context=useOptionalEverfurContext();return context===null?/* @__PURE__ */jsx(ChatBodyAlone,{...props}):/* @__PURE__ */jsx(ChatBodyInProvider,{...props,activePet:context.activePet,telemetry:context.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(props){let client=hostPresentation(props),key=JSON.stringify(client),planPetRef=props.petRef??null,settings=useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:client}),isLocked:()=>false,planPage:null,planPetRef:planPetRef,inProvider:false,telemetry:null}),[key,planPetRef]);/* @__PURE__ */
329
341
  return jsx(ChatSurface,{...props,settings:settings})}function ChatBodyInProvider({activePet:activePet,telemetry:telemetry,...props}){let{presentation:presentation,isLocked:isLocked}=useEverfurPresentationState(hostPresentation(props)),planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&props.topCard===void 0&&planEnabled,planPetRef=props.petRef??activePet??null,plan=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),planPage=wantsPlan&&plan.phase==="ready"?plan.page:null,settings=useMemo(()=>({presentation:presentation,isLocked:isLocked,planPage:planPage,planPetRef:planPetRef,inProvider:true,telemetry:telemetry}),[presentation,isLocked,planPage,planPetRef,telemetry]);/* @__PURE__ */
330
- return 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,handoffToken:handoffToken,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,openUnreadOnRefresh:openUnreadOnRefresh,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,header:header=true,textingEntry:textingEntry=true,renderEmptyHeader:renderEmptyHeader,followUpPolicy:hostFollowUpPolicy,initialAskCard:initialAskCard}){let{presentation:presentation,isLocked:isLocked,planPage:planPage,planPetRef:planPetRef}=settings,{theme:theme,styles:styles3}=useChatTheme(),askHomeFactory=useAskHomeFactory(),askHome=useMemo(()=>askHomeFactory===null?null:askHomeFactory(theme),[askHomeFactory,theme]),hostPoweredBy=useHostPoweredBy(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat,"web"),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=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=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion);let providerContext=useOptionalEverfurContext(),handoffTarget=useChatHandoffTarget(handoffToken,providerContext);useCheckinTarget(chat.openCheckin,checkinTarget??handoffTarget,{petRef:chat.petRef,pinned:petRef!==void 0,ready:!chat.isBootstrapping,selectPet:next=>{pets.setActivePet(next),callHost(onPetChange,next)}}),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),openingCard=useMemo(()=>initialAskCard!==void 0&&askPrompt!==null?{card:initialAskCard,prompt:askPrompt}:void 0,[initialAskCard,askPrompt]),lifecyclePort=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refreshesBlankThread:openUnreadOnRefresh===true,refresh:openUnreadOnRefresh===true?()=>chat.refreshActiveThread?.(OPEN_UNREAD_HEAD)??Promise.resolve():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]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[feedbackNote,setFeedbackNote]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showNote=useCallback((responseId,kind)=>{setFeedbackNote({responseId:String(responseId),kind:kind}),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=kind==="thanks"?setTimeout(()=>{setFeedbackNote(null),thanksTimer.current=null},THANKS_VISIBLE_MS):null},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];setFeedbackNote(note=>note?.responseId===String(responseId)?null:note),chat.feedback(responseId,sentiment).then(result=>{result.ok||showNote(responseId,"failed")}),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat,showNote]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(reason==null&&notes===null?{ok:true}:await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showNote(feedbackTarget,"thanks"),true),[chat,feedbackTarget,showNote]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=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(),openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:openPlan}):void 0,[hostTopCard,planPage,openPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=useState(true),onCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=useMemo(()=>followUpPolicyFor(hostFollowUpPolicy,presentation,isLocked("chatFollowUpCount")),[hostFollowUpPolicy,presentation,isLocked]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,barNode=historyBar!==void 0?/* @__PURE__ */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__ */jsxs(Fragment,{children:[
331
- /* @__PURE__ */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;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,petBreed:shownPet?.breed??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",mood:composerMood(view,urgency.source?.level??null),dictation:presentation.chatComposerMic,telemetry:settings.telemetry},textingAsk=useChatTextingAsk(presentation.chatTextingAsk&&settings.inProvider,chat,textingEntry),uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general",footnoteInThread=presentation.safetyDisclaimerPlacement==="answer_footer"&&(view==="empty"||view==="populated"),footnote=/* @__PURE__ */jsx(Text,{tier:"compact",style:footnoteInThread?styles3.footnoteInThread:styles3.footnote,accessibilityRole:"text",children:forPet(CHAT_COPY.footnoteWeb,shownPet?.name)});
342
+ return 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,handoffToken:handoffToken,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,openUnreadOnRefresh:openUnreadOnRefresh,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,header:header=true,textingEntry:textingEntry=true,renderEmptyHeader:renderEmptyHeader,followUpPolicy:hostFollowUpPolicy,initialAskCard:initialAskCard}){let{presentation:presentation,isLocked:isLocked,planPage:planPage,planPetRef:planPetRef}=settings,{theme:theme,styles:styles3}=useChatTheme(),askHomeFactory=useAskHomeFactory()??(presentation.chatAnswerStyle==="cards"?createAskHome:null),askHome=useMemo(()=>askHomeFactory===null?null:askHomeFactory(theme),[askHomeFactory,theme]),hostPoweredBy=useHostPoweredBy(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat,"web"),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=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=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion);let providerContext=useOptionalEverfurContext(),handoffTarget=useChatHandoffTarget(handoffToken,providerContext);useCheckinTarget(chat.openCheckin,checkinTarget??handoffTarget,{petRef:chat.petRef,pinned:petRef!==void 0,ready:!chat.isBootstrapping,selectPet:next=>{pets.setActivePet(next),callHost(onPetChange,next)}}),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),openingCard=useMemo(()=>initialAskCard!==void 0&&askPrompt!==null?{card:initialAskCard,prompt:askPrompt}:void 0,[initialAskCard,askPrompt]),lifecyclePort=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refreshesBlankThread:openUnreadOnRefresh===true,refresh:openUnreadOnRefresh===true?()=>chat.refreshActiveThread?.(OPEN_UNREAD_HEAD)??Promise.resolve():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]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[feedbackNote,setFeedbackNote]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showNote=useCallback((responseId,kind)=>{setFeedbackNote({responseId:String(responseId),kind:kind}),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=kind==="thanks"?setTimeout(()=>{setFeedbackNote(null),thanksTimer.current=null},THANKS_VISIBLE_MS):null},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];setFeedbackNote(note=>note?.responseId===String(responseId)?null:note),chat.feedback(responseId,sentiment).then(result=>{result.ok||showNote(responseId,"failed")}),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat,showNote]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(reason==null&&notes===null?{ok:true}:await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showNote(feedbackTarget,"thanks"),true),[chat,feedbackTarget,showNote]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=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(),openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:openPlan}):void 0,[hostTopCard,planPage,openPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=useState(true),onCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=useMemo(()=>followUpPolicyFor(hostFollowUpPolicy,presentation,isLocked("chatFollowUpCount")),[hostFollowUpPolicy,presentation,isLocked]),cardsStyle=presentation.chatAnswerStyle==="cards",servedStarters=useMemo(()=>cardsStyle&&chat.messages.length===0?servedStarterPrompts(chat.suggestedPrompts):void 0,[cardsStyle,chat.messages.length,chat.suggestedPrompts]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,bar=historyBar??(header?void 0:DEFAULT_HISTORY_BAR),barNode=bar!==void 0?/* @__PURE__ */jsx(HistoryBar,{bar:bar,history:history,empty:threadEmpty,unread:historyUnread,extra:pill}):null,barInThread=presentation.chatHistoryBar==="scroll"&&(view==="empty"||view==="populated"),cardNode=card===void 0?null:/* @__PURE__ */jsxs(Fragment,{children:[
343
+ /* @__PURE__ */jsx(TopCard,{card:card,open:cardOpen,onOpenChange:setCardOpen,ask:onCardAsk}),bar===void 0?pill:null]}),barShown=bar!==void 0,historyLoad=history.load,historyOpen=history.open;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,petBreed:shownPet?.breed??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",mood:composerMood(view,urgency.source?.level??null),dictation:presentation.chatComposerMic,telemetry:settings.telemetry},textingAsk=useChatTextingAsk(presentation.chatTextingAsk&&settings.inProvider,chat,textingEntry),uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general",footnoteInThread=presentation.safetyDisclaimerPlacement==="answer_footer"&&(view==="empty"||view==="populated"),footnote=/* @__PURE__ */jsx(Text,{tier:"compact",style:footnoteInThread?styles3.footnoteInThread:styles3.footnote,accessibilityRole:"text",children:forPet(CHAT_COPY.footnoteWeb,shownPet?.name)});
332
344
  /* @__PURE__ */
333
345
  return jsx(AskHomeContext.Provider,{value:askHome,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{style:[styles3.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
334
346
  /* @__PURE__ */jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),header?/* @__PURE__ */jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onNewChat:history.newConversation,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet,textingEntry:textingAsk.headerEntry}):null,pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef??null,pet:pet,onRegistered:pets.refresh}):null,!header&&textingAsk.headerEntry!==null?/* @__PURE__ */jsx(TextingEntryRow,{entry:textingAsk.headerEntry,place:"thread"}):null,barInThread?null:barNode,bannerHidden?null:/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
335
- /* @__PURE__ */jsx(View,{style:styles3.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,feedbackNote:feedbackNote,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,threadFoot:footnoteInThread?footnote:null,threadAside:textingAsk.line,threadAsideKey:textingAsk.stage,renderEmptyHeader:renderEmptyHeader,openingCard:openingCard})}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsx(View,{style:styles3.composerOuter,children:/* @__PURE__ */jsx(View,{style:styles3.askEntry,children:textingAsk.entry})}):uploadOn&&attachments!==void 0?/* @__PURE__ */jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsx(Composer,{...composerProps,attachments:null}),footnoteInThread?null:footnote,theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:historySheet}):/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history}),
347
+ /* @__PURE__ */jsx(View,{style:styles3.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,feedbackNote:feedbackNote,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation,threadTop:barInThread?barNode:null,topCard:cardNode,starterPrompts:starterPrompts??servedStarters,emptyState:emptyState,emptyCentered:presentation.chatAnswerStyle==="cards",followUpPolicy:followUpPolicy,answerCards:presentation.chatAnswerStyle==="cards"?answerCards??NO_ANSWER_CARDS:null,threadFoot:footnoteInThread?footnote:null,threadAside:textingAsk.line,threadAsideKey:textingAsk.stage,renderEmptyHeader:renderEmptyHeader,openingCard:openingCard})}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsx(View,{style:styles3.composerOuter,children:/* @__PURE__ */jsx(View,{style:styles3.askEntry,children:textingAsk.entry})}):uploadOn&&attachments!==void 0?/* @__PURE__ */jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsx(Composer,{...composerProps,attachments:null}),footnoteInThread?null:footnote,theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:historySheet}):/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history}),
336
348
  /* @__PURE__ */jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
337
349
  /* @__PURE__ */jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
338
350
  /* @__PURE__ */jsx(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:petRef,pet:pet,onRegistered:onRegistered}){let{styles:styles3}=useChatTheme(),setup=useChatPetRegistration(petRef,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs(View,{style:styles3.setupNotice,accessible:true,accessibilityRole:"alert",children:[
339
351
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.setupNoticeText,children:setup.error.displayMessage}),
340
- /* @__PURE__ */jsx(Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.setupNoticeAction,children:CHAT_COPY.retry})})]})}var NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function EverfurChat(props){/* @__PURE__ */
352
+ /* @__PURE__ */jsx(Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.setupNoticeAction,children:CHAT_COPY.retry})})]})}var NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({}),SERVED_STARTERS_MAX=3;function servedStarterPrompts(prompts){let out=[];for(let prompt of prompts){let label=prompt.trim();if(label.length>0&&!out.some(p=>p.label===label)&&out.push(/* @__PURE__ */Object.freeze({label:label})),out.length===SERVED_STARTERS_MAX)break}return out.length>0?/* @__PURE__ */Object.freeze(out):void 0}var DEFAULT_HISTORY_BAR=/* @__PURE__ */Object.freeze({chats:HISTORY_COPY.heading,newChat:HISTORY_COPY.newChat});function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function EverfurChat(props){/* @__PURE__ */
341
353
  return jsx(EverfurChatCore,{...props})}var NONE3=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function useUnreadState(petOption,lifecycle){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),store=runtime.unread??null,petRef=petOption===void 0?activePet:petOption,subscribe2=useCallback(listener=>store===null?NO_SUBSCRIPTION():store.subscribe(listener),[store]),read=useCallback(()=>store===null||userRef===null?NONE3:store.get(petRef),[store,userRef,petRef]),unread=useSyncExternalStore(subscribe2,read,read),refresh=useCallback(()=>store===null||userRef===null?Promise.resolve():store.refresh(petRef),[store,userRef,petRef]);return useEffect(()=>{refresh()},[refresh,scopeEpoch]),useChatLifecycle(lifecycle,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:refresh}),useMemo(()=>({...unread,refresh:refresh}),[unread,refresh])}function useEverfurUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);return useUnreadState(options.petRef,port)}export{EverfurChat,EverfurPoweredBy,chatHandoffTokenFromUrl,createAppStateLifecycle,createRnChatAttachmentTransport,registerEverfurDictation,useChatAttachments,useEverfurChat,useEverfurPets,useEverfurUnread,useHostPoweredBy};