@everfur/sdk 0.16.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +3 -1
  3. package/chat/lite/package.json +8 -0
  4. package/dist/Chat.d-CzI2228d.d.ts +11 -0
  5. package/dist/Chat.d-D3ScVQ22.d.cts +11 -0
  6. package/dist/{DepthViews.d-DapfRz1S.d.cts → DepthViews.d-6U4QqaW3.d.cts} +1 -1
  7. package/dist/{DepthViews.d-C4TIZDfz.d.cts → DepthViews.d-BLx_ZTwa.d.cts} +1 -1
  8. package/dist/{DepthViews.d-CNjaHLAS.d.ts → DepthViews.d-Cwbel5o4.d.ts} +1 -1
  9. package/dist/{DepthViews.d-A7S-XYiI.d.ts → DepthViews.d-DVIydPLt.d.ts} +1 -1
  10. package/dist/{RecordsPage.d-6WMbieaV.d.ts → RecordsPage.d-Bwalb0wU.d.ts} +1 -1
  11. package/dist/{RecordsPage.d-B2gLf8RH.d.cts → RecordsPage.d-Do7T8Fns.d.cts} +1 -1
  12. package/dist/animations/index.d.cts +3 -3
  13. package/dist/animations/index.d.ts +3 -3
  14. package/dist/{appStateLifecycle.d-B7L427MF.d.ts → appStateLifecycle.d-Bd-rNy6K.d.ts} +6 -11
  15. package/dist/{appStateLifecycle.d-CWedOJq4.d.cts → appStateLifecycle.d-_mh4CEAq.d.cts} +6 -11
  16. package/dist/attachmentTransport.d-Syrvv5zH.d.ts +41 -0
  17. package/dist/attachmentTransport.d-r1XCCdUB.d.cts +41 -0
  18. package/dist/{attachments.d-CB0R1_vK.d.ts → attachments.d-BiBGBE4o.d.ts} +5 -5
  19. package/dist/{attachments.d-CPgp4_W-.d.ts → attachments.d-CyB8hzDo.d.ts} +2 -2
  20. package/dist/{attachments.d-BARh-PrJ.d.cts → attachments.d-GlO5UP7H.d.cts} +5 -5
  21. package/dist/{attachments.d-DeoaCEMD.d.cts → attachments.d-Y-qvSHVU.d.cts} +2 -2
  22. package/dist/{bookingCopy.d-CVmpuk9C.d.cts → bookingCopy.d-BIaCiRuW.d.cts} +2 -2
  23. package/dist/{bookingCopy.d-BakTjvWw.d.ts → bookingCopy.d-DgWvNKD5.d.ts} +2 -2
  24. package/dist/{casesRepository.d-CuokarTU.d.ts → casesRepository.d-BW8DTYeN.d.ts} +1 -1
  25. package/dist/{casesRepository.d-DKRLtYb8.d.cts → casesRepository.d-_0AO2YrL.d.cts} +1 -1
  26. package/dist/chat/index.cjs +32 -31
  27. package/dist/chat/index.d.cts +16 -51
  28. package/dist/chat/index.d.ts +16 -51
  29. package/dist/chat/index.js +32 -31
  30. package/dist/chat/lite/index.cjs +430 -0
  31. package/dist/chat/lite/index.d.cts +35 -0
  32. package/dist/chat/lite/index.d.ts +35 -0
  33. package/dist/chat/lite/index.js +430 -0
  34. package/dist/client/index.cjs +4 -4
  35. package/dist/client/index.d.cts +6 -6
  36. package/dist/client/index.d.ts +6 -6
  37. package/dist/client/index.js +4 -4
  38. package/dist/{clinicBatch.d-BP_Rpvcy.d.ts → clinicBatch.d-BXwATY3-.d.ts} +2 -2
  39. package/dist/{clinicBatch.d-BTDdhMQ2.d.cts → clinicBatch.d-BcuSaOkv.d.cts} +2 -2
  40. package/dist/{config.d-84fNJFv9.d.cts → config.d-D1xcxALX.d.cts} +1 -1
  41. package/dist/{config.d-B4-Mrwq2.d.ts → config.d-jTVsAeky.d.ts} +1 -1
  42. package/dist/consent/index.d.cts +5 -5
  43. package/dist/consent/index.d.ts +5 -5
  44. package/dist/{context.d-87MMrNm6.d.cts → context.d-C3x-z665.d.cts} +5 -5
  45. package/dist/{context.d-rNGMZH8T.d.ts → context.d-goZeZO2I.d.ts} +5 -5
  46. package/dist/{copy.d-CJOLhJac.d.cts → copy.d-DPwFY4r5.d.cts} +2 -2
  47. package/dist/{copy.d-DbwWriBp.d.ts → copy.d-yfJv7fl6.d.ts} +2 -2
  48. package/dist/core/index.cjs +10 -10
  49. package/dist/core/index.d.cts +13 -13
  50. package/dist/core/index.d.ts +13 -13
  51. package/dist/core/index.js +10 -10
  52. package/dist/{depth.d-Dca1T_RH.d.ts → depth.d-SJzknw_P.d.ts} +2 -2
  53. package/dist/{depth.d-CXpPxNSK.d.cts → depth.d-e_8_icip.d.cts} +2 -2
  54. package/dist/{entitlementRepository.d-BBRYTUlp.d.ts → entitlementRepository.d-BNgZhwoE.d.ts} +2 -2
  55. package/dist/{entitlementRepository.d-DBhzBQjZ.d.cts → entitlementRepository.d-C_LdzINM.d.cts} +2 -2
  56. package/dist/{focus.d-BQnOVAql.d.cts → focus.d-CXpIkIuU.d.cts} +2 -2
  57. package/dist/{focus.d-BZ2sEpbU.d.ts → focus.d-DzIgOqNB.d.ts} +2 -2
  58. package/dist/health-plan/index.cjs +7 -7
  59. package/dist/health-plan/index.d.cts +10 -10
  60. package/dist/health-plan/index.d.ts +10 -10
  61. package/dist/health-plan/index.js +7 -7
  62. package/dist/{idempotency.d-9wNNohIA.d.cts → idempotency.d-0biUa_Vw.d.cts} +1 -1
  63. package/dist/{idempotency.d-BdB17veP.d.ts → idempotency.d-DcqIqmf9.d.ts} +1 -1
  64. package/dist/{identity.d-DxNvhj3a.d.ts → identity.d-BEJcHY-5.d.ts} +1 -1
  65. package/dist/{identity.d-nRZBzkG2.d.cts → identity.d-COcNGuCJ.d.cts} +1 -1
  66. package/dist/index.cjs +27 -26
  67. package/dist/index.d.cts +15 -14
  68. package/dist/index.d.ts +15 -14
  69. package/dist/index.js +28 -27
  70. package/dist/{introEvents.d-CQeiUeLn.d.cts → introEvents.d-D8N9bbGO.d.cts} +1 -1
  71. package/dist/{introEvents.d-bkIxpIKr.d.ts → introEvents.d-GCdyQyUG.d.ts} +1 -1
  72. package/dist/notifications/index.d.cts +4 -4
  73. package/dist/notifications/index.d.ts +4 -4
  74. package/dist/{optInView.d-DVJcB4Gp.d.ts → optInView.d-CY2IueSZ.d.ts} +2 -2
  75. package/dist/{optInView.d-BbVUUeoG.d.cts → optInView.d-DVuuWDRw.d.cts} +2 -2
  76. package/dist/{parse.d-CGeJrcAC.d.ts → parse.d--ztmWIIP.d.ts} +1 -1
  77. package/dist/{parse.d-Dk0BasyK.d.cts → parse.d-B-WrkW2C.d.cts} +1 -1
  78. package/dist/{pets.d-DVptPgi0.d.cts → pets.d-BSW0oEYx.d.cts} +1 -1
  79. package/dist/{pets.d-DBopbeRe.d.ts → pets.d-DwsImaHU.d.ts} +1 -1
  80. package/dist/{petsRepository.d-Daef7u0o.d.cts → petsRepository.d-BQfWC3d4.d.cts} +1 -1
  81. package/dist/{petsRepository.d-BtuooSOW.d.ts → petsRepository.d-BudLFHVe.d.ts} +1 -1
  82. package/dist/photo/index.cjs +2 -2
  83. package/dist/photo/index.js +2 -2
  84. package/dist/{ports.d-BxCVSbSi.d.ts → ports.d-B6kDPKF7.d.ts} +4 -4
  85. package/dist/{ports.d-CAT70bVD.d.cts → ports.d-DzPbmiDT.d.cts} +4 -4
  86. package/dist/records/depth/index.cjs +9 -9
  87. package/dist/records/depth/index.d.cts +9 -9
  88. package/dist/records/depth/index.d.ts +9 -9
  89. package/dist/records/depth/index.js +9 -9
  90. package/dist/records/index.cjs +13 -13
  91. package/dist/records/index.d.cts +10 -10
  92. package/dist/records/index.d.ts +10 -10
  93. package/dist/records/index.js +13 -13
  94. package/dist/{requestFunnel.d-Cxt0JqYx.d.ts → requestFunnel.d-BPsCHJWf.d.ts} +2 -2
  95. package/dist/{requestFunnel.d-mEu6B-n8.d.cts → requestFunnel.d-BdpL7gwg.d.cts} +2 -2
  96. package/dist/{runtimeTypes.d-Bkcj_XQy.d.ts → runtimeTypes.d-C_Pcxn-n.d.ts} +4 -4
  97. package/dist/{runtimeTypes.d-D_qHJROH.d.cts → runtimeTypes.d-Cfq3IrZG.d.cts} +4 -4
  98. package/dist/{screenProps.d-CR1lrpzR.d.cts → screenProps.d-BJMn1kTR.d.cts} +1 -1
  99. package/dist/{screenProps.d-D9n-ancr.d.ts → screenProps.d-DGrfO17l.d.ts} +1 -1
  100. package/dist/server/events/index.cjs +3 -3
  101. package/dist/server/events/index.d.cts +48 -6
  102. package/dist/server/events/index.d.ts +48 -6
  103. package/dist/server/events/index.js +3 -3
  104. package/dist/server/index.cjs +2 -2
  105. package/dist/server/index.d.cts +3 -3
  106. package/dist/server/index.d.ts +3 -3
  107. package/dist/server/index.js +2 -2
  108. package/dist/shop/index.cjs +1 -1
  109. package/dist/shop/index.d.cts +3 -3
  110. package/dist/shop/index.d.ts +3 -3
  111. package/dist/shop/index.js +1 -1
  112. package/dist/tabs/index.d.cts +8 -8
  113. package/dist/tabs/index.d.ts +8 -8
  114. package/dist/televet/booking/index.cjs +2 -2
  115. package/dist/televet/booking/index.d.cts +6 -6
  116. package/dist/televet/booking/index.d.ts +6 -6
  117. package/dist/televet/booking/index.js +2 -2
  118. package/dist/televet/call/index.cjs +1 -1
  119. package/dist/televet/call/index.js +1 -1
  120. package/dist/televet/index.cjs +4 -3
  121. package/dist/televet/index.d.cts +1 -0
  122. package/dist/televet/index.d.ts +1 -0
  123. package/dist/televet/index.js +5 -4
  124. package/dist/testing/index.d.cts +1 -1
  125. package/dist/testing/index.d.ts +1 -1
  126. package/dist/testing/rn/index.d.cts +7 -7
  127. package/dist/testing/rn/index.d.ts +7 -7
  128. package/dist/testing/web/index.d.cts +7 -7
  129. package/dist/testing/web/index.d.ts +7 -7
  130. package/dist/texting/index.d.cts +5 -5
  131. package/dist/texting/index.d.ts +5 -5
  132. package/dist/{threadOptions.d-BEG-LZrC.d.cts → threadOptions.d-B0folrKm.d.cts} +1 -1
  133. package/dist/{threadOptions.d-P9v7I7va.d.cts → threadOptions.d-B8HTJa9A.d.cts} +3 -3
  134. package/dist/{threadOptions.d-BgBvSIw8.d.ts → threadOptions.d-BnhE7T8Y.d.ts} +3 -3
  135. package/dist/{threadOptions.d-BerQM1Ql.d.ts → threadOptions.d-DTsJFkL-.d.ts} +1 -1
  136. package/dist/{threadOptions.d-6hfQS1x7.d.cts → threadOptions.d-GPJPprkn.d.cts} +1 -1
  137. package/dist/{threadOptions.d-6hfQS1x7.d.ts → threadOptions.d-GPJPprkn.d.ts} +1 -1
  138. package/dist/{timelineRows.d-C04lp_Vj.d.cts → timelineRows.d-BTcUdNeI.d.cts} +1 -1
  139. package/dist/{timelineRows.d-_7JemrY-.d.ts → timelineRows.d-kmBms1W5.d.ts} +1 -1
  140. package/dist/{useHealthPlanSubscription.d-OhLZpn-n.d.cts → useHealthPlanSubscription.d-B_cth_iF.d.cts} +3 -3
  141. package/dist/{useHealthPlanSubscription.d-CUbHE6eK.d.ts → useHealthPlanSubscription.d-BzNaVl89.d.ts} +3 -3
  142. package/dist/{usePresentation.d-CBtBx38t.d.ts → usePresentation.d-B7Uf44Ax.d.ts} +1 -1
  143. package/dist/{usePresentation.d-YkJeq9mf.d.cts → usePresentation.d-BkAMOfb5.d.cts} +1 -1
  144. package/dist/{useRecordsDepth.d-_rqDIvoq.d.ts → useRecordsDepth.d-BHkZi0tM.d.ts} +1 -1
  145. package/dist/{useRecordsDepth.d-FTImzp6T.d.cts → useRecordsDepth.d-BxHpKipf.d.cts} +1 -1
  146. package/dist/video/index.cjs +2 -2
  147. package/dist/video/index.js +2 -2
  148. package/dist/{view.d-gmYinlac.d.ts → view.d-2BYMRnWj.d.ts} +3 -3
  149. package/dist/{view.d-Dd6AfMvG.d.cts → view.d-CoDbnv0f.d.cts} +3 -3
  150. package/dist/web/consent/index.d.cts +5 -5
  151. package/dist/web/consent/index.d.ts +5 -5
  152. package/dist/web/health-plan/index.cjs +4 -4
  153. package/dist/web/health-plan/index.d.cts +12 -12
  154. package/dist/web/health-plan/index.d.ts +12 -12
  155. package/dist/web/health-plan/index.js +4 -4
  156. package/dist/web/index.cjs +4 -4
  157. package/dist/web/index.d.cts +23 -23
  158. package/dist/web/index.d.ts +23 -23
  159. package/dist/web/index.js +4 -4
  160. package/dist/web/intro/index.d.cts +6 -6
  161. package/dist/web/intro/index.d.ts +6 -6
  162. package/dist/web/notifications/index.d.cts +3 -3
  163. package/dist/web/notifications/index.d.ts +3 -3
  164. package/dist/web/records/depth/index.cjs +9 -9
  165. package/dist/web/records/depth/index.d.cts +9 -9
  166. package/dist/web/records/depth/index.d.ts +9 -9
  167. package/dist/web/records/depth/index.js +9 -9
  168. package/dist/web/records/index.cjs +12 -12
  169. package/dist/web/records/index.d.cts +11 -11
  170. package/dist/web/records/index.d.ts +11 -11
  171. package/dist/web/records/index.js +12 -12
  172. package/dist/web/records-sheet/index.cjs +9 -9
  173. package/dist/web/records-sheet/index.js +9 -9
  174. package/dist/web/shop/index.cjs +1 -1
  175. package/dist/web/shop/index.d.cts +3 -3
  176. package/dist/web/shop/index.d.ts +3 -3
  177. package/dist/web/shop/index.js +1 -1
  178. package/dist/web/televet/booking/index.cjs +2 -2
  179. package/dist/web/televet/booking/index.d.cts +6 -6
  180. package/dist/web/televet/booking/index.d.ts +6 -6
  181. package/dist/web/televet/booking/index.js +2 -2
  182. package/dist/web/televet/call/index.cjs +1 -1
  183. package/dist/web/televet/call/index.js +1 -1
  184. package/dist/web/texting/index.d.cts +5 -5
  185. package/dist/web/texting/index.d.ts +5 -5
  186. package/package.json +17 -26
@@ -1,5 +1,9 @@
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,useMemo,useState,useRef,useEffect,useCallback,useSyncExternalStore,useContext,Fragment as Fragment$1,Component}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,KeyboardAvoidingView,View,Pressable,Text as Text$1,Dimensions,Keyboard,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList,Linking}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as bookingExperience from"@everfur/sdk/televet/booking";import*as texting from"@everfur/sdk/texting";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
2
+ import{createContext,forwardRef,createElement,useCallback,useMemo,useRef,useState,useEffect,useSyncExternalStore,useContext,Component,Fragment as Fragment$1}from"react";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as bookingExperience from"@everfur/sdk/televet/booking";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,Text as Text$1,View,KeyboardAvoidingView,Dimensions,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList,Linking}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import*as texting from"@everfur/sdk/texting";var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot2=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot2.activeHost===id?snapshot2.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot2.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>Promise.resolve(bookingExperience));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
3
+ return jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}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__ */
4
+ 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__ */
5
+ return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
6
+ 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 CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
3
7
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
4
8
  /* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
5
9
  /* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
@@ -92,29 +96,19 @@ import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,
92
96
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
93
97
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
94
98
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
95
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
96
- return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
97
- return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
98
- /* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
99
- /* @__PURE__ */Object.freeze({key:"outdated",label:CHAT_COPY.feedbackReasonOutdated,feedbackType:"outdated"}),
100
- /* @__PURE__ */Object.freeze({key:"unsafe",label:CHAT_COPY.feedbackReasonUnsafe,feedbackType:"dangerous"}),
101
- /* @__PURE__ */Object.freeze({key:"unclear",label:CHAT_COPY.feedbackReasonUnclear,feedbackType:"unclear"}),
102
- /* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
103
- /* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
104
- /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
99
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
105
100
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
106
101
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
107
- return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop2=()=>{};if(!caller)return{signal:deadline,dispose:noop2};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
108
- return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid("pet_ref must be a string");if(petRef.trim().length===0)return invalid("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str2=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
109
- return Object.freeze({petRef:str2(o.pet_ref)??petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str2(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str2(o.pet_id),petRef:petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str2(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
110
- return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid4=validate(petRef,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useStalePetHold(runtime,userRef,petRef,scopeEpoch){let[owner,setOwner]=useState({pet:petRef,user:userRef}),adopt=owner.pet!==petRef||owner.user===null&&userRef!==null;adopt&&setOwner({pet:petRef,user:userRef});let current=adopt?{user:userRef}:owner,held=petRef!==null&&current.user!==null&&current.user!==userRef;return useEffect(()=>{if(!held||userRef===null||petRef===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef)&&setOwner({pet:petRef,user:userRef})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef,petRef,scopeEpoch]),held}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=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 BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef=opts?.petRef??activePet??null,conversationId=opts?.conversationId??null,held=useStalePetHold(runtime,userRef,petRef,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef,petRef:petRef,conversationId:conversationId,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef,petRef,conversationId,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef,petRef:petRef,conversationId:conversationId}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef,petRef:petRef,conversationId:conversationId});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef,petRef,conversationId,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef?{petRef:petRef}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=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__ */
111
- return Object.freeze(out)}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var REF_MAX2=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str3=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str3(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str3(value,REF_MAX2);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
112
- return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str3(v,len),max);function focusOf(value){let o=obj(value),kicker=str3(o?.kicker,120),title=str3(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str3(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str3(risk?.lead,300)===null?null:clean({lead:str3(risk?.lead,300),body:str3(risk?.body),kind:kindOf(risk?.kind)}),odds:str3(odds?.label,120)===null||str3(odds?.from,20)===null||str3(odds?.to,20)===null?null:clean({label:str3(odds?.label,120),tag:str3(odds?.tag,40),from:str3(odds?.from,20),to:str3(odds?.to,20),toLabel:str3(odds?.toLabel,120)}),quote:str3(quote?.text)===null?null:clean({kicker:str3(quote?.kicker,120),tag:str3(quote?.tag,40),text:str3(quote?.text)}),jump:str3(jump?.title,300)===null||str3(jump?.go,60)===null?null:clean({title:str3(jump?.title,300),go:str3(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str3(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str3(s?.title,300),tone=s?.tone;return t===null?null:clean({title:t,body:str3(s?.body),source:str3(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str3(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str3(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text3=str3(v?.text),by=str3(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text3===null||by===null?null:clean({stars:Math.round(stars),text:text3,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str3(v?.chip,40),t=str3(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str3(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str3(v?.value,40),label=str3(v?.label,120),kind=v?.kind;return val===null||label===null?null:clean({value:val,label:label,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,hidden:o.none===true&&o.hidden===true?true:null,productId:idOf(o.productId),partnerSku:str3(o.partnerSku,200),rating:str3(rating?.value,20)===null?null:clean({value:str3(rating?.value,20),label:str3(rating?.label,120)}),line:str3(o.line),reviews:str3(reviews?.label,200)===null||reviewItems===null?null:clean({label:str3(reviews?.label,200),items:reviewItems}),checkoutLine:str3(o.checkoutLine,300),why:str3(why?.title,200)===null||whyRows===null?null:clean({title:str3(why?.title,200),rows:whyRows,score:str3(score?.text,200)===null||str3(score?.value,20)===null?null:clean({text:str3(score?.text,200),value:str3(score?.value,20)})}),dose:str3(dose?.title,200)===null||stats===null?null:clean({title:str3(dose?.title,200),stats:stats,note:str3(dose?.note)}),doseLabel:str3(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str3(ingredients?.label,200),items:ingredientItems}),proof:str3(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str3(o.more,120),fine:str3(o.fine),checkin:str3(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str3(v?.title,300),body=str3(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str3(o?.title,200),questions=words(o?.questions,12,300),add=str3(o?.add,80),added=str3(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str3(v?.key,REF_MAX2),t=str3(v?.title,300),action=str3(v?.action,80),productId=idOf(v?.productId),added=str3(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,title:t,body:str3(v?.body),price:str3(v?.price,40),was:str3(v?.was,40),tag:str3(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}function waitOf(value){let o=obj(value),kicker=str3(o?.kicker,120),title=str3(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str3(v?.title,120),state=v?.state;return t===null?null:clean({title:t,detail:str3(v?.detail,120),state:typeof state=="string"&&TRACK_STATES.has(state)?state:null,tag:str3(v?.tag,40)})},6),heading:str3(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,120);if(icon===null||label===null)return null;if(v?.fromVet===true)return clean({icon:icon,label:label,text:"",fromVet:true});let text3=str3(v?.text,300);return text3===null?null:clean({icon:icon,label:label,text:text3})},6),note:str3(o.note,300),action:str3(o.action,80)})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str3(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str3(o.eyebrow,120),title:title,subtitle:str3(o.subtitle,300),subtitleNoRecords:str3(o.subtitleNoRecords,300),headImageUrl:imageOf(o.headImageUrl),byline:str3(byline?.name,120)===null?null:clean({name:str3(byline?.name,120),role:str3(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str3(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),wait:waitOf(o.wait),fine:str3(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,60),val=str3(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
113
- return Object.freeze({petRef:str3(o.pet_ref,REF_MAX2)??petRef,pet:/* @__PURE__ */Object.freeze({name:str3(pet?.name,120),species:str3(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str3(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid2("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host=globalThis,stored2=host[SHARED_READS_SYMBOL];if(stored2 instanceof WeakMap)return stored2;let made=/* @__PURE__ */new WeakMap;return host[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef,petRef,fresh2){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh2&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh2)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,runtime,userRef,pet,fresh2),[hostRepository,repository,own,runtime,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh2=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh2);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
102
+ return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop2=()=>{};if(!caller)return{signal:deadline,dispose:noop2};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var REF_MAX=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str(value,REF_MAX);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
103
+ return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str(v,len),max);function focusOf(value){let o=obj(value),kicker=str(o?.kicker,120),title=str(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str(risk?.lead,300)===null?null:clean({lead:str(risk?.lead,300),body:str(risk?.body),kind:kindOf(risk?.kind)}),odds:str(odds?.label,120)===null||str(odds?.from,20)===null||str(odds?.to,20)===null?null:clean({label:str(odds?.label,120),tag:str(odds?.tag,40),from:str(odds?.from,20),to:str(odds?.to,20),toLabel:str(odds?.toLabel,120)}),quote:str(quote?.text)===null?null:clean({kicker:str(quote?.kicker,120),tag:str(quote?.tag,40),text:str(quote?.text)}),jump:str(jump?.title,300)===null||str(jump?.go,60)===null?null:clean({title:str(jump?.title,300),go:str(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str(s?.title,300),tone=s?.tone;return t===null?null:clean({title:t,body:str(s?.body),source:str(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text3=str(v?.text),by=str(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text3===null||by===null?null:clean({stars:Math.round(stars),text:text3,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str(v?.chip,40),t=str(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str(v?.value,40),label=str(v?.label,120),kind=v?.kind;return val===null||label===null?null:clean({value:val,label:label,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,hidden:o.none===true&&o.hidden===true?true:null,productId:idOf(o.productId),partnerSku:str(o.partnerSku,200),rating:str(rating?.value,20)===null?null:clean({value:str(rating?.value,20),label:str(rating?.label,120)}),line:str(o.line),reviews:str(reviews?.label,200)===null||reviewItems===null?null:clean({label:str(reviews?.label,200),items:reviewItems}),checkoutLine:str(o.checkoutLine,300),why:str(why?.title,200)===null||whyRows===null?null:clean({title:str(why?.title,200),rows:whyRows,score:str(score?.text,200)===null||str(score?.value,20)===null?null:clean({text:str(score?.text,200),value:str(score?.value,20)})}),dose:str(dose?.title,200)===null||stats===null?null:clean({title:str(dose?.title,200),stats:stats,note:str(dose?.note)}),doseLabel:str(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str(ingredients?.label,200),items:ingredientItems}),proof:str(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str(o.more,120),fine:str(o.fine),checkin:str(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str(v?.title,300),body=str(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str(o?.title,200),questions=words(o?.questions,12,300),add=str(o?.add,80),added=str(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str(v?.key,REF_MAX),t=str(v?.title,300),action=str(v?.action,80),productId=idOf(v?.productId),added=str(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,title:t,body:str(v?.body),price:str(v?.price,40),was:str(v?.was,40),tag:str(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}function waitOf(value){let o=obj(value),kicker=str(o?.kicker,120),title=str(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str(v?.title,120),state=v?.state;return t===null?null:clean({title:t,detail:str(v?.detail,120),state:typeof state=="string"&&TRACK_STATES.has(state)?state:null,tag:str(v?.tag,40)})},6),heading:str(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str(v?.label,120);if(icon===null||label===null)return null;if(v?.fromVet===true)return clean({icon:icon,label:label,text:"",fromVet:true});let text3=str(v?.text,300);return text3===null?null:clean({icon:icon,label:label,text:text3})},6),note:str(o.note,300),action:str(o.action,80)})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str(o.eyebrow,120),title:title,subtitle:str(o.subtitle,300),subtitleNoRecords:str(o.subtitleNoRecords,300),headImageUrl:imageOf(o.headImageUrl),byline:str(byline?.name,120)===null?null:clean({name:str(byline?.name,120),role:str(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),wait:waitOf(o.wait),fine:str(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str(v?.label,60),val=str(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
104
+ return Object.freeze({petRef:str(o.pet_ref,REF_MAX)??petRef,pet:/* @__PURE__ */Object.freeze({name:str(pet?.name,120),species:str(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host=globalThis,stored2=host[SHARED_READS_SYMBOL];if(stored2 instanceof WeakMap)return stored2;let made=/* @__PURE__ */new WeakMap;return host[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef,petRef,fresh2){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh2&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh2)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,runtime,userRef,pet,fresh2),[hostRepository,repository,own,runtime,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh2=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh2);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
114
105
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
115
106
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}function selectView(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
116
107
  return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state,policy){if(policy===void 0)return visibleFollowUps(state);let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state.messages.length-1;i>=0;i-=1){let m=state.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state.suggestedPrompts)take(prompt);let fill=[];try{fill=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill=[]}for(let prompt of Array.isArray(fill)?fill:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
117
- return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef,conversationId){let opts={};return petRef!==void 0&&(opts.petRef=petRef),conversationId!==void 0&&(opts.conversationId=conversationId),opts}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){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,count=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count<=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:count,...exclude!==void 0?{exclude:exclude}:{}}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function petRegistrationKey(runtime,auth,petRef,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef,pet,onRegistered){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),register=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 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;return conversationId===null||conversationId.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function useChatLifecycle(lifecycle,target){let latest=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}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},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])}function targetKey(target){if(target===void 0)return null;let conversationId=target.conversationId??"",petRef=target.petRef??"";return conversationId===""&&petRef===""?null:`${String(conversationId)}|${String(petRef)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=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__ */
108
+ 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,count=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count<=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:count,...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 str2=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=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
109
+ 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:str2(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str2(o.food_brand),foodType:str2(o.food_type),microchipId:str2(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str2(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str2(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str2(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),conditionName:conditionName,diagnosedDate:str2(row.diagnosed_date),notes:str2(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 str3=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__ */
110
+ return Object.freeze({petRef:str3(o.pet_ref)??petRef,name:str3(o.name),species:str3(o.species),breed:str3(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=str3(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(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__ */
111
+ 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;return conversationId===null||conversationId.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function useChatLifecycle(lifecycle,target){let latest=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}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},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])}function targetKey(target){if(target===void 0)return null;let conversationId=target.conversationId??"",petRef=target.petRef??"";return conversationId===""&&petRef===""?null:`${String(conversationId)}|${String(petRef)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=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__ */
118
112
  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__ */
119
113
  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 HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
120
114
  return jsxs(View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
@@ -204,13 +198,12 @@ return jsxs(View,{style:styles3.composerOuter,children:[attachments!==null&&pick
204
198
  /* @__PURE__ */jsx(Text,{style:styles3.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:dictationErrorMessage(voice.error)}),
205
199
  /* @__PURE__ */jsx(AnnounceLine,{line:dictationErrorMessage(voice.error)})]}):null,
206
200
  /* @__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,
207
- /* @__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}})}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 subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot2=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot2.activeHost===id?snapshot2.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot2.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>Promise.resolve(bookingExperience));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
208
- return jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=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 VetVisitButton(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles6(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
201
+ /* @__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 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 VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=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__ */
209
202
  return jsxs(Fragment,{children:[null,
210
- /* @__PURE__ */jsx(EverfurTelevetHost,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
203
+ /* @__PURE__ */jsx(TelevetHostOutlet,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
211
204
  return jsxs(Fragment,{children:[
212
205
  /* @__PURE__ */jsx(Pressable,{onPress:()=>{if(!(busy||settling.current)){if(!redirecting){let request={...petRef!==void 0?{petRef:petRef}:{},...usState!==void 0?{usState:usState}:{},...visitRef!=null?{visitRef:visitRef,intent:intent??null}:{}};openVetVisitInApp(request,onStartInApp)===null&&callHost(onError,"unavailable",null);return}settling.current=true,(visitRef==null?visit.open():visit.openVisit(visitRef,intent??null)).then(result=>{result.opened?callHost(onOpened,result.flowId??null):result.reason!=="cancelled"&&callHost(onError,result.reason,result.error)}).finally(()=>{settling.current=false})}},accessibilityRole:"button",accessibilityLabel:text3,accessibilityState:{busy:busy,disabled:busy},style:[styles3.button,busy?styles3.busy:null,style],children:/* @__PURE__ */jsx(Text,{style:[styles3.label,labelStyle],children:text3})}),
213
- /* @__PURE__ */jsx(EverfurTelevetHost,{})]})}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function useBrandImage(uri){let[failed,setFailed]=useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandImage({uri:uri,label:label,decorative:decorative=false,style:style,resizeMode:resizeMode="contain",fallback:fallback=null,onError:onError,testID:testID}){let image=useBrandImage(uri);if(uri===null||!image.shown)return fallback;let a11y=decorative?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...label===void 0?{}:{accessibilityLabel:label}};/* @__PURE__ */
206
+ /* @__PURE__ */jsx(TelevetHostOutlet,{})]})}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function useBrandImage(uri){let[failed,setFailed]=useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandImage({uri:uri,label:label,decorative:decorative=false,style:style,resizeMode:resizeMode="contain",fallback:fallback=null,onError:onError,testID:testID}){let image=useBrandImage(uri);if(uri===null||!image.shown)return fallback;let a11y=decorative?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...label===void 0?{}:{accessibilityLabel:label}};/* @__PURE__ */
214
207
  return jsx(Image,{source:{uri:uri},style:style,resizeMode:resizeMode,...a11y,onError:()=>{image.onError(),onError?.()},...testID===void 0?{}:{testID:testID}})}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsx(View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsx(Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var UNMEASURED=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),NO_BALANCE=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function balanceHeaderSides(m,reserved,logoWidth){if(m.row===null||m.leading===null||m.trailing===null)return NO_BALANCE;let difference=Math.abs(m.leading-m.trailing);if(difference<.5)return NO_BALANCE;let centre=m.row-reserved-m.leading-m.trailing,spare=Math.min(difference,Math.max(0,centre-logoWidth));return spare<.5?NO_BALANCE:m.leading<m.trailing?{leading:m.leading+spare,trailing:void 0}:{leading:void 0,trailing:m.trailing+spare}}function nextMeasures(prev,key,width){let old=prev[key];return old!==null&&Math.abs(old-width)<.5?prev:{...prev,[key]:width}}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same(c.brand,compiled.brand)&&same(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
215
208
  /* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
216
209
  /* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
@@ -237,13 +230,20 @@ return jsxs(Fragment,{children:[
237
230
  /* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:historyUnread?`${CHAT_COPY.openHistoryNative}${CHAT_COPY.newReplySuffix}`:CHAT_COPY.openHistoryNative,containerStyle:styles3.iconSlot,style:styles3.iconButton,onPress:onOpenHistory,children:[
238
231
  /* @__PURE__ */jsx(MenuGlyph,{size:MENU_GLYPH_SIZE,color:theme.slots.header?.textColor??theme.color.text.primary,strokeWidth:2}),historyUnread?/* @__PURE__ */jsx(View,{style:styles3.unreadDot,pointerEvents:"none"}):null]})]})}),
239
232
  /* @__PURE__ */jsx(View,{style:styles3.centre,pointerEvents:"box-none",children:/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,barStyle:styles3.logoBar,logoStyle:styles3.logo})}),
240
- /* @__PURE__ */jsx(View,{style:[styles3.trailing,sideMins.trailing===void 0?null:{minWidth:sideMins.trailing}],children:/* @__PURE__ */jsxs(View,{style:styles3.trailingContent,onLayout:onTrailingLayout,children:[shownPetRef===null?null:/* @__PURE__ */jsx(VetVisitButton,{entry:"chat",petRef:shownPetRef,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles3.vetEntry,labelStyle:styles3.vetEntryLabel}),
233
+ /* @__PURE__ */jsx(View,{style:[styles3.trailing,sideMins.trailing===void 0?null:{minWidth:sideMins.trailing}],children:/* @__PURE__ */jsxs(View,{style:styles3.trailingContent,onLayout:onTrailingLayout,children:[shownPetRef===null?null:/* @__PURE__ */jsx(VetVisitButtonCore,{entry:"chat",petRef:shownPetRef,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles3.vetEntry,labelStyle:styles3.vetEntryLabel}),
241
234
  /* @__PURE__ */jsx(View,{style:styles3.right,children:canSwitch?/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.switchActivePet,{name:name}),containerStyle:styles3.avatarSlot,style:styles3.avatarWrap,onPress:()=>setSwitcherOpen(true),children:[
242
235
  /* @__PURE__ */jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE}),
243
236
  /* @__PURE__ */jsx(View,{style:styles3.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsx(PlusGlyph,{size:ADD_BADGE_GLYPH,color:theme.color.brandInk,strokeWidth:2})})]}):pets.loading&&shown===null?
244
237
  /* @__PURE__ */jsx(View,{style:styles3.avatarWrap,accessible:true,accessibilityLabel:CHAT_COPY.yourPet,children:/* @__PURE__ */jsx(Ring,{size:HEADER_AVATAR_SIZE,strokeWidth:HEADER_RING_STROKE,color:theme.color.mark,children:/* @__PURE__ */jsx(View,{style:styles3.placeholderDisc})})}):/* @__PURE__ */jsx(View,{style:styles3.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:shown===null?CHAT_COPY.yourPet:name,children:/* @__PURE__ */jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE})})})]})}),
245
238
  /* @__PURE__ */jsx(PetSwitcherSheet,{visible:switcherOpen,pets:pets.pets,activePetRef:shown?.petRef??null,onSelect:select,onAddPet:addPet,onClose:()=>setSwitcherOpen(false)})]}),textingEntry===null?null:/* @__PURE__ */jsx(TextingEntryRow,{entry:textingEntry,place:"header"})]})}function TextingEntryRow({entry:entry,place:place}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles9(theme),[theme]);/* @__PURE__ */
246
- return jsx(View,{style:place==="header"?styles3.textingEntryRowHeader:styles3.textingEntryRowThread,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:entry.label,containerStyle:styles3.textingEntrySlot,style:styles3.vetEntry,onPress:entry.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.vetEntryLabel,numberOfLines:1,children:entry.label})})})}function makeStyles9(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2,header=theme.slots.header;return StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET4,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},textingEntrySlot:{borderRadius:theme.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:ROW_PADDING,paddingBottom:10,backgroundColor:header?.backgroundColor??c.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:ROW_PADDING,paddingTop:theme.space.sm},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:ROW_PADDING,paddingVertical:10,backgroundColor:c.surface,...slotBox(header)},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:header?.backgroundColor??c.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:theme.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:CENTRE_GAP,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var MIN_TOUCH_TARGET5=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles10(theme),[theme]),[reason,setReason]=useState(null),[note,setNote]=useState(""),[pending,setPending]=useState(false),[failed,setFailed]=useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
239
+ return jsx(View,{style:place==="header"?styles3.textingEntryRowHeader:styles3.textingEntryRowThread,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:entry.label,containerStyle:styles3.textingEntrySlot,style:styles3.vetEntry,onPress:entry.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.vetEntryLabel,numberOfLines:1,children:entry.label})})})}function makeStyles9(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2,header=theme.slots.header;return StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET4,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},textingEntrySlot:{borderRadius:theme.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:ROW_PADDING,paddingBottom:10,backgroundColor:header?.backgroundColor??c.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:ROW_PADDING,paddingTop:theme.space.sm},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:ROW_PADDING,paddingVertical:10,backgroundColor:c.surface,...slotBox(header)},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:header?.backgroundColor??c.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:theme.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:CENTRE_GAP,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
240
+ /* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
241
+ /* @__PURE__ */Object.freeze({key:"outdated",label:CHAT_COPY.feedbackReasonOutdated,feedbackType:"outdated"}),
242
+ /* @__PURE__ */Object.freeze({key:"unsafe",label:CHAT_COPY.feedbackReasonUnsafe,feedbackType:"dangerous"}),
243
+ /* @__PURE__ */Object.freeze({key:"unclear",label:CHAT_COPY.feedbackReasonUnclear,feedbackType:"unclear"}),
244
+ /* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
245
+ /* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
246
+ /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var MIN_TOUCH_TARGET5=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles10(theme),[theme]),[reason,setReason]=useState(null),[note,setNote]=useState(""),[pending,setPending]=useState(false),[failed,setFailed]=useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
247
247
  return jsx(Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"slide",onRequestClose:skip,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:styles3.root,children:[
248
248
  /* @__PURE__ */jsx(Pressable,{style:styles3.scrim,onPress:skip,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y}),
249
249
  /* @__PURE__ */jsxs(View,{style:styles3.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
@@ -330,7 +330,7 @@ return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:hostFinder
330
330
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.actionLabel,{color:ink2}],children:label})]})}let ink=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??tier.textColor;/* @__PURE__ */
331
331
  return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},style:[styles3.findVetButton,{borderColor:tier.borderColor,backgroundColor:tier.pillColor},styles3.findVetSlotBox,busy?styles3.findVetBusy:null],onPress:onPress,children:[
332
332
  /* @__PURE__ */jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink,strokeWidth:1.5}),
333
- /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles15(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT2,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=useCallback(petRef=>handle.setActivePet(petRef),[handle]);return useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=useRef(false),scope=useRef({send:chat.send,id:chat.conversationId});useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles3}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxs(View,{style:styles3.assistantSender,testID:"everfur-assistant-sender",children:[
333
+ /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles15(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT2,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useStalePetHold(runtime,userRef,petRef,scopeEpoch){let[owner,setOwner]=useState({pet:petRef,user:userRef}),adopt=owner.pet!==petRef||owner.user===null&&userRef!==null;adopt&&setOwner({pet:petRef,user:userRef});let current=adopt?{user:userRef}:owner,held=petRef!==null&&current.user!==null&&current.user!==userRef;return useEffect(()=>{if(!held||userRef===null||petRef===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef)&&setOwner({pet:petRef,user:userRef})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef,petRef,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef=opts?.petRef??activePet??null,conversationId=opts?.conversationId??null,held=useStalePetHold(runtime,userRef,petRef,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef,petRef:petRef,conversationId:conversationId,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef,petRef,conversationId,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef,petRef:petRef,conversationId:conversationId}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef,petRef:petRef,conversationId:conversationId});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef,petRef,conversationId,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef?{petRef:petRef}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=useCallback(petRef=>handle.setActivePet(petRef),[handle]);return useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=useRef(false),scope=useRef({send:chat.send,id:chat.conversationId});useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles3}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxs(View,{style:styles3.assistantSender,testID:"everfur-assistant-sender",children:[
334
334
  /* @__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 httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
335
335
  return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count){return count===1?`1 ${CHAT_COPY.sourceSingular}`:`${count} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function tileImageUrl(url){return hardenHttpsUrl(url.trim())}function followUpActionsFor(chat,options){if(options?.followUpActions===void 0||chat.isStreaming||chat.status==="error")return[];let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true?[]:hostList(options.followUpActions,{answer:last.text,question:questionFor(chat.messages,last.id),messageId:last.id})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor&&runs.push({kind:"text",text:text3.slice(cursor,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor=match.index+match[0].length}return cursor<text3.length&&runs.push({kind:"text",text:text3.slice(cursor)}),runs}function renderInlineMarkdown(text3,styles3){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
336
336
  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;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__ */
@@ -359,7 +359,7 @@ return jsxs(View,{style:styles3.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onL
359
359
  /* @__PURE__ */jsxs(View,{style:styles3.head,children:[
360
360
  /* @__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]}),
361
361
  /* @__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__ */
362
- 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(VetVisitButton,{entry:"chat",petRef:petRef,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style: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 count=cards.length;/* @__PURE__ */
362
+ 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 count=cards.length;/* @__PURE__ */
363
363
  return jsxs(View,{style:styles3.block,children:[
364
364
  /* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count,expanded),accessibilityState:{expanded:expanded},containerStyle:styles3.toggleSlot,style:styles3.togglePill,onPress:()=>setExpanded(current=>!current),children:[
365
365
  /* @__PURE__ */jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
@@ -388,7 +388,7 @@ return Object.freeze(PROMPTS.flatMap(template=>{let own=template.intent==="vet_r
388
388
  /* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
389
389
  /* @__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"?RAPH_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__ */
390
390
  return jsxs(View,{style:home!==null?styles3.homeBlock:styles3.block,children:[titleNode,
391
- /* @__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(VetVisitButton,{entry:"chat",petRef:petRef,label:prompt.label,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:[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__ */
391
+ /* @__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__ */
392
392
  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__ */
393
393
  return jsx(ErrorState,{error:chat.error,onRetry:chat.retryLast,onAddPet:extras.onAddPet});case"populated":/* @__PURE__ */
394
394
  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__ */
@@ -414,7 +414,7 @@ return jsxs(View,{style:[styles3.turnNotice,error?styles3.turnNoticeError:null],
414
414
  /* @__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}):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__ */
415
415
  return jsxs(View,{style:[styles3.rowBlock,styles3.rowBlockAssistant],testID:`everfur-texting-ask-${stage}`,children:[
416
416
  /* @__PURE__ */jsx(View,{style:[styles3.row,styles3.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${text3}`,children:/* @__PURE__ */jsxs(View,{style:styles3.bubble,children:[senderLine,
417
- /* @__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 EverfurChat(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
417
+ /* @__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__ */
418
418
  return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},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__ */
419
419
  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__ */
420
420
  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,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset,topCard:hostTopCard,onOpenHealthPlan:onOpenHealthPlan,answerCards:answerCards,historySheet:historySheet,historyBar:historyBar,starterPrompts:starterPrompts,emptyState:emptyState,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),useCheckinTarget(chat.openCheckin,checkinTarget),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,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=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:[
@@ -425,6 +425,7 @@ return jsx(AskHomeContext.Provider,{value:askHome,children:/* @__PURE__ */jsxs(K
425
425
  /* @__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}),
426
426
  /* @__PURE__ */jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
427
427
  /* @__PURE__ */jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
428
- /* @__PURE__ */jsx(EverfurTelevetHost,{})]})})}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:[
428
+ /* @__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:[
429
429
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.setupNoticeText,children:setup.error.displayMessage}),
430
- /* @__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"}export{EverfurChat,EverfurPoweredBy,createAppStateLifecycle,createRnChatAttachmentTransport,registerEverfurDictation,useChatAttachments,useEverfurChat,useEverfurPets,useHostPoweredBy};
430
+ /* @__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__ */
431
+ return jsx(TelevetHostSlot.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */jsx(EverfurChatCore,{...props})})}export{EverfurChat,EverfurPoweredBy,createAppStateLifecycle,createRnChatAttachmentTransport,registerEverfurDictation,useChatAttachments,useEverfurChat,useEverfurPets,useHostPoweredBy};