@everfur/sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +251 -4
  2. package/README.md +9 -3
  3. package/dist/{Chat-DwAC2vhB.d.ts → Chat-BOX-03ho.d.ts} +17 -3
  4. package/dist/{Chat-DPUD6dnc.d.cts → Chat-TA-aTcVF.d.cts} +17 -3
  5. package/dist/{DepthViews-DP0R-DhB.d.cts → DepthViews-CgjX2AJ5.d.ts} +1 -1
  6. package/dist/{DepthViews-DbFhR4Du.d.cts → DepthViews-Cviea-ri.d.cts} +1 -1
  7. package/dist/{DepthViews-DNEM96Se.d.ts → DepthViews-D2dRqWRq.d.ts} +1 -1
  8. package/dist/{DepthViews-D_3hl4xk.d.ts → DepthViews-DSFyaSeL.d.cts} +1 -1
  9. package/dist/{ErrorPolicyPort-CwbfmxzJ.d.ts → ErrorPolicyPort-D22LUVrK.d.ts} +1 -1
  10. package/dist/{ErrorPolicyPort-CNf4uQZP.d.cts → ErrorPolicyPort-D6CybiqJ.d.cts} +1 -1
  11. package/dist/{EverfurResult-DN9pL2Ab.d.cts → EverfurError-DmELDpXp.d.cts} +1 -67
  12. package/dist/{EverfurResult-DN9pL2Ab.d.ts → EverfurError-DmELDpXp.d.ts} +1 -67
  13. package/dist/EverfurResult-SGvHKsCB.d.ts +69 -0
  14. package/dist/EverfurResult-ZtH-YV1h.d.cts +69 -0
  15. package/dist/animations/index.cjs +1 -1
  16. package/dist/animations/index.d.cts +6 -5
  17. package/dist/animations/index.d.ts +6 -5
  18. package/dist/animations/index.js +1 -1
  19. package/dist/{attachments-5NeobOCd.d.ts → attachments-C_vtFu2f.d.ts} +7 -5
  20. package/dist/{attachments-D8T5re7e.d.cts → attachments-DHvnITuE.d.cts} +7 -5
  21. package/dist/{attachments-Bw3iMQgu.d.ts → attachments-oD5U2fXI.d.ts} +3 -3
  22. package/dist/{attachments-CQgFrEQ7.d.cts → attachments-pIdGOQfm.d.cts} +3 -3
  23. package/dist/bookingCopy-CJir9mjb.d.ts +1135 -0
  24. package/dist/bookingCopy-DfuA13dh.d.cts +1135 -0
  25. package/dist/branding-Xb_wL8N1.d.cts +212 -0
  26. package/dist/branding-xpQ056sM.d.ts +212 -0
  27. package/dist/callCopy-rDH9JTFo.d.cts +45 -0
  28. package/dist/callCopy-rDH9JTFo.d.ts +45 -0
  29. package/dist/callRoom-7wrE3RP2.d.ts +62 -0
  30. package/dist/callRoom-B_EqaUzx.d.cts +62 -0
  31. package/dist/casesRepository-B-Eg8ZJ3.d.cts +63 -0
  32. package/dist/casesRepository-DHgIYKN9.d.ts +63 -0
  33. package/dist/chat/index.cjs +1 -1
  34. package/dist/chat/index.d.cts +12 -10
  35. package/dist/chat/index.d.ts +12 -10
  36. package/dist/chat/index.js +1 -1
  37. package/dist/client/index.cjs +5 -5
  38. package/dist/client/index.d.cts +15 -11
  39. package/dist/client/index.d.ts +15 -11
  40. package/dist/client/index.js +5 -5
  41. package/dist/{config-CzTZGlfF.d.cts → config-ClI7QxB0.d.ts} +4 -3
  42. package/dist/{config-DW60uRb9.d.ts → config-DAFbf721.d.cts} +4 -3
  43. package/dist/consent/index.cjs +1 -1
  44. package/dist/consent/index.d.cts +9 -8
  45. package/dist/consent/index.d.ts +9 -8
  46. package/dist/consent/index.js +1 -1
  47. package/dist/{context-XvTzq1tE.d.cts → context-B-dUM1Qf.d.cts} +9 -8
  48. package/dist/{context-DXhqHlPU.d.ts → context-CZbgF_OH.d.ts} +9 -8
  49. package/dist/{copy-Mjoo91aS.d.ts → copy-CeRH3NXy.d.ts} +5 -4
  50. package/dist/{copy-bKDNigLb.d.cts → copy-CneuYdrO.d.cts} +5 -4
  51. package/dist/core/index.cjs +9 -9
  52. package/dist/core/index.d.cts +123 -32
  53. package/dist/core/index.d.ts +123 -32
  54. package/dist/core/index.js +9 -9
  55. package/dist/{depth-CErXCU8J.d.cts → depth-B3NFKlF9.d.cts} +38 -6
  56. package/dist/{depth-DjDcJ6kH.d.ts → depth-DO3Ko_qs.d.ts} +38 -6
  57. package/dist/entitlementRepository-74kW5mK0.d.ts +43 -0
  58. package/dist/entitlementRepository-m6zLUmiB.d.cts +43 -0
  59. package/dist/{identity-DI4eVx9S.d.cts → identity-C7uxGwfT.d.cts} +3 -3
  60. package/dist/{identity-BMx2SUOM.d.ts → identity-CLAUq-K4.d.ts} +3 -3
  61. package/dist/index.cjs +6 -6
  62. package/dist/index.d.cts +20 -17
  63. package/dist/index.d.ts +20 -17
  64. package/dist/index.js +6 -6
  65. package/dist/{models-D2EUxPZY.d.cts → models-Bn2z0NNo.d.cts} +1 -1
  66. package/dist/{models-B-Uh2LTf.d.ts → models-DSqA5Ahs.d.ts} +1 -1
  67. package/dist/notifications/index.cjs +2 -2
  68. package/dist/notifications/index.d.cts +5 -4
  69. package/dist/notifications/index.d.ts +5 -4
  70. package/dist/notifications/index.js +2 -2
  71. package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
  72. package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
  73. package/dist/{pets-aB8q0JyX.d.cts → pets-BoB5B7kp.d.cts} +2 -2
  74. package/dist/{pets-CtQdRpWo.d.ts → pets-w4M9d-Dn.d.ts} +2 -2
  75. package/dist/{casesRepository-ClLv6qMl.d.ts → petsRepository-BjKJ8UsN.d.ts} +3 -49
  76. package/dist/{casesRepository-DHwtGRYY.d.cts → petsRepository-DZZoEG3r.d.cts} +3 -49
  77. package/dist/photo/index.cjs +1 -1
  78. package/dist/photo/index.d.cts +3 -2
  79. package/dist/photo/index.d.ts +3 -2
  80. package/dist/photo/index.js +1 -1
  81. package/dist/{ports-DMolTRzU.d.ts → ports-BO3bzTJg.d.ts} +14 -17
  82. package/dist/{ports-DEBzEhbp.d.cts → ports-C2EVK416.d.cts} +14 -17
  83. package/dist/records/depth/index.cjs +2 -2
  84. package/dist/records/depth/index.d.cts +11 -10
  85. package/dist/records/depth/index.d.ts +11 -10
  86. package/dist/records/depth/index.js +2 -2
  87. package/dist/records/index.cjs +3 -3
  88. package/dist/records/index.d.cts +25 -14
  89. package/dist/records/index.d.ts +25 -14
  90. package/dist/records/index.js +3 -3
  91. package/dist/{requestFunnel-CjW7uDuA.d.ts → requestFunnel-D7ipek3e.d.ts} +28 -4
  92. package/dist/{requestFunnel-L-BQfi0z.d.cts → requestFunnel-Djjwgoe9.d.cts} +28 -4
  93. package/dist/{runtime-BR9ysG0J.d.ts → runtimeTypes-CTL3yToK.d.ts} +10 -100
  94. package/dist/{runtime-B8s-_hv8.d.cts → runtimeTypes-D2C9uD85.d.cts} +10 -100
  95. package/dist/server/events/index.cjs +1 -1
  96. package/dist/server/events/index.d.cts +4 -3
  97. package/dist/server/events/index.d.ts +4 -3
  98. package/dist/server/events/index.js +1 -1
  99. package/dist/server/index.cjs +1 -1
  100. package/dist/server/index.d.cts +5 -4
  101. package/dist/server/index.d.ts +5 -4
  102. package/dist/server/index.js +1 -1
  103. package/dist/televet/booking/index.cjs +1 -0
  104. package/dist/televet/booking/index.d.cts +566 -0
  105. package/dist/televet/booking/index.d.ts +566 -0
  106. package/dist/televet/booking/index.js +1 -0
  107. package/dist/televet/call/index.cjs +1 -0
  108. package/dist/televet/call/index.d.cts +161 -0
  109. package/dist/televet/call/index.d.ts +161 -0
  110. package/dist/televet/call/index.js +1 -0
  111. package/dist/televet/index.cjs +1 -1
  112. package/dist/televet/index.d.cts +64 -12
  113. package/dist/televet/index.d.ts +64 -12
  114. package/dist/televet/index.js +1 -1
  115. package/dist/televetGlobal-CEk0_cW9.d.cts +34 -0
  116. package/dist/televetGlobal-Cs9Wbqsy.d.ts +34 -0
  117. package/dist/testing/index.cjs +4 -4
  118. package/dist/testing/index.d.cts +4 -3
  119. package/dist/testing/index.d.ts +4 -3
  120. package/dist/testing/index.js +4 -4
  121. package/dist/testing/rn/index.cjs +1 -1
  122. package/dist/testing/rn/index.d.cts +13 -10
  123. package/dist/testing/rn/index.d.ts +13 -10
  124. package/dist/testing/rn/index.js +1 -1
  125. package/dist/testing/web/index.cjs +1 -1
  126. package/dist/testing/web/index.d.cts +14 -12
  127. package/dist/testing/web/index.d.ts +14 -12
  128. package/dist/testing/web/index.js +1 -1
  129. package/dist/{timelineRows-DZed6dAM.d.ts → timelineRows-7yFNK_rU.d.ts} +1 -1
  130. package/dist/{timelineRows-CaohZzXS.d.cts → timelineRows-CzR1T2DR.d.cts} +1 -1
  131. package/dist/tokens-CIngRkvt.d.cts +362 -0
  132. package/dist/tokens-CIngRkvt.d.ts +362 -0
  133. package/dist/typeStyle-DHJzDaUo.d.cts +112 -0
  134. package/dist/typeStyle-YPS_MXeI.d.ts +112 -0
  135. package/dist/{useRecordsDepth-BHBzJ76R.d.cts → useRecordsDepth-Bnw36jPr.d.cts} +24 -5
  136. package/dist/{useRecordsDepth-BU-OhzH6.d.ts → useRecordsDepth-DFF7Faxx.d.ts} +24 -5
  137. package/dist/{useVetVisit-CjmMa896.d.ts → useVetVisit-BsjoDO-n.d.ts} +21 -6
  138. package/dist/{useVetVisit-Bc84hWUU.d.cts → useVetVisit-Ds8f1peV.d.cts} +21 -6
  139. package/dist/video/index.cjs +1 -1
  140. package/dist/video/index.d.cts +3 -2
  141. package/dist/video/index.d.ts +3 -2
  142. package/dist/video/index.js +1 -1
  143. package/dist/{view-DtSPYpKa.d.ts → view-BqcOYFTr.d.ts} +5 -4
  144. package/dist/{view-C3qPIXGX.d.cts → view-CaJs8WFH.d.cts} +5 -4
  145. package/dist/web/consent/index.cjs +1 -1
  146. package/dist/web/consent/index.d.cts +9 -8
  147. package/dist/web/consent/index.d.ts +9 -8
  148. package/dist/web/consent/index.js +1 -1
  149. package/dist/web/index.cjs +10 -10
  150. package/dist/web/index.d.cts +43 -19
  151. package/dist/web/index.d.ts +43 -19
  152. package/dist/web/index.js +10 -10
  153. package/dist/web/notifications/index.cjs +2 -2
  154. package/dist/web/notifications/index.d.cts +7 -6
  155. package/dist/web/notifications/index.d.ts +7 -6
  156. package/dist/web/notifications/index.js +2 -2
  157. package/dist/web/records/depth/index.cjs +2 -2
  158. package/dist/web/records/depth/index.d.cts +11 -10
  159. package/dist/web/records/depth/index.d.ts +11 -10
  160. package/dist/web/records/depth/index.js +2 -2
  161. package/dist/web/records/index.cjs +3 -3
  162. package/dist/web/records/index.d.cts +123 -14
  163. package/dist/web/records/index.d.ts +123 -14
  164. package/dist/web/records/index.js +3 -3
  165. package/dist/web/televet/booking/index.cjs +2 -0
  166. package/dist/web/televet/booking/index.d.cts +770 -0
  167. package/dist/web/televet/booking/index.d.ts +770 -0
  168. package/dist/web/televet/booking/index.js +2 -0
  169. package/dist/web/televet/call/index.cjs +1 -0
  170. package/dist/web/televet/call/index.d.cts +144 -0
  171. package/dist/web/televet/call/index.d.ts +144 -0
  172. package/dist/web/televet/call/index.js +1 -0
  173. package/dist/web/televet/index.cjs +1 -1
  174. package/dist/web/televet/index.d.cts +61 -9
  175. package/dist/web/televet/index.d.ts +61 -9
  176. package/dist/web/televet/index.js +1 -1
  177. package/package.json +74 -5
  178. package/televet/booking/package.json +8 -0
  179. package/televet/call/package.json +8 -0
  180. package/web/televet/booking/native-blocked.cjs +12 -0
  181. package/web/televet/booking/package.json +8 -0
  182. package/web/televet/call/native-blocked.cjs +12 -0
  183. package/web/televet/call/package.json +8 -0
  184. package/dist/entitlementRepository-DKdXFgTo.d.cts +0 -698
  185. package/dist/entitlementRepository-DSbzuyAW.d.ts +0 -698
  186. package/dist/typeStyle-0TydiZ1w.d.cts +0 -19
  187. package/dist/typeStyle-CWMsoe6b.d.ts +0 -19
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import {createContext,forwardRef,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component}from'react';import {useSafeAreaInsets,SafeAreaProvider}from'react-native-safe-area-context';import {z}from'zod';import sg from'react-native-sse';import {StyleSheet,TextInput,View,Linking,KeyboardAvoidingView,Platform,Pressable,ActivityIndicator,ScrollView,Animated,useColorScheme,AccessibilityInfo,PixelRatio,Dimensions,Text,UIManager,LayoutAnimation,Modal,Image,useWindowDimensions,FlatList}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Kc=Object.defineProperty;var i=(e,t)=>Kc(e,"name",{value:t,configurable:true});function Ce(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Ce,"hasLoneSurrogate");function ot(e){return [...e].length}i(ot,"serverLength");function L(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(L,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function qc(e){return e.ok}i(qc,"isOk");function $c(e){return !e.ok}i($c,"isErr");var Er=class Er extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Er.prototype);}};i(Er,"EverfurThrownError");var Cr=Er;function Yc(e){if(e.ok)return e.value;throw new Cr(e.error)}i(Yc,"unwrap");var Rr=class Rr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Rr.prototype);}};i(Rr,"EverfurConfigError");var $=Rr;var Ii=128,Ai=128,Oi=/[\u0000-\u001F\u007F]/,Xc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qc(e){let t=e,r=ot(t);if(r===0||r>Ai)throw new $("invalid-argument",`petRef must be 1..${Ai} characters`);if(Oi.test(t))throw new $("invalid-argument","petRef must be printable (no control characters)");return t}i(Qc,"petRef");function Zc(e){let t=e,r=ot(t);if(r===0||r>Ii)throw new $("invalid-argument",`userRef must be 1..${Ii} characters`);if(t.includes("@"))throw new $("invalid-argument","userRef must not contain '@'");if(Oi.test(t))throw new $("invalid-argument","userRef must be printable (no control characters)");return t}i(Zc,"userRef");function Jc(e){if(!Xc.test(e))throw new $("invalid-argument","conversationId must be a UUID");return e}i(Jc,"conversationId");var xn=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(xn.map(e=>e.wireCode));var ep=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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Mi=Object.freeze(xn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:ep[e.wireCode]}))),tp=new Map(Mi.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),rp=Object.freeze(["http_envelope",...[...new Set(Mi.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Sr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...rp]){let o=tp.get(n+r);if(o)return o}}i(Sr,"contractErrorFor");function np(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(np,"contractDocUrl");function Li(e){return null}i(Li,"publishedDocUrl");var op=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"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 _n(e){return op[e]}i(_n,"categoryFor");function Ie(e){let t=Sr(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";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"}}i(Ie,"fromWire");function Di(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(Di,"fromHttpStatus");var ip=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Be(e){return ip.has(e)}i(Be,"isAutoRetryable");var sp=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function wn(e){return Be(e)||sp.has(e)}i(wn,"isRetryableCode");function Pr(e,t=false){return t||Be(e)}i(Pr,"shouldRetry");var ap=500,In=8e3,jt=4;function Tr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(ap*2**r,In);return Math.floor(t()*n)}i(Tr,"backoffDelayMs");function Ni(e){return e==="conversationNotFound"}i(Ni,"canRecreateOnNotFound");var lp=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:"This feature isn't available on your account right now.",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:"Something in that request was not right. Check the details and try again.",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.",unknown:"Something went wrong. Please try again."});function xt(e){return lp[e]}i(xt,"userFacingError");function Ui(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Ui,"defineHidden");var up=/^[a-z][a-z0-9_]{0,63}$/;function N(e,t){let r=Sr(t?.wireCode,t?.wireEnvelope),n={code:e,category:_n(e),retryable:t?.retryable??wn(e),displayMessage:xt(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&up.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Ui(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Ui(n,"raw",t.raw),Object.freeze(n)}i(N,"makeEverfurError");var dp="file",cp="document.pdf",pp="records upload: the file handle has no uri",fp="records upload failed";function mp(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(pp));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(fp)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(dp,{uri:r.uri,name:cp,type:"application/pdf"});let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(mp,"createRnRecordsUploadTransport");var kr=Object.freeze({track(){},trackExpectedFailure(){}});var Vi=Object.freeze({shouldRetry(e,t){return Be(e)&&t<jt},maxAttempts(){return jt}});var Bi=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function qe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(qe,"assertNever");function Hi(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Hi,"acceptedFrame");function zi(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(zi,"heartbeatFrame");function ji(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ji,"deltaFrame");function Wi(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Wi,"doneFrame");function de(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(de,"errorFrame");function Gi(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Gi,"analysisStartedFrame");function Ki(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Ki,"analysisCompleteFrame");function qi(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(qi,"unknownFrame");function $i(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new $("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:hp(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new $("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i($i,"createIdentityProvider");function hp(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(hp,"expiryMs");function On(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(On,"newSessionId");function bp(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(bp,"authHeaders");function Wt(e,t){return {...e,headers:{...vp(e.headers),...bp(t)}}}i(Wt,"withAuthHeaders");function vp(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(vp,"stripAuthHeaders");async function Yi(e,t){if(t.mode==="anonymous")return t.transport.request(Wt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(An())}let n=await t.transport.request(Wt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return v(An())}let s=await t.transport.request(Wt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(An(s.error.httpStatus)):s}i(Yi,"authedSend");function An(e){return N("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(An,"authRejectedError");var Xi=`
1
+ import {createContext,forwardRef,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component}from'react';import {useSafeAreaInsets,SafeAreaProvider}from'react-native-safe-area-context';import {z}from'zod';import sh from'react-native-sse';import {StyleSheet,TextInput,View,Linking,KeyboardAvoidingView,Platform,Pressable,useColorScheme,AccessibilityInfo,PixelRatio,Dimensions,Text,Animated,UIManager,LayoutAnimation,Modal,Image,ActivityIndicator,ScrollView,useWindowDimensions,FlatList}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var nf=Object.defineProperty;var i=(e,t)=>nf(e,"name",{value:t,configurable:true});function Re(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Re,"hasLoneSurrogate");function it(e){return [...e].length}i(it,"serverLength");function M(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(M,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function of(e){return e.ok}i(of,"isOk");function sf(e){return !e.ok}i(sf,"isErr");var Or=class Or extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Or.prototype);}};i(Or,"EverfurThrownError");var Ar=Or;function af(e){if(e.ok)return e.value;throw new Ar(e.error)}i(af,"unwrap");var Fr=class Fr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fr.prototype);}};i(Fr,"EverfurConfigError");var Q=Fr;var ns=128,os=128,is=/[\u0000-\u001F\u007F]/,lf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uf(e){let t=e,r=it(t);if(r===0||r>os)throw new Q("invalid-argument",`petRef must be 1..${os} characters`);if(is.test(t))throw new Q("invalid-argument","petRef must be printable (no control characters)");return t}i(uf,"petRef");function df(e){let t=e,r=it(t);if(r===0||r>ns)throw new Q("invalid-argument",`userRef must be 1..${ns} characters`);if(t.includes("@"))throw new Q("invalid-argument","userRef must not contain '@'");if(is.test(t))throw new Q("invalid-argument","userRef must be printable (no control characters)");return t}i(df,"userRef");function cf(e){if(!lf.test(e))throw new Q("invalid-argument","conversationId must be a UUID");return e}i(cf,"conversationId");var Vn=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Vn.map(e=>e.wireCode));var pf=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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),as=Object.freeze(Vn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:pf[e.wireCode]}))),ff=new Map(as.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),mf=Object.freeze(["http_envelope",...[...new Set(as.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Mr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...mf]){let o=ff.get(n+r);if(o)return o}}i(Mr,"contractErrorFor");function yf(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(yf,"contractDocUrl");function ls(e){return null}i(ls,"publishedDocUrl");var gf=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"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 Hn(e){return gf[e]}i(Hn,"categoryFor");function Ae(e){let t=Mr(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";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"}}i(Ae,"fromWire");function us(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(us,"fromHttpStatus");var hf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function He(e){return hf.has(e)}i(He,"isAutoRetryable");var bf=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Bn(e){return He(e)||bf.has(e)}i(Bn,"isRetryableCode");function Lr(e,t=false){return t||He(e)}i(Lr,"shouldRetry");var vf=500,zn=8e3,Yt=4;function Dr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(vf*2**r,zn);return Math.floor(t()*n)}i(Dr,"backoffDelayMs");function ds(e){return e==="conversationNotFound"}i(ds,"canRecreateOnNotFound");var Cf=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:"This feature isn't available on your account right now.",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:"Something in that request was not right. Check the details and try again.",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.",unknown:"Something went wrong. Please try again."});function It(e){return Cf[e]}i(It,"userFacingError");function cs(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(cs,"defineHidden");var Ef=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Mr(t?.wireCode,t?.wireEnvelope),n={code:e,category:Hn(e),retryable:t?.retryable??Bn(e),displayMessage:It(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ef.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&cs(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&cs(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Rf="file",Sf="document.pdf",Tf="records upload: the file handle has no uri",Pf="records upload failed";function kf(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Tf));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Pf)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(Rf,{uri:r.uri,name:Sf,type:"application/pdf"});let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(kf,"createRnRecordsUploadTransport");var Nr=Object.freeze({track(){},trackExpectedFailure(){}});var ps=Object.freeze({shouldRetry(e,t){return He(e)&&t<Yt},maxAttempts(){return Yt}});var fs=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Xe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Xe,"assertNever");function ms(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ms,"acceptedFrame");function ys(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(ys,"heartbeatFrame");function gs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(gs,"deltaFrame");function hs(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(hs,"doneFrame");function pe(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(pe,"errorFrame");function bs(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(bs,"analysisStartedFrame");function vs(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(vs,"analysisCompleteFrame");function Cs(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Cs,"unknownFrame");function Es(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new Q("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:wf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new Q("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Es,"createIdentityProvider");function wf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(wf,"expiryMs");function Wn(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(Wn,"newSessionId");function If(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(If,"authHeaders");function Xt(e,t){return {...e,headers:{...Af(e.headers),...If(t)}}}i(Xt,"withAuthHeaders");function Af(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(Af,"stripAuthHeaders");async function Rs(e,t){if(t.mode==="anonymous")return t.transport.request(Xt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(jn())}let n=await t.transport.request(Xt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return v(jn())}let s=await t.transport.request(Xt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(jn(s.error.httpStatus)):s}i(Rs,"authedSend");function jn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(jn,"authRejectedError");var Ss=`
2
2
 
3
- `,Cp=1048576,Ep=z.record(z.string(),z.unknown()),Rp=["emergency","schedule_soon","home_care"];async function*xr(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",a=0,l=false;for await(let u of e){for(s+=o.decode(u,{stream:true});;){let d=s.indexOf(Xi,a);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+Xi.length),a=0;let p=Qi(c,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Cp){yield de({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let u=Qi(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield de({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(xr,"parseSse");function Qi(e,t){let r=null,n=[];for(let a of e.split(`
3
+ `,Of=1048576,Ff=z.record(z.string(),z.unknown()),Mf=["emergency","schedule_soon","home_care"];async function*Ur(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",a=0,l=false;for await(let u of e){for(s+=o.decode(u,{stream:true});;){let d=s.indexOf(Ss,a);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+Ss.length),a=0;let p=Ts(c,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Of){yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let u=Ts(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ur,"parseSse");function Ts(e,t){let r=null,n=[];for(let a of e.split(`
4
4
  `)){let l=a.replace(/\s+$/,"");l.length===0||l.startsWith(":")||(l.startsWith("id:")?r=l.slice(3).trim():l.startsWith("data:")&&n.push(l.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
5
- `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Ep.safeParse(o);return s.success?Sp(s.data,r,t):null}i(Qi,"parseBlock");function Sp(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return de({code:ae(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ae(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Wi({conversationId:ae(e.conversation_id)??"",messageId:ae(e.message_id),title:ae(e.title),followUpQuestions:kp(e.follow_up_questions),citations:Zi(e.citations),citationStatus:ae(e.citation_status),urgencyLevel:Ji(e.urgency_level),urgencyReason:ae(e.urgency_reason),urgencyProvided:Tp(e),resultId:ae(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return Hi(ae(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return zi(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=ae(e.delta)??ae(e.token)??"";return ji(s,t,r)}return o==="analysis_started"?Gi(ae(e.request_id),t,r):o==="analysis_complete"?Ki({resultId:ae(e.result_id),analysisType:ae(e.analysis_type),modelVersion:ae(e.model_version),confidence:Pp(e.confidence),detections:Zi(e.detections),interpretation:ae(e.interpretation),lastEventId:t},r):qi(e,t,r)}i(Sp,"frameFromWire");function ae(e){return typeof e=="string"?e:null}i(ae,"asString");function Pp(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Pp,"asNumber");function Ji(e){return typeof e=="string"&&Rp.includes(e)?e:null}i(Ji,"asUrgency");function Tp(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ji(t)!==null}i(Tp,"urgencySlotProvided");function kp(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(kp,"asStringList");function xp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(xp,"isPlainObject");function Zi(e){return Array.isArray(e)?e.filter(xp):[]}i(Zi,"asMapList");var _p="0.3.0",wp="react-native",Ip="2026-09-19",es="EVERFUR_API_BASE_URL";function Gt(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(Gt,"configFailure");function Mn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Mn,"checkPublishableKey");function ts(e,t){let r=Mn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=Ap(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||Ip;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:_p,platform:t?.platform??wp,debug:e.debug===true})})}i(ts,"tryResolveClientConfig");function Ap(e){let t=e?.trim(),r=t&&t.length>0?t:Vp(es);return r?Np(r):Gt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${es}. The SDK never ships a hardcoded host.`)}i(Ap,"tryResolveApiBaseUrl");function rs(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(rs,"buildBaseHeaders");var Op=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Fp(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Fp,"hostOf");function Mp(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Mp,"isPrintableHost");function Lp(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Mp(t)}i(Lp,"canEchoOrigin");function Dp(e,t){return `${e}://${t}`}i(Dp,"safeOrigin");function Np(e){let t=e.trim(),r=Op.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Gt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Fp(r[2]);if(o.length===0)return Gt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Lp(t,o)?`: ${Dp(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Up(o)))return n==="http"?Gt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):Gt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let a=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:a})}i(Np,"normalizeBaseUrl");function Up(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Up,"isLoopbackHost");function Vp(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Vp,"readEnv");var Bp=3e4,ss="x-request-id";async function*ns(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(ns,"fetchByteSource");function Hp(e){let t=new TextEncoder,r=jp(),n=false,o=i(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
5
+ `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Ff.safeParse(o);return s.success?Lf(s.data,r,t):null}i(Ts,"parseBlock");function Lf(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return pe({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return hs({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:Uf(e.follow_up_questions),citations:Ps(e.citations),citationStatus:le(e.citation_status),urgencyLevel:ks(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:Nf(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return ms(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return ys(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=le(e.delta)??le(e.token)??"";return gs(s,t,r)}return o==="analysis_started"?bs(le(e.request_id),t,r):o==="analysis_complete"?vs({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:Df(e.confidence),detections:Ps(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):Cs(e,t,r)}i(Lf,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function Df(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Df,"asNumber");function ks(e){return typeof e=="string"&&Mf.includes(e)?e:null}i(ks,"asUrgency");function Nf(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||ks(t)!==null}i(Nf,"urgencySlotProvided");function Uf(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Uf,"asStringList");function Vf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Vf,"isPlainObject");function Ps(e){return Array.isArray(e)?e.filter(Vf):[]}i(Ps,"asMapList");var Hf="0.5.0",Bf="react-native",zf="2026-09-19",xs="EVERFUR_API_BASE_URL";function Qt(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(Qt,"configFailure");function Kn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Kn,"checkPublishableKey");function _s(e,t){let r=Kn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=jf(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||zf;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Hf,platform:t?.platform??Bf,debug:e.debug===true})})}i(_s,"tryResolveClientConfig");function jf(e){let t=e?.trim(),r=t&&t.length>0?t:Qf(xs);return r?Yf(r):Qt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${xs}. The SDK never ships a hardcoded host.`)}i(jf,"tryResolveApiBaseUrl");function ws(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(ws,"buildBaseHeaders");var Wf=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Gf(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Gf,"hostOf");function Kf(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Kf,"isPrintableHost");function qf(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Kf(t)}i(qf,"canEchoOrigin");function $f(e,t){return `${e}://${t}`}i($f,"safeOrigin");function Yf(e){let t=e.trim(),r=Wf.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Qt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Gf(r[2]);if(o.length===0)return Qt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=qf(t,o)?`: ${$f(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Xf(o)))return n==="http"?Qt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):Qt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let a=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:a})}i(Yf,"normalizeBaseUrl");function Xf(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Xf,"isLoopbackHost");function Qf(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Qf,"readEnv");var Zf=3e4,Fs="x-request-id";async function*Is(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Is,"fetchByteSource");function Jf(e){let t=new TextEncoder,r=tm(),n=false,o=i(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
6
6
  `);let c=u.data??"";for(let p of c.split(`
7
7
  `))d+=`data: ${p}
8
8
  `;d+=`
9
- `,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=us(d),p=Be(Ie(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
9
+ `,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=Ds(d),p=He(Ae(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
10
10
 
11
- `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),zp(r.source,l)}i(Hp,"eventSourceByteSource");async function*zp(e,t){try{yield*e;}finally{t();}}i(zp,"sourceWithCleanup");function jp(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(jp,"createByteQueue");async function Wp(e,t){let r=t.fetchImpl??ds(),n=cs(t.config.apiBaseUrl,e.path,e.query),o=ps(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=Xp(Bp),a=Qp(s.signal,e.signal),l;try{l=await r(n,fs({...e,signal:a},o));}catch(d){return v(Ln(d))}finally{s.cancel();}let u=await ms(l);return l.ok?L(u):v(qp(l.status,u,ls(l)))}i(Wp,"requestJson");function as(e){return {request:i(t=>Wp(t,e),"request"),stream:i((t,r)=>Gp(Yp(t,r),e),"stream")}}i(as,"createHttpTransport");async function*Gp(e,t){let r=cs(t.config.apiBaseUrl,e.path,e.query),n=ps(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Kp(e,n));yield*xr(Hp(l),()=>$p(l));return}let o=t.fetchImpl??ds(),s;try{s=await o(r,fs(e,n));}catch(l){yield os("",true,bs(l));return}let a=ls(s);if(!s.ok){let l=await ms(s),u=ys(l)??us(s.status),d=hs(l)||Be(Ie(u));yield os(u,d,gs(l),a);return}if(s.body){yield*xr(ns(s.body),a);return}yield*xr(ns(null),a);}i(Gp,"streamFrames");function Kp(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Kp,"buildEventSourceInit");function qp(e,t,r){let n=ys(t),o=n?Ie(n):Di(e),s=gs(t);return N(o,{httpStatus:e,...hs(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...is(t)?{reasonCode:is(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(qp,"errorFromResponse");function Ln(e){return N("internalError",{retryable:true,wireMessage:bs(e)})}i(Ln,"networkError");function ls(e){let t=e.headers.get(ss);return typeof t=="string"&&t.length>0?t:null}i(ls,"requestIdOf");function $p(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(ss);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i($p,"eventSourceRequestId");function us(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(us,"statusToWireCode");function os(e,t,r,n=null){return de({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(os,"syntheticErrorFrame");function ds(){let e=globalThis.fetch;if(typeof e!="function")throw new $("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(ds,"getGlobalFetch");function cs(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(cs,"buildUrl");function ps(e,t,r,n){let o={...rs(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(ps,"mergeHeaders");function fs(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(fs,"buildInit");function Yp(e,t){return e.signal?e:{...e,signal:t}}i(Yp,"withSignal");function Xp(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(Xp,"timeoutSignal");function Qp(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Qp,"mergeAbortSignals");async function ms(e){try{return await e.json()}catch{return null}}i(ms,"safeJson");function is(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(is,"extractReasonCode");function ys(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(ys,"extractWireCode");function gs(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(gs,"extractWireMessage");function hs(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(hs,"extractRetryable");function bs(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(bs,"describeCause");var Zp=3e4,Jp=In*2,ef="idempotency-key",tf=new Set(["POST","PUT","PATCH","DELETE"]),rf=Object.freeze({onEvent(){}}),nf=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Re(e){let t=e.observer??rf,r=e.timers??nf,n=e.rng??Math.random,o=e.sleep??((f,m)=>hf(f,r,m)),s=e.maxAttempts??jt,a=e.unaryTimeoutMs??Zp,l=e.newIdempotencyKey??sf(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,g){let k=g?.maxAttempts,y=Math.max(1,k??s),T=g?.idempotent??tf.has(m.method)?l():null,O=of(m,T),w=0;for(;;){let b=i(B=>Object.freeze({call:f,method:m.method,path:m.path,attempt:w,...T?{idempotencyKey:T}:{},...B}),"stamp");u(b({phase:"attempt"}));let S=yf(a,r),P=gf(S.signal,m.signal),V;try{V=await Yi({...O,signal:P.signal},e.auth);}catch(B){V=v(Ln(B));}finally{P.dispose(),S.cancel();}if(V.ok)return u(b({phase:"settled",ok:true,reason:"ok"})),V;let I=V.error,A=lf(I,w,{maxAttempts:y,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...k!==void 0?{perCallMaxAttempts:k}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),x={ok:false,code:I.code,reason:A.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!A.retry)return u(b({phase:"settled",...x})),v(I);if(u(b({phase:"retry",...x,delayMs:A.delayMs})),await o(A.delayMs,m.signal),m.signal?.aborted===true)return u(b({phase:"settled",...x,reason:"aborted"})),v(I);w+=1;}}i(d,"send");async function c(f){return Wt(f,await mf(e.auth))}i(c,"authorize");async function*p(f,m,g){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,g);}catch{yield de({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(Re,"createRequestFunnel");function of(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ef&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(of,"assembleHeaders");function sf(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(sf,"defaultIdempotencyKeyFactory");var af=10;function lf(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=uf(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!Be(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(af,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=df(e,r.now);return u!==null?u>Jp?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Tr(t,r.rng)}}i(lf,"decideRetry");function uf(e){let t=e.code==="unknown"?Ie(ff(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(uf,"throttleKind");function df(e,t){let r=cf(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(df,"retryOverrideMs");function cf(e){for(let t of Cs(e)){let r=t.resets_at,n=pf(r);if(n!==null)return n}return null}i(cf,"findResetsAt");function Cs(e){if(!vs(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];vs(n)&&t.push(n);}return t}i(Cs,"candidateScopes");function pf(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(pf,"parseInstantMs");function ff(e){for(let t of Cs(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(ff,"rawWireCode");function vs(e){return typeof e=="object"&&e!==null}i(vs,"isRecord");async function mf(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(mf,"resolveDeviceAuth");function yf(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(yf,"boundedSignal");function gf(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(gf,"mergeSignals");function hf(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(hf,"delayAbortable");var _r=Object.freeze(["better","same","worse"]),Nn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Es(e){return v(N("validationFailed",{retryable:false,wireMessage:e}))}i(Es,"invalid");function Dn(){return v(N("internalError",{retryable:false}))}i(Dn,"malformed");function Rs(e){return typeof e!="string"||e.trim().length===0?N("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Ce(e)?N("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Rs,"petPath");var He=i(e=>typeof e=="string"?e:null,"str");function Ss(e){if(typeof e!="object"||e===null)return null;let t=e,r=He(t.case_id),n=He(t.status);if(r===null||n===null)return null;let o=He(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:He(t.body_location),lastResponse:o!==null&&_r.includes(o)?o:null,checkInDueAt:He(t.check_in_due_at),openedAt:He(t.opened_at),resolvedAt:He(t.resolved_at),resolutionText:He(t.resolution_text)})}i(Ss,"caseFromWire");function Ps(e){return {async list(t,r){let n=Rs(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return Dn();let a=s.map(Ss);return a.every(l=>l!==null)?L(Object.freeze(a)):Dn()},async checkin(t,r,n,o){let s=Rs(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!Nn.test(r))return Es("case_id must be a UUID");if(!_r.includes(n))return Es("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=Ss(l.case);return u===null?Dn():L(Object.freeze({case:u,ctaDeepLink:He(l.cta_deep_link)}))}}}i(Ps,"createCasesRepositoryOver");var Ts=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ks=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Ir(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(Ir,"delayAbortable");function Ar(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Ar,"mergeSignals");var Un=class Un{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Ar(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(Un,"MediaStore");var wr=Un;function Bn(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Bn,"makeUser");function Hn(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(Hn,"makeAssistant");function qt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(qt,"stripPending");function xs(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(xs,"appendText");function zn(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(zn,"finalizeAssistant");function _s(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(_s,"freezeSnapshot");function U(e,t,r){return N(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function jn(e){let t=Ie(e.code);return N(t,{retryable:e.retryable||Pr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(jn,"errorFromFrame");function Ae(e){return de({code:bf(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Ae,"synthErrorFrame");function bf(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return qe(e)}}i(bf,"canonicalWireCode");function ws(e){let t=Array.isArray(e)?e:Vn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!Vn(n))continue;let o=Kt(n.category)??Kt(n.title)??"",s=vf(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(ws,"parsePromptCategories");function Wn(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(Wn,"flattenPrompts");function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Vn,"isPlainObject");function Kt(e){return typeof e=="string"?e:null}i(Kt,"asStr");function vf(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Vn(r)){let n=Kt(r.text)??Kt(r.prompt)??Kt(r.title);n!==null&&t.push(n);}return t}i(vf,"asPromptTextList");function Is(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(Is,"defaultIdFactory");function As(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(As,"defaultIdempotencyFactory");var Fs={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*Ms(e,t,r,n){let o=e[Symbol.asyncIterator](),s=Os(t.overallMs,n),a=Os(t.idleMs,n),l=Rf(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Ef();return}if(d.tag==="idle"||d.tag==="overall"){yield Cf();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(Ms,"withWatchdog");function Cf(){return de({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Cf,"synthTimeoutFrame");function Ef(){return de({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ef,"synthStreamErrorFrame");function Os(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(Os,"deadline");function Rf(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Rf,"abortPromise");var Sf="checkin",Pf=/^\d{4}-\d{2}-\d{2}$/,Or="watching";function Ls(e){return e.status!=null&&e.status!==Or}i(Ls,"isCheckinSettled");function Ds(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Sf||n===void 0||o===void 0||!Nn.test(n)||!Pf.test(o)?null:n}i(Ds,"parseCheckinOriginRef");function Gn(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(N("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Ce(o))return v(N("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),L(r.length?`?${r.join("&")}`:"")}i(Gn,"historyQuery");function Xt(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(Xt,"validConversationId");function Yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Yt,"object");function Ns(e){return e==null||typeof e=="string"&&e.length>0&&!Ce(e)}i(Ns,"cursor");function $t(){return v(N("internalError",{retryable:false}))}i($t,"malformed");function Us(e){let t=Yt(e);if(!t||!Array.isArray(t.conversations)||!Ns(t.next_cursor))return $t();let r=[];for(let n of t.conversations){let o=Yt(n);if(!o||typeof o.conversation_id!="string"||!Xt(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return $t();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return $t();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return L(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Us,"mapConversationPage");function Vs(e){let t=Yt(e);if(!t||!Array.isArray(t.messages)||!Ns(t.next_cursor))return $t();let r=[],n=new Set;for(let o of t.messages){let s=Yt(o);if(!s||typeof s.message_id!="string"||!Xt(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return $t();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?Ds(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Tf(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:kf(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return L(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Vs,"mapMessagePage");function Tf(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Tf,"normalizeUrgency");function kf(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=Yt(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(kf,"historyCitations");var Mr=5,Bs=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Qt=4e3,xf=6e4,_f=18e4,wf=24,If=512,Af=false;function zs(e){return new Kn(e)}i(zs,"createChatController");var qn=class qn extends wr{constructor(r){super(_s({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??Re({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Ps(this.funnel),this.telemetry=r.telemetry??kr,this.errorPolicy=r.errorPolicy??Vi,this.timers=r.timers??Fs,this.rng=r.rng??Math.random,this.newId=r.newId??Is(),this.makeIdempotencyKey=r.makeIdempotencyKey??As(),this.budget={idleMs:r.budget?.idleMs??xf,overallMs:r.budget?.overallMs??_f};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):Fr(Ae(u))}let a=Hs(r)??Of(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):Fr(Ae(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return Fr(Ae(U("accessDenied",false)));let o=Hs(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Fr(Ae(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Mf()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Bn(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?qt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(Wn(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=Gn(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=Us(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?L(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return L(null);let l=await this.resumeConversation(a.id);return l.ok?L(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return L(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),L(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Ce(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Bs.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${Bs.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>Qt)return v(U("validationFailed",false,`notes is over ${Qt} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return L(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null}),d=i(c=>c.checkin?.caseId===r,"carries");return this.snapshot.messages.some(d)&&this.patch({messages:this.snapshot.messages.map(c=>d(c)?Object.freeze({...c,checkin:u}):c)}),l}async getMessages(r,n){if(!Xt(r))return v(U("validationFailed",false));let o=Gn(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?Vs(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!Xt(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),L(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===Or).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId);return Object.freeze({...d,checkin:Object.freeze({...c,status:s.has(c.caseId)?Or:p?.status??"resolved",answer:c.answer??p?.lastResponse??null,resolutionText:c.resolutionText??p?.resolutionText??null})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return L(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),L(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return L(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),L(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Ae(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return L(n);let o=this.snapshot.conversationId;return o!==null?L(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):L(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Ce(o))return v(N("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?L(ws(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=Ar(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Bn(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let y=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;y.ok&&this.snapshot.conversationId===null&&this.adoptConversation(y.value);}if(u&&this.snapshot.conversationId===null){let y=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!y.ok){yield*this.emitTerminal(r,y.error,Ae(y.error));return}this.adoptConversation(y.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let y=U("internalError",!0);yield*this.emitTerminal(r,y,Ae(y));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Ar(o.signal,p.signal),m=null;try{let y;try{y=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let T=this.authRejected();yield*this.emitTerminal(r,T,Ae(T));return}if(o.signal.aborted||!this.alive(o.epoch))return;let R=this.funnel.stream("chat.send",y,f);for await(let T of Ms(R,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(T.kind==="error"&&T.terminal){m=T;break}if(this.applyFrame(T,r),yield T,T.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let y=U("streamIncomplete",!0);yield*this.emitTerminal(r,y,Ae(y));return}let g=Ie(m.code);if(g==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let y=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!y){let R=this.authRejected();yield*this.emitTerminal(r,R,m);return}this.patch({reconnecting:!0});continue}if(g==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let y=this.authRejected();yield*this.emitTerminal(r,y,m);return}if(g==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,jn(m),m);return}if(Ni(g)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let k=m.retryable&&Pr(g,!0);if(Af&&k&&s+1<this.errorPolicy.maxAttempts(g));yield*this.emitTerminal(r,jn(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return qe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?qt(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,Hn(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=If){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},wf);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?xs(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?zn(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?qt(d):d),zn(Hn(l,"",this.stamp()),r)];}let a=Wn([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=Ff(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?qt(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(qn,"ChatControllerImpl");var Kn=qn,Zt=4e3;function Of(e){return e===void 0?null:!Array.isArray(e)||e.length>Mr?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${Mr} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(Of,"validateImageKeys");function Hs(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Zt?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Zt}`)}:null}i(Hs,"validateMessageText");function Ff(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ff,"urgencyTier");async function*Fr(e){yield e;}i(Fr,"singleFrameStream");async function*Mf(){}i(Mf,"emptyStream");async function Gs(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(w=>w.ok?L(o):w):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,g]=await Promise.all([p,f]),k=null;if(m.ok)k=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let w=m.error;c=w,js(w)?(l=true,d=w):(Ws(w)&&(a=true),u=true);}let y=[];g.ok?y=g.value:R(g.error);function R(w){js(w)?(l=true,d===null&&(d=w)):Ws(w)&&(a=true);}i(R,"recordAuthSignals");let T=d!==null?d.displayMessage:null;return Object.freeze({conversationId:k,petRef:n,suggestedPrompts:y,error:T,warning:T===null&&k===null&&u?Lf:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Gs,"bootstrapChat");var Lf="Chat is ready. Your first message will start the conversation.";function js(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(js,"isUnauthorized");function Ws(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ws,"isForbidden");var $n=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ks(e){return e!==$n}i(Ks,"isUploadTransportAvailable");var Df=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Lr=10*1024*1024,Dr=Mr,Jt=120,Nf="/widget/v1/uploads/initiate";function Uf(e){return typeof e=="string"&&Df.includes(e.trim().toLowerCase())}i(Uf,"isAttachmentMime");function Yn(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Jt)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Jt);let n=t.slice(r);return n.length>=Jt?t.slice(0,Jt):`${t.slice(0,r).slice(0,Jt-n.length)}${n}`}i(Yn,"sanitizeFilename");function Xn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Xn,"formatBytes");var er=i(e=>Object.freeze({ok:true,value:e}),"ok"),Se=i(e=>Object.freeze({ok:false,error:e}),"err");function ne(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(ne,"failure");function Vf(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Vf,"attachmentSize");function Bf(e){let t=Yn(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Uf(r))return Se(ne("unsupported_type",false,t));let n=Vf(e);return n===null?Se(ne("unknown",false,t)):n>Lr?Se(ne("too_large",false,t,{sizeBytes:n})):er(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Bf,"validateAttachment");function Hf(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),a=r(t.s3_key);if(o===null||s===null||a===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Lr,s3_key:a,purpose:r(t.purpose)})}i(Hf,"parsePolicy");function zf(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return ne("quota_exceeded",false,t,{cause:e});case "rateLimited":return ne("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return ne("idempotency_conflict",true,t,{cause:e});case "validationFailed":return ne("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return ne("network",true,t,{cause:e});default:return r===429?ne("rate_limited",true,t,{cause:e}):r===503?ne("network",true,t,{cause:e}):r===void 0?ne("network",true,t,{cause:e}):ne("server",e.retryable,t,{httpStatus:r,cause:e})}}i(zf,"initiateFailure");async function jf(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Nf,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Se(zf(n.error,t.filename));let o=Hf(n.value);return o===null?Se(ne("server",false,t.filename)):er(o)}i(jf,"initiateAttachmentUpload");async function Wf(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return Se(ne("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),er(void 0)}catch{return o()?Se(ne("cancelled",true,r.filename)):Se(ne("server",true,r.filename))}}i(Wf,"uploadAttachmentBytes");var Gf=2,Kf=3,qf=Object.freeze([1e3,2e3,4e3]),qs=0;function $f(){return qs+=1,`attachment-${qs}`}i($f,"defaultNewId");function $s(e){let t=Math.max(1,e.concurrency??Gf),r=Math.max(1,e.maxAttempts??Kf),n=e.backoffMs??qf,o=Math.max(1,e.maxPerMessage??Dr),s=e.timers??ks,a=e.newId??$f,l=Ks(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),g=false,k=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let S=u.get(b);return S===void 0?[]:[S.state]}))});for(let b of f)b();},"publish"),y=i((b,S)=>{b.state=Object.freeze({...b.state,...S}),k();},"patch"),R=i(()=>{for(;!g&&p.size<t&&c.length>0;){let b=c.shift(),S=u.get(b);S!==void 0&&(p.add(b),T(S).finally(()=>{p.delete(b),R();}));}},"pump"),T=i(async b=>{let{attachment:S}=b;for(;b.attempts<r;){if(g||b.controller.signal.aborted)return;b.attempts+=1;let P=b.controller.signal;y(b,{status:"uploading",error:null,progress:0});let V=await jf(e.funnel,S,{signal:P});if(g||P.aborted)return;let I;if(!V.ok)I=Se(V.error);else {let re=await Wf(e.transport,V.value,S,{signal:P,onProgress:i(j=>{!P.aborted&&b.state.status==="uploading"&&y(b,{progress:Yf(j)});},"onProgress")});if(g||P.aborted)return;I=re.ok?er(V.value.s3_key):Se(re.error);}if(I.ok){y(b,{status:"uploaded",s3Key:I.value,error:null,progress:1});return}let A=I.error,x=A.retryable&&b.attempts<r;if(y(b,{status:x?"uploading":"failed",error:A,progress:0}),!x)return;let B=n[Math.min(b.attempts-1,n.length-1)]??0;await Ir(B,P,s);}},"run"),O=i(b=>{c.push(b.state.id),R();},"enqueue"),w={available:l,subscribe(b){return f.add(b),()=>{f.delete(b);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(b=>b.status==="uploading")},get s3Keys(){return m.attachments.flatMap(b=>b.status==="uploaded"&&b.s3Key!==null?[b.s3Key]:[])},add(b){let S=Bf(b);if(!S.ok)return S;if(g||d.length>=o)return Se(ne("too_many",false,S.value.filename));let P=a(),V={attachment:S.value,controller:new AbortController,attempts:0,state:Object.freeze({id:P,filename:S.value.filename,previewUri:b.uri,contentType:S.value.contentType,sizeBytes:S.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(P,V),d.push(P),k(),O(V),er(V.state)},retry(b){let S=u.get(b);S===void 0||g||S.state.status!=="failed"||(S.controller=new AbortController,S.attempts=0,y(S,{status:"uploading",error:null,progress:0,s3Key:null}),O(S));},remove(b){let S=u.get(b);if(S===void 0)return;S.controller.abort(),u.delete(b);let P=d.indexOf(b);P>=0&&d.splice(P,1);let V=c.indexOf(b);V>=0&&c.splice(V,1),k();},clear(){for(let b of [...d])w.remove(b);},dispose(){g=true;for(let b of u.values())b.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return w}i($s,"createAttachmentQueue");function Yf(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Yf,"clamp");var Ys=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function tr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Ys,t)?Ys[t]:null}i(tr,"canonicalPetSpecies");var Xs=50,Xf=128,Qn=120,Qs=120,Qf=2e3,Zs=120,Zf=80,ta=new Set(["male","female","unknown"]),ra=new Set(["day","month","year"]),na=new Set(["low","medium","high","athletic"]),oa=new Set(["indoor","outdoor","both"]),ia=new Set(["mild","moderate","severe"]),Jf=/^(\d{4})-(\d{2})-(\d{2})$/,sa=[["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"]],aa=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...sa,...aa].map(([e])=>e));function em(e){let t=Jf.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(em,"isRealDate");var nr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),tm=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Ur=i((e,t)=>typeof t=="string"&&em(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Oe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Ce(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=ot(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),rm={sex:nr(ta),spayedNeutered:tm,birthDate:Ur,birthDatePrecision:nr(ra),activityLevel:nr(na),indoorOutdoor:nr(oa),foodBrand:Oe(Zs),foodType:Oe(Zs),microchipId:Oe(Zf)},Zn=["ref","ref",false,Oe(Xf,{required:true,trimmed:true})],Jn=["notes","notes",false,Oe(Qf,{trimmed:true})],Js=[Zn,["name","name",true,Oe(Qn,{required:true,trimmed:true})],["dose","dose",false,Oe(Qs,{trimmed:true})],["frequency","frequency",false,Oe(Qs,{trimmed:true})],["startDate","start_date",false,Ur],["endDate","end_date",false,Ur],Jn],nm={allergies:[Zn,["allergen","allergen",true,Oe(Qn,{required:true,trimmed:true})],["severity","severity",false,nr(ia)],Jn],medications:Js,supplements:Js,conditions:[Zn,["conditionName","condition_name",true,Oe(Qn,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ur],Jn]};function om(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[u,d,c,p]of nm[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};s[d]=f;}let a=s.start_date,l=s.end_date;return typeof a=="string"&&typeof l=="string"&&l<a?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(om,"itemToWire");function im(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Xs)return {error:`${e} has ${t.length} items; the server accepts at most ${Xs}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=om(e,o,t[o]);if("error"in s)return s;let a=s.item.ref;if(typeof a=="string"){let l=a.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(s.item);}return {items:r}}i(im,"listToWire");function la(e,t){let r=e,n={};for(let[a,l]of sa){let u=r[a];if(u!==void 0){if(u!==null){let d=rm[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[a,l]of aa){let u=r[a];if(u===void 0)continue;let d=im(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&tr(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(la,"petHealthToWire");var J=i(e=>typeof e=="string"?e:null,"str"),rr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),sm=i(e=>typeof e=="boolean"?e:null,"bool");function Nr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Nr,"itemsFromWire");function ea(e){let t=J(e.name);return t===null||t.length===0?null:Object.freeze({ref:J(e.ref),name:t,dose:J(e.dose),frequency:J(e.frequency),startDate:J(e.start_date),endDate:J(e.end_date),notes:J(e.notes)})}i(ea,"medicationFromWire");function ua(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:rr(ta,e.sex),spayedNeutered:sm(e.spayed_neutered),birthDate:J(e.birth_date),birthDatePrecision:rr(ra,e.birth_date_precision),activityLevel:rr(na,e.activity_level),indoorOutdoor:rr(oa,e.indoor_outdoor),foodBrand:J(e.food_brand),foodType:J(e.food_type),microchipId:J(e.microchip_id),allergies:Nr(e.allergies,r=>{let n=J(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:J(r.ref),allergen:n,severity:rr(ia,r.severity),notes:J(r.notes)})}),medications:Nr(e.medications,ea),supplements:Nr(e.supplements,ea),conditions:Nr(e.conditions,r=>{let n=J(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:J(r.ref),conditionName:n,diagnosedDate:J(r.diagnosed_date),notes:J(r.notes)})})})}i(ua,"petHealthFromWire");var pa=100,fa=50,ma=100,ya=50,ga=500,am=128,lm=6e4;function Me(e){return N("validationFailed",{retryable:false,wireMessage:e})}i(Me,"invalid");function it(e,t,r){if(typeof t!="string")return Me(`${e} must be a string`);let n=ot(t);return n<=r?null:Me(`${e} is ${n} characters; the server accepts at most ${r}`)}i(it,"checkString");function Vr(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Me(`${e} must be a finite number between 0 and ${r}`)}i(Vr,"outOfRange");function da(e,t){if(typeof e!="string")return Me("pet_ref must be a string");if(e.trim().length===0)return Me("pet_ref must not be blank");if(Ce(e))return Me("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Me("profile must be an object");let r=[it("pet_ref",e,am)];return t?.name!==void 0&&r.push(it("name",t.name,pa)),t?.species!==void 0&&r.push(it("species",t.species,fa)),t?.breed!==void 0&&r.push(it("breed",t.breed,ma)),t?.ageYears!==void 0&&r.push(Vr("age_years",t.ageYears,ya)),t?.weightKg!==void 0&&r.push(Vr("weight_kg",t.weightKg,ga)),r.find(n=>n!==null)??null}i(da,"validate");function ha(e,t){let r=la(e,t);return "error"in r?{error:Me(r.error)}:r}i(ha,"healthToWire");function um(e){if(typeof e!="object"||e===null)return {error:Me("patch must be an object")};let t=e,r=[["name","name",s=>it("name",s,pa)],["species","species",s=>it("species",s,fa)],["breed","breed",s=>it("breed",s,ma)],["ageYears","age_years",s=>Vr("age_years",s,ya)],["weightKg","weight_kg",s=>Vr("weight_kg",s,ga)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=ha(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Me("patch must change at least one field")}:{body:n})}i(um,"patchToWire");function dm(e){if(e==null)return {body:{}};let t=ha(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(dm,"toWire");var Fe=i(e=>typeof e=="string"?e:null,"str"),Br=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function ca(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Fe(r.pet_ref)??t,name:Fe(r.name),species:Fe(r.species),breed:Fe(r.breed),ageYears:Br(r.age_years),weightKg:Br(r.weight_kg)})}i(ca,"fromWire");function ba(e){if(typeof e!="object"||e===null)return null;let t=e,r=Fe(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Fe(t.pet_id),petRef:r,name:Fe(t.name),species:Fe(t.species),breed:Fe(t.breed),ageYears:Br(t.age_years),weightKg:Br(t.weight_kg),updatedAt:Fe(t.updated_at)})}i(ba,"widgetPetFromWire");function cm(e){let t=ba(e);return t===null?null:Object.freeze({...t,...ua(e)})}i(cm,"widgetPetProfileFromWire");function pm(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=ba(r);return n===null?[]:[n]}))}i(pm,"petListFromWire");function $e(e){return fm(Re({auth:e}),Re({auth:e,unaryTimeoutMs:lm}))}i($e,"createPetsRepository");function fm(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>da(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?L(pm(s.value)):v(s.error)},async registerPet(o,s,a){let l=da(o,s);if(l!==null)return v(l);let u=dm(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?L(ca(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=um(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?L(ca(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=cm(l.value);return u===null?v(N("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):L(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?L(void 0):v(l.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?L(void 0):v(s.error)}}}i(fm,"createPetsRepositoryOver");var to=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function mm(e){return to[e]}i(mm,"requires");function va(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(to))for(let a of to[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(va,"deniedDecisionsFor");function Ca(e,t,r){let n=mm(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return eo({name:e,enabled:false,isPending:true,limits:{}});let s=ym(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?eo({name:e,enabled:true,isPending:false,limits:s}):eo({name:e,enabled:false,isPending:false,limits:s,disabled:gm(n,o)})}i(Ca,"decideCapability");function ym(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[s,a]of Object.entries(o)){let l=r[s];r[s]=l===void 0?a:Math.min(l,a);}}return r}i(ym,"mergeLimits");function gm(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:xt("accessDenied"),level:"user_entitlement",recoverable:false})}i(gm,"disabledFor");function eo(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(eo,"freezeDecision");function ge(e){let t=le(e);return t===null?null:bm(t)}i(ge,"parseColor");function le(e){if(typeof e=="number")return Ea(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return ro(t.slice(1));if(t.toLowerCase().startsWith("0x"))return ro(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return hm(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=ro(t);if(r!==null)return r}return /^\d+$/.test(t)?Ea(Number.parseInt(t,10)):null}i(le,"toRgba");function ro(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:no(t[0]),g:no(t[1]),b:no(t[2]),a:1};if(t.length===6)return {r:st(t,0),g:st(t,2),b:st(t,4),a:1};if(t.length===8){let r=st(t,0);return {r:st(t,2),g:st(t,4),b:st(t,6),a:r/255}}return null}i(ro,"fromHex");function hm(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=oo(Number(n[0])),s=oo(Number(n[1])),a=oo(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(hm,"fromRgbFunc");function Ea(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(Ea,"argbIntToRgba");function st(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(st,"byte");function no(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(no,"dup");function oo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(oo,"clampByte");function bm(e){if(e.a>=1)return lt(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(bm,"normalizeRgba");function lt(e,t,r){return `#${io(e)}${io(t)}${io(r)}`.toUpperCase()}i(lt,"rgbToHex");function io(e){return e.toString(16).padStart(2,"0")}i(io,"hex2");var vm="#111111",_t="#FFFFFF",Hr="#000000";function Sa(e){let t=le(e);if(t===null)return _t;let r=at(t),n=at({r:17,g:17,b:17}),o=at({r:255,g:255,b:255});return lo(r,o)>=lo(r,n)?_t:vm}i(Sa,"readableOn");function or(e,t){let r=Sa(e);return ue(r,e)>=t?r:ue(_t,e)>=ue(Hr,e)?_t:Hr}i(or,"legibleOn");function ir(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(_t)>=t(Hr)?_t:Hr}i(ir,"poleForGrounds");function at(e){let t=so(e.r/255),r=so(e.g/255),n=so(e.b/255);return .2126*t+.7152*r+.0722*n}i(at,"relativeLuminance");function so(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(so,"linearize");function lo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(lo,"luminanceContrast");function ue(e,t){let r=le(e),n=le(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:Pa(r,o);return lo(at(s),at(o))}i(ue,"contrastRatio");function Pa(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(Pa,"composite");function ut(e,t){let r=le(e),n=le(t);if(r===null||n===null)return null;let o=r.a>=1?r:Pa(r,{...n});return lt(o.r,o.g,o.b)}i(ut,"flattenOnto");var Ra=.05;function dt(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(le(e)===null)return r;if(s(e))return e;let a=ut(e,o),l=a===null?null:le(a),u=le(r);if(l===null||u===null)return r;for(let d=1;d<1/Ra;d+=1){let c=d*Ra,p=i((m,g)=>Math.round(m+(g-m)*c),"mix"),f=lt(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(dt,"pushToContrast");function Ta(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(Ta,"rgbToHsl");function uo(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:ao(c+l),g:ao(p+l),b:ao(f+l)}}i(uo,"hslToRgb");function ao(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(ao,"channel");function ze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ze(e[t]);}return e}i(ze,"deepFreeze");var jr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),xa={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},_a={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ka={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Cm={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Em={regular:"400",medium:"500",bold:"700"},Rm={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},co=0,ct="System",Le="monospace",Sm=["content","heading","control","compact","badge"];function Pm(e){let t={};for(let r of Sm)t[r]=e;return t}i(Pm,"authoredTierSizes");function wa(){return {family:ct,mono:Le,fontUrl:null,families:{regular:ct,medium:ct,bold:ct,mono:Le,monoMedium:Le,monoBold:Le},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ka,tierSizes:Pm(ka),lineHeight:Cm,weight:Em,letterSpacing:Rm,scale:1,maxScale:co,scaleCaps:jr}}i(wa,"baseType");var Ia={},pt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function zr(e){return `cubic-bezier(${e.join(", ")})`}i(zr,"cssCubicBezier");var Aa={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:zr(pt.standard),emphasized:zr(pt.emphasized),exit:zr(pt.exit)},reducedMotion:false},Tm={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:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",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:"#B91C1C",errorRed:"#FF1B00",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(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ft=ze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Tm,space:xa,radius:_a,type:wa(),motion:Aa,slots:Ia}),km={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:"#9A938C",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",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",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Wr=ze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:km,space:xa,radius:_a,type:wa(),motion:Aa,slots:Ia});var xm="#23272C",Oa=4.5,_m=.6,po=.9,wm=.02,Im="#FFFFFF",Am="#111111";function Om(e){return ue(e,xm)>=Oa&&Math.max(ue(e,Im),ue(e,Am))>=Oa}i(Om,"readsOnDark");function La(e){let t=le(e);if(t===null)return null;let{h:r,s:n,l:o}=Ta(t.r,t.g,t.b),s=Math.min(Math.max(o,_m),po);for(let l=0;;l+=1){let u=s+l*wm;if(u>po)break;let d=uo({h:r,s:n,l:u}),c=lt(d.r,d.g,d.b);if(Om(c))return c}let a=uo({h:r,s:n,l:po});return lt(a.r,a.g,a.b)}i(La,"deriveDarkVariant");var Fm=7,Fa=.05,Mm="#000000",Lm="#FFFFFF";function Dm(e,t,r,n){let o=ut(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let s=le(o),a=le(r);if(s===null||a===null)return r;for(let l=1;l<1/Fa;l+=1){let u=l*Fa,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=lt(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(ue(c,t)>=n)return c}return r}i(Dm,"pushContrast");function Nm(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=Ma(n);for(let s of r){let a=Ma(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(Nm,"hardestGround");function Ma(e){let t=le(e);return t===null?0:at(t)}i(Ma,"luminanceOf");function Ye(e,t){return ut(e,t)??ge(e)??t}i(Ye,"solid");function Da(e){let t=e.color,r=e.brightness==="dark",n=r?Lm:Mm,o=Nm(t,r),s=i(l=>Dm(l,o,n,Fm),"text"),a={...t,brandSoft:Ye(t.brandSoft,t.surface),brandSofter:Ye(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:Ye(t.badgeBgPositive,t.surface),badgeBgCaution:Ye(t.badgeBgCaution,t.surface),badgeBgCritical:Ye(t.badgeBgCritical,t.surface),badgeBgNeutral:Ye(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Ye(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Ye(t.checkupCardConcernBg,t.surface)};return ze({...e,highContrast:true,color:a})}i(Da,"deriveHighContrast");var wt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),Um=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Pe=4.5,Vm=Object.freeze({});function Bm(e){return wt.includes(e)}i(Bm,"isSlotName");function Hm(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Hm,"parseRadius");function Na(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Bm(n)||o===null||typeof o!="object")continue;let s=zm(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(Na,"parseThemeSlots");function Gr(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Gr,"pick");function zm(e){let t={},r=ge(Gr(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ge(Gr(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Hm(Gr(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ge(Gr(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(zm,"parseSlot");function Ua(e,t){return t===null||Object.keys(t).length===0?e??Vm:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(Ua,"mergeThemeSlots");var jm=3;function Wm(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>ut(e,r)??r)}i(Wm,"seatsOf");function Gm(e,t){let r=ir(e);return e.every(n=>ue(r,n)>=t)}i(Gm,"someInkReads");function Km(e,t){let r=t[0];return r===void 0?null:ut(e,r)}i(Km,"collapseUnsatisfiableFill");function qm(e){let t=or(e[0],Pe);return e.every(r=>ue(t,r)>=Pe)?t:ir(e)}i(qm,"inkFor");function Va(e,t){let r=false,n={};for(let o of wt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=Wm(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!Gm(u,Pe)){let p=Km(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>ue(p,f)<Pe))&&(d.textColor=qm(u),c=true);else if(p!==void 0){let f=dt(p,u,ir(u),Pe);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=dt(s.borderColor,u,ir(u),jm);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(Va,"guardSlotContrast");var $m=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),Kr="slots.",Ym=Object.freeze([1,2]);function mo(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(mo,"isEmptyBranding");function Xm(e){let t=e?.schemaVersion??null;return t===null||Ym.includes(t)}i(Xm,"isKnownBrandingSchema");function Qm(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Qm,"lockedFieldsOf");function Zm(e){return e==="hide_powered_by"||$m.includes(e)?true:e.startsWith(Kr)&&wt.includes(e.slice(Kr.length))}i(Zm,"isThemeLockName");function Xe(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:mt(G(t,"display_name","displayName")),logoUrl:mt(G(t,"logo_url","logoUrl")),primaryColor:ge(G(t,"primary_color","primaryColor")),accentColor:ge(G(t,"accent_color","accentColor")),brightness:ry(G(t,"brightness","color_scheme","colorScheme")),fontFamily:mt(G(t,"font_family","fontFamily")),fontUrl:mt(G(t,"font_url","fontUrl")),fonts:Ba(G(t,"fonts")),fontUrls:Ba(G(t,"font_urls","fontUrls")),placeholder:mt(G(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Jm(G(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ge(G(t,"primary_color_dark","primaryColorDark")),accentColorDark:ge(G(t,"accent_color_dark","accentColorDark")),surfaceStyle:Ha(G(t,"surface_style","surfaceStyle"),ey),radiusScale:Ha(G(t,"radius_scale","radiusScale"),ty),logoUrlDark:mt(G(t,"logo_url_dark","logoUrlDark")),slots:Na(G(t,"slots")),accessibilityMaxFontScale:iy(G(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:ay(G(t,"locked_fields","lockedFields")),schemaVersion:sy(G(t,"schema_version","schemaVersion"))};return mo(r)?null:Object.freeze(r)}i(Xe,"parseClientBranding");function Jm(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Jm,"parseBool");function G(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(G,"pick");function mt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(mt,"parseNonEmptyString");var qr=["regular","medium","bold","mono","monoMedium","monoBold"];function Ba(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of qr){let o=mt(G(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Ba,"parseFaceMap");var ey=["white","cream","subtle"],ty=["sharp","default","round"];function Ha(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(Ha,"parseEnum");function ry(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(ry,"parseBrightness");function qa(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(qa,"parseNumber");var ny=1,oy=3.1;function iy(e){let t=qa(e);return t===null?null:t<=0?0:Math.min(oy,Math.max(ny,t))}i(iy,"parseMaxFontScale");function sy(e){if(e==null)return null;let t=qa(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(sy,"parseSchemaVersion");function $a(e){let t=e.trim();return t.startsWith(Kr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i($a,"toWireName");function ay(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=$a(r);Zm(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(ay,"parseLockedFields");function za(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(za,"hardenHttpsUrl");function ja(e,t){if(t===null||mo(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Wr:ft:e,n=r.brightness==="dark"?Wr:ft,o=r.brightness==="dark",s=o?t.primaryColorDark??Wa(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??Wa(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&py(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?le(c):null,f=i(k=>Math.round(k+(255-k)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?fy(n,r.color.text):{},g={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...cy(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:yy(t.radiusScale??null,r.radius,n),type:{...r.type,...dy(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:Ua(r.slots,t.slots??null)};return ze(g)}i(ja,"withServerBranding");var ly={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},uy=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function fo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(fo,"isMonoFace");function dy(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of qr){let u=ly[l].map(p=>r[p]).find(p=>p!==void 0),d=fo(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of uy)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(dy,"mergeFaces");function Wa(e){return e===null?null:La(e)}i(Wa,"darkVariantOf");function cy(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(cy,"surfaceOf");function Ga(e,t){return e==null?false:ge(e)===ge(t)}i(Ga,"sameColor");function py(e,t,r,n){return Ga(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Ga(e.primaryColor,ft.color.primary)}i(py,"isCompiledPrimary");function fy(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(fy,"compiledBrandFamily");var my={sharp:.5,default:1,round:1.5};function yy(e,t,r){if(e===null)return t;let n=my[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(yy,"radiusOf");var gy="Everfur",hy=.5;function yo(e){let t=e?.branding??null,r=Xm(t)?t:null,n=Ry(e?.clientOverride??null,Qm(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=ja((s==="auto"?o:s)==="dark"?Wr:ft,Ka(r)),d=ja(u,Ka(n));return Fy(d,e)}i(yo,"resolveTheme");function by(e,t,r){return yo({...r,branding:Xe(t),clientOverride:Xe(e)})}i(by,"previewTheme");function vy(e){return e==="placeholder"?"chat_placeholder":$a(e)}i(vy,"wireNameOf");var Cy={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Ey(e,t){return t.has(vy(e))?true:(Cy[e]??[]).some(r=>t.has(r))}i(Ey,"isLocked");function Ry(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Ey(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of wt){let d=o[u];d!==void 0&&(t.has(`${Kr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return mo(s)?null:s}i(Ry,"withoutFields");function Ka(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(Ka,"withoutBrightness");function Sy(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(Sy,"scaledSizes");function Py(e){return e===void 0||!Number.isFinite(e)?1:Math.max(hy,e)}i(Py,"effectiveScale");var Ya=["content","heading","control","compact","badge"];function Ty(e){if(!(e>0))return jr;let t={};for(let r of Ya){let n=jr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(Ty,"tierCaps");function ky(e,t){return t>0?Math.min(e,t):e}i(ky,"capped");function xy(e,t,r,n){let o={};for(let s of Ya)o[s]=n?Sy(e,ky(t,r[s])):e;return o}i(xy,"sizesByTier");function _y(e){return e==="dark"?"#FFFFFF":"#000000"}i(_y,"inkPole");function wy(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(wy,"textGrounds");function Xa(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Xa,"linkGrounds");function Iy(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Xa(e)}}i(Iy,"slotGrounds");function Ay(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Ay,"registration");function Oy(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of qr)!(o[a]===ct||o[a]===Le)&&r!==void 0&&Ay(r,o[a])===false&&(o[a]=fo(a)?Le:ct,s[a]=false),n!==null&&fo(a)&&o[a]===Le&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Oy,"platformFaces");function Fy(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?gy:e.meta.displayName,s=za(e.meta.logoUrl),a={};for(let O of qr){let w=e.type.fontUrls[O];w!==void 0&&(a[O]=za(w));}let l=a.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:co,p=Py(t?.textScale),f=Ty(c),m=xy(e.type.size,p,f,t?.scaleTypeSizes===true),g=e.color,k=_y(e.brightness),y=wy(g),R={...g,primary:r,accent:n,onPrimary:or(r,Pe),onAccent:or(n,Pe),brandInk:dt(g.brandInk,y,k,Pe),linkInk:dt(e.slots.link?.textColor??n,Xa(g),k,Pe),text:{...g.text,secondary:dt(g.text.secondary,y,k,Pe)}},T={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:R,space:e.space,radius:e.radius,type:{...e.type,...Oy(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:Va(e.slots,Iy(R))};return t?.highContrast===true?Da(ze(T)):ze(T)}i(Fy,"finalize");var Qa="/widget/v1/entitlements",My=304,Ly=Object.freeze({kind:"notModified"});async function Ja(e,t={},r=Re({auth:e})){let n=await r.send("entitlements.fetch",Ny(t));return n.ok?Uy(n.value):n.error.httpStatus===My?Ly:{kind:"failed",error:n.error}}i(Ja,"fetchEntitlements");var Dy=64;function Ny(e){let t={};return go(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Dy?{method:"GET",path:Qa,headers:t,query:{region:e.region}}:{method:"GET",path:Qa,headers:t}}i(Ny,"buildRequest");function Uy(e){if(e===null||typeof e!="object"||!go(e.revision))return Za();let t=typeof e.region=="string"?e.region:"",r=go(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:By(e.capabilities),branding:Vy(e)})}i(Uy,"parseUpdated");function Vy(e){let t=Xe(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Xe(r.branding);return n!==null?n:Xe(r)}return null}i(Vy,"parseBranding");function By(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Hy(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(By,"mapCapabilities");function Hy(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Hy,"isEnabled");function Za(){return {kind:"failed",error:N("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Za,"malformed");function go(e){return typeof e=="number"&&Number.isFinite(e)}i(go,"isFiniteNumber");var zy=30;function el(e){let t=e.scheduler??jy,r=e.resolve??Ja,n=Math.max(1,e.floorSeconds??zy),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(R=>{l||!a||(c=Math.max(n,R),u=t.set(()=>{u=null,y();},c*1e3));},"schedule"),g=null,k=i(async()=>{if(l)return null;let R=p;e.onFetch?.();let T=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},O;try{O=await r(e.authFor(),T);}catch(w){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Wy(w)}),!l&&R===p&&(e.onSettled?.(),m(s())),null}if(l||R!==p)return null;switch(O.kind){case "updated":d=O.revision,e.update(O.decisions,O.branding??null),m(O.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:O.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),O},"tick"),y=i(()=>{let R=k().finally(()=>{g===R&&(g=null);});return g=R,R},"run");return {start(){a||l||(a=true,y());},prime(){return l?Promise.resolve(null):g??y()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),y());}}}i(el,"createEntitlementPoller");var jy={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Wy(e){return e instanceof Error?e.message:"poll failed"}i(Wy,"describe");var tl="everfur.notifications.device";function Gy(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Gy,"compiledDefaultDecisions");function rl(e=Gy){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(rl,"createEntitlementStore");function al(e,t){return new bo(e,t)}i(al,"createEverfurRuntime");var Ky=6e4,nl=Object.freeze([tl]),vo=class vo{constructor(t,r){this.sessionId=On();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new $("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?$y(n.telemetry):kr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Mn(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=sl(s);else if(n.transport!==void 0)l=n.transport;else {let c=qy(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=as({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=sl(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Yy(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Bi,this.upload=n.upload??Ts,this.uploadTransport=n.uploadTransport??$n,this.imageCache=n.imageCache??Qy,this.kv=n.storage??Xy(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?rl():rl(()=>va("sdk_config",xt("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",ho(c),()=>this.buildChatController(c),ol),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${ho(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=$i(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Ky,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return el({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=zs({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Gs(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.startBeforeLogoutHooks(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=On(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await this.sweepPerUserKv();}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}startBeforeLogoutHooks(){let t=this.currentUser,r=this.identity;if(t===null||r===null||this.beforeLogoutHooks.size===0)return null;let n=Object.freeze({userRef:t.userRef,auth:this.graceAuth(t,r)}),o=[...this.beforeLogoutHooks].map(l=>{try{return Promise.resolve(l(n))}catch(u){return Promise.reject(u)}}),s=i((l,u)=>{try{this.telemetry.track("sdk.logout.hookFailed",{reason:l,count:u,totalCount:o.length});}catch{}},"report"),a=Promise.allSettled(o).then(l=>{let u=l.filter(d=>d.status==="rejected").length;u>0&&s("failed",u);});return new Promise(l=>{let u=false,d=i(()=>{u||(u=true,clearTimeout(c),l());},"finish"),c=setTimeout(()=>{u||s("timeout",o.length),d();},3e3);a.then(d,d);})}graceAuth(t,r){let n=r.currentToken();n.catch(()=>{});let o={userRef:t.userRef,currentToken:i(()=>n,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:this.transport,identity:o,userRef:t.userRef,sessionId:this.leavingSessionId??this.sessionId}}async sweepPerUserKv(){if(nl.length===0)return;let t=await Promise.allSettled(nl.map(n=>this.kv.removeItem(n))),r=t.filter(n=>n.status==="rejected").length;r>0&&this.telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:r,totalCount:t.length});}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v(il(t)):r($e(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?il("prepare"):n===null?null:ll(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?L(void 0):s.currentToken().then(()=>L(void 0),()=>v(N("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):L(void 0):v(N("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",ho(r),()=>this.buildChatController(r),ol,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):L(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(vo,"EverfurRuntimeImpl");var bo=vo;function ho(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(ho,"chatScopeKey");function ol(e){e.dispose();}i(ol,"disposeChat");function il(e){return N("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(il,"disposedError");function ll(e){return N("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(ll,"notConfiguredError");function qy(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return ts(r,t===void 0?void 0:{platform:t})}i(qy,"tryResolveClient");function $y(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i($y,"guardTelemetry");function Yy(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
- [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(Yy,"reportConfigFailure");function sl(e){return Object.freeze({request(){return Promise.resolve(v(ll(e)))},stream(t,r){let n=de({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(sl,"refusingTransport");function Xy(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Xy,"createInMemoryKv");var Qy=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});var ul=Symbol.for("@everfur/sdk#EverfurContext@v1"),dl=globalThis,$r=dl[ul]??(dl[ul]=createContext(null));$r.displayName??="EverfurContext";function q(){let e=useContext($r);if(e===null)throw new $("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(q,"useEverfurContext");function cl(){return q().handle}i(cl,"useEverfur");var pl=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),fl=globalThis,sr=fl[pl]??(fl[pl]=createContext(ft));sr.displayName??="EverfurThemeContext";function M(){return useContext(sr)}i(M,"useEverfurTheme");function Yr(e){let{runtime:t}=q(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?og(e.clientTheme):"",f=useMemo(()=>e.clientTheme?Xe(e.clientTheme):null,[p]),m=n.branding??null,g=useMemo(()=>yo({branding:m,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(g),createElement(sr.Provider,{value:g},e.children)}i(Yr,"EverfurThemeProviderCore");function og(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(og,"stableKey");function bl(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=useRef(null),c=useRef(null),[p,f]=useReducer(x=>x+1,0),m=useRef(null),g=useRef(void 0),k=r?.userRef??null;g.current!==k&&(g.current!==void 0&&(m.current=null),g.current=k);let y=m.current!==null?m.current.user:r??null,R=useRef(null),T=useRef(void 0),O=n??null;T.current!==O&&(T.current!==void 0&&(R.current=null),T.current=O);let w=R.current!==null?R.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:al({config:l.withDefaults?l.withDefaults(t):t,user:y,activePet:w,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,S=useRef(null);useEffect(()=>{let x=d.current?.runtime;x===void 0||!x.isDisposed||S.current!==x&&(S.current=x,f());}),useEffect(()=>{let x=c.current;x!==null&&(c.current=null,x.dispose());});let P=y?.userRef??null;useLayoutEffect(()=>{b.setUser(y);},[b,P]),useLayoutEffect(()=>{b.setActivePet(w);},[b,w]),useEffect(()=>()=>b.dispose(),[b]),useEffect(()=>{s==="onMount"&&b.prepare(w===null?{}:{petRef:w});},[b,s,P,w]);let V=useMemo(()=>({setUser:i(x=>{m.current={user:x},b.setUser(x),f();},"setUser"),setActivePet:i(x=>{R.current={pet:x},b.setActivePet(x),f();},"setActivePet"),open:i(x=>b.open(x),"open"),prepare:i(x=>b.prepare(x),"prepare"),registerPet:i((x,B)=>b.registerPet(x,B),"registerPet"),updatePet:i((x,B)=>b.updatePet(x,B),"updatePet"),deletePet:i(x=>b.deletePet(x),"deletePet"),eraseUserData:i(()=>b.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let x=b.logout();return f(),x},"logout")}),[b,f]),I=useMemo(()=>({runtime:b,handle:V,userRef:P,activePet:w,scopeEpoch:b.scopeEpoch}),[b,V,P,w,p]),A=createElement(Yr,{clientTheme:o??null,seams:l.theme,children:a});return createElement($r.Provider,{value:I},l.wrap?l.wrap(A):A)}i(bl,"EverfurProviderCore");var ag=2;function lg(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<ag)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(lg,"readEventSourceResponseHeader");function vl(){let e=sg;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>lg(n,o),"getResponseHeader")})}}i(vl,"createRnEventSourceFactory");function pg(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(pg,"useRnColorScheme");function fg(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(fg,"isThenable");function mg(){let[e,t]=useState(false);return useEffect(()=>{let r=true,n=AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(mg,"useRnReducedMotion");function Rl(){let e=PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(Rl,"readFontScale");function yg(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(yg,"subscribeFontScale");function gg(){return useSyncExternalStore(yg,Rl,Rl)}i(gg,"useRnTextScale");function kl(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(kl,"platformOS");function hg(){return kl()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(hg,"contrastSignal");function bg(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=hg(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);fg(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(bg,"useRnHighContrast");function vg(){return kl()==="ios"?"Menlo":Le}i(vg,"rnPlatformMonoFamily");function Cg(){return globalThis.__DEV__!==false}i(Cg,"isDevelopment");var Sl=new Set;function Eg(e){if(!Cg()||Sl.has(e))return;Sl.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(Eg,"warnUnregisteredFace");function Rg(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||Eg(e),o}i(Rg,"rnIsFontRegistered");var Qr=Object.freeze({useColorScheme:pg,useReducedMotion:mg,useTextScale:gg,useHighContrast:bg,scaleTypeSizes:false,platformMonoFamily:vg,isFontRegistered:Rg});function Pg(e){return createElement(SafeAreaProvider,null,e)}i(Pg,"wrapInSafeArea");var Tg=Object.freeze({platform:"react-native",eventSourceFactory:vl(),wrap:Pg,theme:Qr});function kg(e){return createElement(bl,{...e,seams:Tg})}i(kg,"EverfurProvider");function It(e){let{runtime:t}=q(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Ca(e,n.decisions,{isPending:n.isPending}),[e,n])}i(It,"useCapability");function Og(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Og,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=M(),n=Og(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var At=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Fg=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function E(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Fg[t]]}}i(E,"face");var Eo=class Eo extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Eo,"HostRenderBoundary");var Co=Eo;function Lg({render:e}){return e()}i(Lg,"RenderHost");function ht({render:e,fallback:t,resetKey:r}){return createElement(Co,{fallback:t,resetKey:r,children:createElement(Lg,{render:e})})}i(ht,"HostRender");var Dg=48;function Ng(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Ng,"selectView");function Po(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=It(t),l=useMemo(()=>Ng(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(ht,{render:o,fallback:jsx(Al,{capability:t,style:s})}):jsx(Al,{capability:t,style:s});case "disabled":return n?jsx(ht,{render:()=>n(a),fallback:jsx(Ol,{decision:a,style:s}),resetKey:a}):jsx(Ol,{decision:a,style:s});default:return qe(l)}}i(Po,"CapabilityGate");function Al({capability:e,style:t}){let r=M(),n=useMemo(()=>Fl(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(Al,"PendingSkeleton");function Ol({decision:e,style:t}){let r=M(),n=useMemo(()=>Fl(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(C,{style:n.offstateText,children:o}):null})}i(Ol,"OffState");function Fl(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:Dg,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...E(e,"regular"),fontSize:o.size.body,lineHeight:Math.round(o.size.body*o.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}i(Fl,"makeStyles");var h=Object.freeze({placeholder:"Message",send:"Send",stop:"Stop",retry:"Try again",followUps:"Follow up questions",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",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\u2026",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",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another 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 K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var To=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),Ml=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Ug(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Ug,"sentimentToFeedbackType");function Ll(e,t){if(e==="down"&&t!==null){let r=To.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Ug(e)}i(Ll,"feedbackTypeFor");var zg=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function ar(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=q(),s=e?.petRef??n??null,a=e?.conversationId??null,l=useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[u,d]=useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=useRef(null);useEffect(()=>{let I=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=I,d({scope:l,controller:I}),()=>{p.current=null,d(A=>A?.controller===I?null:A),t.registry.releaseChat(I);}},[t,r,s,a,o,l]);let f=useCallback(I=>c?c.subscribe(I):jg,[c]),m=useCallback(()=>c?c.getSnapshot():zg,[c]),g=useSyncExternalStore(f,m,m),k=useCallback((I,A)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?xo(c,c.send(I,A?.imageS3Keys===void 0?{}:{imageS3Keys:A.imageS3Keys}),()=>p.current===c):Promise.resolve(_o()),[c]),y=useCallback(I=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?xo(c,c.askEverfur(I),()=>p.current===c):Promise.resolve(_o()),[c]),R=useCallback(()=>c&&p.current===c?xo(c,c.retryLast(),()=>p.current===c):Promise.resolve(_o()),[c]),T=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),O=useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[w,b]=useState({controller:null,byMessage:{}}),S=w.controller===c?w.byMessage:Wg,P=useCallback(async(I,A,x,B)=>{if(!c||p.current!==c)return v(N("accessDenied"));let re=String(I),j=w.controller===c?w.byMessage[re]:void 0;if(j===A&&x==null)return b(fe=>{let W={...fe.controller===c?fe.byMessage:{}};return delete W[re],{controller:c,byMessage:W}}),L(Object.freeze({feedbackId:""}));b(fe=>({controller:c,byMessage:{...fe.controller===c?fe.byMessage:{},[re]:A}}));let se=await c.submitFeedback(I,Ll(A,x??null),B??null);return p.current!==c?v(N("accessDenied")):(se.ok||b(fe=>{let W={...fe.controller===c?fe.byMessage:{}};return j===void 0?delete W[re]:W[re]=j,{controller:c,byMessage:W}}),se)},[c,w]),V=useMemo(()=>{let I=i(async A=>{if(!c||p.current!==c)return v(N("accessDenied"));let x=await A(c);return p.current===c?x:v(N("accessDenied"))},"run");return {listConversations:i(A=>I(x=>x.listConversations({...s?{petRef:s}:{},...A})),"listConversations"),getMessages:i((A,x)=>I(B=>B.getMessages(A,x)),"getMessages"),resumeConversation:i(A=>I(x=>x.resumeConversation(A)),"resumeConversation"),loadOlderMessages:i(()=>I(A=>A.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>I(A=>A.markRead()),"markRead"),refreshActiveThread:i(()=>I(A=>A.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((A,x)=>I(B=>B.answerCheckin(A,x)),"answerCheckin"),openCheckin:i(A=>I(x=>x.openCheckin(A)),"openCheckin")}},[c,s]);return useMemo(()=>({status:g.status,messages:g.messages,conversationId:g.conversationId,petRef:s,error:g.error,isStreaming:g.isStreaming,isBootstrapping:g.isBootstrapping,historyCursor:g.historyCursor??null,isLoadingHistory:g.isLoadingHistory??false,stopped:g.stopped??false,reconnecting:g.reconnecting??false,...V,suggestedPrompts:g.suggestedPrompts,unreadCount:g.unreadCount,hasUnreadThreads:g.hasUnreadThreads??false,newConversation:O,sentimentByMessage:S,feedback:P,send:k,askEverfur:y,retryLast:R,stop:T}),[g,s,k,y,R,T,V,O,S,P])}i(ar,"useEverfurChat");var jg=i(()=>{},"NOOP_UNSUBSCRIBE"),Wg=Object.freeze({});async function xo(e,t,r){for await(let o of t);if(!r())return v(N("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):L(Gg(n.messages))}i(xo,"driveToResult");function Gg(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i(Gg,"lastAssistantResponseId");function _o(){return v(N("internalError",{retryable:true}))}i(_o,"notReadyError");function ce(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(ce,"slotBox");function wo(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(wo,"ownGroundSlot");function Te(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Te,"slotText");function Ul(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:Xn(Lr),filename:e.filename,size:Xn(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Dr});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(Ul,"attachmentErrorMessage");function Vl(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(Vl,"attachControlLabel");var Yg=Object.freeze({attachments:Object.freeze([])});function Zr(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=q(),o=e.maxPerMessage??Dr,s=useMemo(()=>{if(e.queue)return e.queue;let{services:y}=t.registry;return $s({funnel:Re({auth:y.authFor(r),...y.errorPolicy?{errorPolicy:y.errorPolicy}:{}}),transport:e.transport??y.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.queue,e.transport]);useEffect(()=>()=>{s!==e.queue&&s.dispose();},[s,e.queue]);let a=useSyncExternalStore(s.subscribe,s.getSnapshot,()=>Yg),[l,u]=useState(null),d=useCallback(y=>{let T=(Array.isArray(y)?y:[y]).map(w=>s.add(w)),O=T.find(w=>!w.ok);return O!==void 0&&!O.ok&&u(O.error),T},[s,u]),c=useCallback(y=>s.retry(y),[s]),p=useCallback(y=>s.remove(y),[s]),f=useCallback(()=>s.clear(),[s]),m=useCallback(()=>u(null),[u]),g=a.attachments.some(y=>y.status==="uploading"),k=a.attachments.some(y=>y.status==="failed");return useMemo(()=>({available:s.available,attachments:a.attachments,maxPerMessage:o,uploading:g,failed:k,blocked:g||k,s3Keys:a.attachments.flatMap(y=>y.status==="uploaded"&&y.s3Key!==null?[y.s3Key]:[]),rejected:l,add:d,retry:c,remove:p,clear:f,dismissRejected:m}),[s.available,a,o,g,k,l,d,c,p,f,m])}i(Zr,"useChatAttachments");var Zg="pet_not_registered";function zl(e){return e!=null&&e.reasonCode===Zg}i(zl,"isPetNotRegistered");var Jg=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function jl(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=q(),a=useCallback(()=>$e(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:Ao(t),[t]),[u,d]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=useCallback(()=>{if(e===null||t===void 0||f===null)return;let k=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(y=>{k===c.current&&(y.ok?(d({key:f,status:"registered",error:null,registered:y.value}),p.current?.()):d({key:f,status:"failed",error:y.error,registered:null}));});},[a,e,f]);useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let g=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?Jg:u.key!==f?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[f,u,g])}i(jl,"useChatPetRegistration");function Ao(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Ao).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${Ao(n)}`).join(",")}}`}i(Ao,"stableKey");var ur=Object.freeze({standard:pt.standard,emphasized:pt.emphasized,exit:pt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var Wl=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,reduced:false}),eh=Object.freeze({...Wl,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,reduced:true});function Gl(e){return e.motion.reducedMotion?eh:Wl}i(Gl,"chatMotion");function Jr(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(Jr,"followUpDelayMs");function Kl(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(Kl,"nextRevealLength");var Oo=Object.freeze({});function $l(e){let[t,r]=useState(Oo),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Oo?u:Oo);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[l.id]:a.images})));},[e]);let s=useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return useMemo(()=>({byMessage:t,stage:s}),[t,s])}i($l,"useSentImages");var sh=500;function Fo(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,sh):null}i(Fo,"sanitizeSeedPrompt");function Xl(e,t,r){let n=Fo(r),o=useRef(e);o.current=e;let s=useRef(null);useEffect(()=>{if(n===null||t||s.current===n)return;let a=o.current;a!==void 0&&(s.current=n,Promise.resolve(a(n)).catch(()=>{}));},[n,t]);}i(Xl,"useInitialAsk");function ah(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(ah,"isCoalesced");function Ql(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:ah(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Ql,"decideChatRefresh");function Mo(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Mo,"reportHostFailure");function lh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(lh,"isThenable");function Y(e,...t){if(typeof e=="function")try{let r=e(...t);return lh(r)&&Promise.resolve(r).then(void 0,Mo),r}catch(r){Mo(r);return}}i(Y,"callHost");var Zl=new WeakMap;function Jl(e){if(typeof e!="function")return;let t=Zl.get(e);if(t!==void 0)return t;let r=i((...n)=>{Y(e,...n);},"guarded");return Zl.set(e,r),r}i(Jl,"guardHost");function Ot(e,...t){let r;try{r=e(...t);}catch(n){return Mo(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Ot,"callHostAsync");function tu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:Y(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=Ql(l,{activeConversationId:u,isTurnInFlight:d,isOffline:s,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},c!==void 0&&Promise.resolve(c()).catch(()=>{});}},useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),useEffect(()=>{if(e===void 0)return;let l=[],u=i((d,c)=>{if(d===void 0)return;let p=Y(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)Y(d);}},[e]);}i(tu,"useChatLifecycle");function dh(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(dh,"targetKey");function nu(e,t){let r=dh(t),n=useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=useRef(null);useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:s,target:a}=n.current;s===void 0||a===void 0||Promise.resolve(s(a)).catch(()=>{});},[r]);}i(nu,"useCheckinTarget");function su(e,t,r){let[n,o]=useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);useEffect(()=>{o(l=>{let u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let a=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(su,"useChatDraft");function au(e,t,r,n){let o=useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=useRef(null),[a,l]=useState(null);useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await Ot(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),useEffect(()=>{e===void 0||a!==`${t??""}`||Y(()=>e.write(t,r));},[e,t,r,a]);}i(au,"usePersistedDraft");var X=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",search:"Search",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function tn(e){let t=e?.replace(/\s+/g," ").trim();return t||X.untitled}i(tn,"conversationTitle");function uu(e){return `${e.unreadCount!==null&&e.unreadCount>0?X.unreadPrefix:""}${X.openConversation} ${tn(e.title)}`}i(uu,"openConversationLabel");function lu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(lu,"normalizeForSearch");function gh(e,t){let r=lu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=lu(tn(o.title)),a=s.indexOf(r);if(a<0)continue;let l=a===0?0:s.charAt(a-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(gh,"filterConversations");function No(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(No,"fresh");function du(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>No(s)),d=l.scope===s?l:No(s);useEffect(()=>(a.current+=1,r(false),o(""),u(No(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async O=>{let w=++a.current,b=O!==void 0;u(P=>({...P,scope:s,loading:!b,loadingMore:b,error:null}));let S=await e.listConversations(O?{cursor:O}:void 0);if(w===a.current){if(!S.ok){u(P=>({...P,loading:false,loadingMore:false,error:S.error.displayMessage}));return}u(P=>{let V=O&&P.scope===s?P.rows:[],I=new Set(V.map(A=>A.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...V,...S.value.conversations.filter(A=>!I.has(A.id))],cursor:S.value.nextCursor===O?null:S.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async O=>{let w=++a.current;u(S=>({...S,loading:true,error:null}));let b=await e.resumeConversation(O);w===a.current&&(u(S=>({...S,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),g=i(async()=>{let O=a.current,w=await e.loadOlderMessages();O===a.current&&!w.ok&&u(b=>({...b,error:w.error.displayMessage}));},"earlier"),k=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),y=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),R=useMemo(()=>gh(d.rows,n),[d.rows,n]),T=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:g,newConversation:k,loadMore:y,query:n,setQuery:o,searching:T,filtered:R,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(du,"useHistoryPanel");var rn="#111111",nn="#FFFFFF",vh=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:rn,pillColor:nn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:rn,pillColor:nn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:rn,pillColor:nn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:rn,pillColor:nn,showsVetAction:false})});function Ch(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Ch,"urgencySignature");function Eh(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Eh,"generalUrgencyReason");function fu(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Eh(t)}:null}return null}i(fu,"latestUrgencySource");function mu(e){let t=e===null?null:Ch(e),[r,n]=useState(null),[o,s]=useState(false);useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:vh[e.level],d=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=useCallback(()=>s(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(mu,"useUrgencySurface");function yu(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(yu,"selectView");function Rh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Rh,"needsNewConversation");function gu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Rh(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(gu,"turnNotice");function hu(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(hu,"awaitingAssistant");function bu(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(bu,"buildChatOpts");var dr=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function Eu(e){let t=M(),r=useMemo(()=>Th(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${dr.title}. ${dr.body}`,children:[jsx(C,{style:r.title,children:dr.title}),jsx(C,{style:r.body,children:dr.body})]})}i(Eu,"ClinicalDisclaimer");function Th(e){let{color:t,space:r,type:n}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...E(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...E(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Th,"makeStyles");var oe={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function ee(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(ee,"box");function pe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(pe,"stroke");function Ru({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[ee(e),{gap:e*.22}],...oe,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(Ru,"MenuGlyph");function Su({size:e,color:t,strokeWidth:r,rotate:n}){let o=pe(e,r),s=e*.78;return jsxs(View,{style:[ee(e),{transform:[{rotate:n}]}],...oe,children:[jsx(View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsx(View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(Su,"Cross");function Pu(e){return jsx(Su,{...e,rotate:"0deg"})}i(Pu,"PlusGlyph");function bt(e){return jsx(Su,{...e,rotate:"45deg"})}i(bt,"CloseGlyph");function Ze({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsx(View,{style:ee(e),...oe,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(Ze,"CheckGlyph");function Tu({size:e,color:t,strokeWidth:r,direction:n}){let o=pe(e,r),s=e*.46;return jsx(View,{style:ee(e),...oe,children:jsx(View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:n==="down"?-s*.4:s*.4,transform:[{rotate:n==="down"?"45deg":"225deg"}]}})})}i(Tu,"ChevronGlyph");function ku({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxs(View,{style:[ee(e),{flexDirection:"row",gap:1}],...oe,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(ku,"BookGlyph");function xu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.5;return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}i(xu,"ArrowUpRightGlyph");function _u({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(_u,"CopyGlyph");function on({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=pe(e,r),a=n?t:"transparent";return jsxs(View,{style:[ee(e),{transform:[{rotate:o}]}],...oe,children:[jsx(View,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),jsx(View,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),jsx(View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}i(on,"ThumbGlyph");function wu({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:[ee(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...oe,children:[jsx(View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsx(View,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}i(wu,"InfoGlyph");function Iu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.34;return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}i(Iu,"UploadGlyph");function Au({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:[ee(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...oe,children:[jsx(View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(Au,"PhotoGlyph");function Ou({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),jsx(View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}i(Ou,"CameraGlyph");function Fu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.66;return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsx(View,{style:{position:"absolute",bottom:e*.02,right:e*.02,width:n,height:e*.4,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}})]})}i(Fu,"SearchGlyph");function Mu({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}i(Mu,"EditGlyph");function Lu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.62;return jsxs(View,{style:ee(e),...oe,children:[jsx(View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsx(View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(Lu,"MapPinGlyph");function Du({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:ee(e),testID:r,...oe,children:jsx(View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}i(Du,"SendGlyph");function Nu({size:e,color:t,testID:r}){return jsx(View,{style:ee(e),testID:r,...oe,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(Nu,"StopGlyph");function sn({size:e,strokeWidth:t,color:r,children:n}){return jsx(View,{style:[ee(e),{borderRadius:e/2,borderWidth:t??StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(sn,"Ring");function Q(){let e=M();return Gl(e)}i(Q,"useChatMotion");var Fh=8;function Vu(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Vu,"bezierComponent");function Mh(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Mh,"bezierSlope");function an(e){let[t,r,n,o]=e;return s=>{if(s<=0)return 0;if(s>=1)return 1;let a=s;for(let l=0;l<Fh;l+=1){let u=Mh(a,t,n);if(u===0)break;a-=(Vu(a,t,n)-s)/u;}return Vu(Math.min(1,Math.max(0,a)),r,o)}}i(an,"bezierEasing");var Uo=an(ur.standard),Lh=an(ur.outQuad);function zo(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(zo,"useAnimatedValue");function vt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=zo(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:Lh,useNativeDriver:true}),a=n>0?Animated.sequence([Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[o,r])}i(vt,"useFadeIn");function jo({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=zo(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:Uo,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=Animated.timing(l,{toValue:0,duration:r,easing:Uo,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsx(Animated.View,{style:[n,{opacity:l}],children:o})}i(jo,"FadePresence");function H({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,...s}){let a=Q(),l=zo(1),u=useCallback(d=>{a.pressMs<=0||a.pressScale===1||Animated.timing(l,{toValue:d,duration:a.pressMs,easing:Uo,useNativeDriver:true}).start();},[l,a.pressMs,a.pressScale]);return jsx(Pressable,{...s,style:t,onPressIn:d=>{u(a.pressScale),n?.(d);},onPressOut:d=>{u(1),o?.(d);},children:jsx(Animated.View,{style:[e,{transform:[{scale:l}]}],children:r})})}i(H,"PressScale");function zu(e,t,r){let n=t&&r.revealTickMs>0,[o,s]=useState(0),a=useRef(e);return a.current=e,useEffect(()=>{if(!n)return;let l=setInterval(()=>{s(u=>Kl(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(zu,"useRevealedText");var Bu=false;function Dh(e){e.layoutMs<=0||(Bu||(Bu=true,Platform.OS==="android"&&typeof UIManager.setLayoutAnimationEnabledExperimental=="function"&&UIManager.setLayoutAnimationEnabledExperimental(true)),LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}));}i(Dh,"animateLayout");function ln(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Dh(t));}i(ln,"useAnimateLayoutOn");var Wo=36,jh=22,Wh=12,Gh=12,Kh=16,qh="#000",$h="rgba(0,0,0,0.45)";function ju({uri:e,label:t,onClose:r}){let n=M(),o=useSafeAreaInsets();return e===null?null:jsxs(Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.closePreview,style:un.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:un.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[un.closeWrap,{top:o.top+Gh}],children:jsx(H,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:Wh,style:un.closeButton,onPress:r,children:jsx(bt,{size:jh,color:n.color.surface,strokeWidth:2})})})]})}i(ju,"AttachmentImageLightbox");var un=StyleSheet.create({backdrop:{flex:1,backgroundColor:qh,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Kh},closeButton:{width:Wo,height:Wo,borderRadius:Wo/2,backgroundColor:$h,alignItems:"center",justifyContent:"center"}});var dn=12,Jh=80,Go=44,Wu=22,eb=.14,tb=18,rb=8,Gu=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Ku({sources:e,full:t,onPick:r,onClose:n}){let o=M(),s=useMemo(()=>nb(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(H,{accessibilityRole:"button",accessibilityLabel:Gu[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsx(View,{style:s.tileIconWrap,children:a==="photo"?jsx(Au,{size:Wu,color:o.color.brandInk,strokeWidth:1.5}):jsx(Ou,{size:Wu,color:o.color.brandInk,strokeWidth:1.5})}),jsx(C,{tier:"control",style:s.tileLabel,children:Gu[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Ku,"AttachmentPickerPopover");function nb(e){let t=e.color,r=e.radius;return StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:eb,shadowRadius:tb,shadowOffset:{width:0,height:rb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Jh,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Go,height:Go,borderRadius:Go/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...E(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-dn/2,width:dn,height:dn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:dn+4,height:2,backgroundColor:t.surfaceCream}})}i(nb,"makeStyles");var qu=56,$u=12,sb=14,ab=10,lb="rgba(16,70,46,0.45)",ub="rgba(7,193,104,0.55)",db="rgba(185,28,28,0.55)",cb=200,pb=300,rd=20,qo=22,fb=12,mb="rgba(0,0,0,0.78)",Yu=220,Xu=100,Qu="rgba(255,255,255,0.15)";function nd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=M(),l=useMemo(()=>id(a),[a]);return e.length===0&&t===null?null:jsxs(View,{style:l.strip,children:[e.length>0?jsx(View,{style:l.cards,children:e.map(u=>jsx(yb,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:Ul(t)}):null]})}i(nd,"AttachmentStrip");function yb({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=M(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=useRef(e.status),[c,p]=useState(false);return useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxs(View,{style:t.card,children:[jsx(Pressable,{accessibilityRole:u?"button":"image",accessibilityLabel:u?K(h.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!u},disabled:!u,style:t.thumbHit,onPress:()=>o(e),children:jsxs(View,{style:t.thumb,children:[jsx(Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsx(View,{style:t.uploadingOverlay,children:jsx(ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsx(gb,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(bt,{size:rd,color:s.color.surface,strokeWidth:2})})}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:K(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(bt,{size:fb,color:s.color.surface,strokeWidth:1.5})})]})}i(yb,"PreviewCard");function gb({styles:e,onDone:t}){let r=M(),n=Q(),o=useRef(null);o.current===null&&(o.current=new Animated.Value(0));let s=o.current;return useEffect(()=>{let a=Animated.sequence([Animated.timing(s,{toValue:1,duration:cb,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:pb,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsx(Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsx(Ze,{size:rd,color:r.color.surface,strokeWidth:2})})}i(gb,"SuccessFlash");function od({images:e,onPreview:t}){let r=M(),n=useMemo(()=>id(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsx(View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsx(Image,{source:{uri:s.uri},style:o?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${s.uri}-${a}`))})}i(od,"SentImages");function id(e){let t=e.color,r=e.type;return StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:qu,height:qu,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:$u,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:lb},successOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:ub},failedOverlay:{...StyleSheet.absoluteFillObject,borderRadius:$u,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:db},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:qo,height:qo,borderRadius:qo/2,backgroundColor:mb,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Yu,height:Yu,borderRadius:sb,backgroundColor:Qu},gridImage:{width:Xu,height:Xu,borderRadius:ab,backgroundColor:Qu}})}i(id,"makeStyles");var hb="file",bb="chat attachment upload: the file handle has no uri",vb="chat attachment upload failed";function Cb(e){return {uri:e.uri,name:Yn(e.name),type:e.mimeType}}i(Cb,"filePartOf");function sd(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(bb));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(vb)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(hb,Cb(r));let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(sd,"createRnChatAttachmentTransport");function cn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=q(),o=useMemo(()=>$e(e.registry.services.authFor(t)),[e,t,n]),[s,a]=useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},u=useRef(0),d=useCallback(async()=>{let p=++u.current;a(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&a(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:d}),[l.pets,l.loading,l.error,c,d])}i(cn,"useEverfurPets");function ad(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(ad,"headerPetOf");var ld=Object.freeze({visitButton:"Talk to a vet"});var Qo=Object.freeze(["visit","join","summary","messages"]);function Zo(e){return typeof e=="string"&&Qo.includes(e)}i(Zo,"isVetVisitIntent");var Tb="/widget/v1/televet/handoffs",kb="/widget/v1/televet/availability",xb="/widget/v1/televet/chat-entry",_b=/^[a-z0-9][a-z0-9_-]{0,39}$/,wb=/^[A-Za-z0-9_-]{22}$/;var ud=32,dd=128,cd=64;function ei(e){let t=e.httpStatus;switch(e.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 t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(ei,"vetVisitErrorReasonOf");function pd(e){return v(N("validationFailed",{retryable:false,wireMessage:e}))}i(pd,"invalid");function Jo(e){return v(N("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Jo,"unusable");function Ib(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!_b.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let s=t?.visitRef,a=t?.intent,l=s!=null;if(l){let u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>cd)return {ok:false,message:`visitRef must be 1..${cd} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Zo(a))return {ok:false,message:`intent must be one of ${Qo.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(Ib,"handoffBody");function Ab(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Zo(r)?null:Object.freeze({visitRef:t,intent:r})}i(Ab,"parseVisitEcho");function md(e){let t=e.funnel??Re({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(fd(r,"televet.visit.handoff_failed",{reason:ei(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let y=typeof o=="string"?[...o].length:0;if(y<1||y>dd)return n(N("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${dd} characters`}));a=o;}let l=Ib(a,s);if(!l.ok){let y=pd(l.message);return y.ok?y:n(y.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:Tb,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Ob(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!wb.test(f))){let y=Jo("the handoff response carried no usable return flow id");return y.ok?y:n(y.error)}let m=u.visit_ref!==void 0,g=m?Ab(d.value?.visit):null;if(m&&g===null){let y=Jo("the handoff response did not confirm the visit it opens");return y.ok?y:n(y.error)}let k=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...g!==null?{visit:g}:{}});return k===null?n(N("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(fd(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),L(k))},async checkAvailability(o){if(typeof o!="string"||o.length>ud)return pd(`state must be at most ${ud} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:kb,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?Jo("the availability response carried no usable answer"):L(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:xb},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(md,"createVetVisitController");function Ob(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!Db(t)?null:Object.freeze({url:t,expiresAt:r})}i(Ob,"parseHandoff");var Fb=new Set(["localhost","127.0.0.1","[::1]"]),Mb=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Lb=/[\s\u0000-\u001f\u007f]/;function Db(e){if(Lb.test(e))return false;let t=Mb.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),s=r==="https",a=r==="http"&&Fb.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(Db,"isOpenableVisitUrl");function fd(e,t,r){if(e)try{e.track(t,r);}catch{}}i(fd,"safeTrack");var gd=Object.freeze({status:"idle",error:null,errorReason:null});function Ub(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=useState(null);if(useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let g=await f.checkAvailability(n);return g.ok&&g.value.available}catch{return false}},"ask")().then(g=>{p&&d({key:l,open:g});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(Ub,"usePreflight");var Vb=Object.freeze({status:"opening",error:null,errorReason:null});function bd(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=q(),s=It("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=useMemo(()=>{if(t.controller)return t.controller;let{services:I}=r.registry;return md({auth:I.authFor(n),telemetry:I.telemetry,...I.errorPolicy?{errorPolicy:I.errorPolicy}:{}})},[r,n,o,t.controller]),p=useRef(c);p.current=c;let f=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),m=Ub(p,a,{usState:l,chat:u,scope:f}),g=a&&(m===null||m.open)&&(!u||d!==null),k=t.returnTo??null,[y,R]=useState(gd),T=useRef(null),O=useRef({runtime:r,userRef:n,scopeEpoch:o});O.current={runtime:r,userRef:n,scopeEpoch:o};let w=useRef(c);w.current=c;let b=useRef(g);b.current=g;let S=useCallback((I,A)=>{if(T.current)return T.current;let x=i((W,nt)=>(R({status:W==="cancelled"?"idle":"error",error:nt,errorReason:W==="cancelled"?null:W}),Object.freeze({opened:false,reason:W,error:nt})),"fail");if(!b.current)return Promise.resolve(x("unavailable",null));let B=e.prepare();if(!B.ok)return Promise.resolve(x(B.reason,null));let re=O.current,j=w.current;R(Vb);let fe=(async()=>{let W,nt={...k!==null?{returnTo:k}:{},...u?{entry:"chat"}:{},...A!==null?{visitRef:A.visitRef}:{},...A!==null&&A.intent!==null&&A.intent!==void 0?{intent:A.intent}:{}},br=Object.keys(nt).length===0?void 0:nt,Bt=I===void 0?d:I;try{W=await(br===void 0?j.createHandoff(Bt):j.createHandoff(Bt,br));}catch{return e.abandon(B.value),x("unknown",null)}let Pt=O.current;if(Pt.runtime!==re.runtime||Pt.userRef!==re.userRef||Pt.scopeEpoch!==re.scopeEpoch)return e.abandon(B.value),x("cancelled",null);if(!W.ok)return e.abandon(B.value),x(ei(W.error),W.error);let Tt=await e.finish(B.value,W.value);return Tt!==null?x(Tt,null):(R(gd),Object.freeze(W.value.flowId===void 0?{opened:true}:{opened:true,flowId:W.value.flowId}))})().finally(()=>{T.current===fe&&(T.current=null);});return T.current=fe,fe},[e,d,k,u]),P=useCallback(I=>S(I,null),[S]),V=useCallback((I,A)=>S(void 0,{visitRef:I,intent:A??null}),[S]);return {available:g,isPending:s.isPending||(m?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:P,openVisit:V}}i(bd,"useVetVisitWith");var zb=i(e=>Linking.openURL(e),"defaultOpenUrl");function pn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??zb;return {prepare:i(()=>({ok:true,value:null}),"prepare"),async finish(s,a){try{return await o(a.url),null}catch{return "openFailed"}},abandon:i(()=>{},"abandon")}},[t]);return bd(n,r)}i(pn,"useVetVisit");var vd=44,qb=.6;function Lt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:m}=e,g=pn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{}}),k=M(),y=useMemo(()=>$b(k),[k]),R=useRef(false);if(!g.available)return null;let T=g.status==="opening",O=r??ld.visitButton;return jsx(Pressable,{onPress:i(()=>{T||R.current||(R.current=true,(f==null?g.open():g.openVisit(f,m??null)).then(b=>{b.opened?Y(o,b.flowId??null):b.reason!=="cancelled"&&Y(s,b.reason,b.error);}).finally(()=>{R.current=false;}));},"onPress"),accessibilityRole:"button",accessibilityLabel:O,accessibilityState:{busy:T,disabled:T},style:[y.button,T?y.busy:null,a],children:jsx(C,{style:[y.label,l],children:O})})}i(Lt,"VetVisitButton");function $b(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:vd,minWidth:vd,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...ce(s.vetVisitButton)},busy:{opacity:qb},label:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...Te(s.vetVisitButton)}})}i($b,"makeStyles");function ri(e){return tr(e)==="cat"?"cat":"dog"}i(ri,"speciesOf");function ni(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(ni,"petAgeYears");function Rd(e){let t=ni(e.ageYears),r=ri(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Rd,"formatPetMeta");var Ed=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Yb(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Ed[t%Ed.length]}i(Yb,"pickInitialsPalette");function oi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(oi,"getInitial");function Sd(e){return {...Yb(e.petRef),initial:oi(e.name)}}i(Sd,"petInitials");function Jb(e){return Math.max(12,Math.round(e*.42))}i(Jb,"letterSize");function mr({pet:e,size:t,ringStroke:r}){let n=M(),o=useMemo(()=>ev(n),[n]),s=t-r*2,a=e===null?null:Sd(e),l=Jb(s);return jsx(sn,{size:t,strokeWidth:r,color:n.color.success,children:jsx(View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsx(C,{tier:"badge",style:[o.letter,{fontSize:l,lineHeight:Math.round(l*1.2),color:a===null?n.color.text.muted:a.foreground}],children:a===null?oi(null):a.initial})})})}i(mr,"PetDisc");function ev(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...E(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(ev,"makeStyles");var si=48,xd=2,iv=320,sv="80%",av="rgba(17,17,17,0.45)",lv=18,Pd=22,uv=12,Td=.4,dv=44;function ai(e){return e?.name?.trim()||h.yourPet}i(ai,"petDisplayName");function _d({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=M(),l=useMemo(()=>cv(a),[a]);return e?jsx(Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxs(View,{style:l.root,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=ai(u),p=Rd(u);return jsxs(H,{accessibilityRole:"button",accessibilityLabel:K(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(mr,{pet:u,size:si,ringStroke:xd}),jsxs(View,{style:l.copy,children:[jsx(C,{style:l.name,numberOfLines:1,children:c}),jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsx(Ze,{size:lv,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxs(H,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(C,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(_d,"PetSwitcherSheet");function cv(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:av},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Pd,borderTopRightRadius:Pd,gap:14,maxHeight:sv},title:{...E(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:iv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:dv,paddingHorizontal:8},addDisc:{width:si,height:si,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:xd,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...E(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...E(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...E(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...E(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Td},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:uv,backgroundColor:t.brandSoft},closeText:{...E(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Td}})}i(cv,"makeStyles");var mv=44,fn=36,yv=22,ui=9,gv=1.5,wd=6,Et=35,mn=1.75,di=12.4,hv=.5,bv=8,vv=28,Cv=160;function pi(e,t){return ad(e,t)}i(pi,"headerPet");function Ad({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=M(),u=useMemo(()=>Rv(l),[l]),[d,c]=useState(false),p=pi(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,g=ai(p),k=i(R=>{c(false),e.setActivePet(R),Y(o,R);},"select"),y=s===void 0?null:()=>{c(false),Y(s);};return jsxs(View,{style:u.row,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsx(Ru,{size:yv,color:l.color.text.primary,strokeWidth:2}),r?jsx(View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsx(View,{style:u.center,pointerEvents:"box-none",children:jsx(Ev,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(Lt,{entry:"chat",petRef:m,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsx(View,{style:u.right,children:f?jsxs(H,{accessibilityRole:"button",accessibilityLabel:K(h.switchActivePet,{name:g}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(mr,{pet:p,size:Et,ringStroke:mn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(Pu,{size:bv,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(sn,{size:Et,strokeWidth:mn,color:l.color.success,children:jsx(View,{style:u.placeholderDisc})})}):jsx(View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:g,children:jsx(mr,{pet:p,size:Et,ringStroke:mn})})}),jsx(_d,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:k,onAddPet:y,onClose:()=>c(false)})]})}i(Ad,"ChatHeader");function Ev({logoUrl:e,name:t,styles:r}){let[n,o]=useState(null);return e===null||n===e?null:jsx(View,{style:r.logoBar,children:jsx(Image,{source:{uri:e},style:r.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:()=>o(e)})})}i(Ev,"BrandLogo");function Rv(e){let t=e.color,r=Et-mn*2;return StyleSheet.create({vetEntry:{minHeight:mv,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...E(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:t.surface},iconSlot:{borderRadius:fn/2},iconButton:{width:fn,height:fn,borderRadius:fn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:wd,right:wd,width:ui,height:ui,borderRadius:ui,backgroundColor:t.danger,borderWidth:gv,borderColor:t.surface},center:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:vv,width:Cv},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Et/2},avatarWrap:{width:Et,height:Et,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:di,height:di,borderRadius:di/2,borderWidth:hv,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(Rv,"makeStyles");var et=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),Od=Object.freeze(_r.map(e=>Object.freeze({answer:e,label:et.answers[e]})));function Fd(e,t){let[r,n]=useState(null),[o,s]=useState(null),[a,l]=useState(null),u=useCallback(c=>{t!==null&&(n(c),s(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):s(p.error);}));},[t,e.caseId]),d=a??e.answer;return {answer:d,answerable:!Ls(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(Fd,"useCheckinCard");var Nd=44,Tv=.6;function Ud({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s}){let a=M(),l=useMemo(()=>kv(a),[a]),u=Fd(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable;return jsxs(View,{style:l.card,accessibilityLabel:et.eyebrow,children:[jsx(C,{tier:"compact",style:l.eyebrow,children:et.eyebrow}),jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsx(View,{style:[l.row,u.pending?l.rowPending:null],children:Od.map(({answer:p,label:f})=>{let m=(u.pending??u.answer)===p;return jsx(Pressable,{onPress:()=>u.choose(p),disabled:d,accessibilityRole:"button",accessibilityLabel:f,accessibilityState:{selected:m,disabled:d,busy:u.pending===p},style:[l.pill,m?l.pillSelected:null],children:jsx(C,{tier:"control",style:[l.pillLabel,m?l.pillLabelSelected:null],children:f})},p)})}):null,u.answer!==null?jsx(C,{style:l.logged,children:et.logged}):null,u.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:et.findVet,style:l.findVet,children:jsx(C,{tier:"control",style:l.findVetLabel,children:et.findVet})}):n?jsx(Lt,{entry:"chat",petRef:n,label:et.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},style:l.findVet,labelStyle:l.findVetLabel}):null:null,t.resolutionText?jsx(C,{style:l.resolution,children:t.resolutionText}):null,u.error?jsx(C,{style:l.error,accessibilityRole:"alert",children:u.error.displayMessage}):null]})}i(Ud,"CheckinCard");function kv(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.surface,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},eyebrow:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:Tv},pill:{flex:1,minHeight:Nd,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surfaceCream},pillSelected:{backgroundColor:t.brand,borderColor:t.brand},pillLabel:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:Nd,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...E(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(kv,"makeStyles");var _v=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),Vd="#C8BEB4";function wv(e){return e?_v[e.toUpperCase()]??Vd:Vd}i(wv,"tierColor");function Iv(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(Iv,"tierLabel");function Ne(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ne,"text");function Av(e){let t=Ne(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(Av,"httpsUrl");function Ov(e,t){let r=Ne(e.source_name)??Ne(e.sourceName),n=Ne(e.section),o=Ne(e.authority_tier)??Ne(e.authorityTier),s=Iv(o),a=r??Ne(e.title)??`Source ${t+1}`,l=Ne(e.monograph_chunk_id)??Ne(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:Av(e.url),excerpt:Ne(e.excerpt),tierColor:wv(o),key:`${a}-${l??"none"}-${t}`})}i(Ov,"toCitationCard");function Bd(e){return e===void 0||e.length===0?Fv:Object.freeze(e.map((t,r)=>Ov(t,r)))}i(Bd,"toCitationCards");var Fv=Object.freeze([]);function mi(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(mi,"sourcesLabel");function Hd(e,t){return `${t?h.hideSources:h.showSources} ${mi(e)}`}i(Hd,"sourcesToggleLabel");function zd(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(zd,"citationA11yLabel");var Vv=244,Wd=8,Gd=13,Bv=14,Hv=.3,zv=-0.24,jv=22,Wv=10,Gv=15;function Kd({citations:e}){let t=M(),r=useMemo(()=>$v(t),[t]),n=useMemo(()=>Bd(e),[e]),[o,s]=useState(false);if(n.length===0)return null;let a=n.length;return jsxs(View,{style:r.block,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:Hd(a,o),accessibilityState:{expanded:o},containerStyle:r.toggleSlot,style:r.togglePill,onPress:()=>s(l=>!l),children:[jsx(ku,{size:Gd,color:t.color.brandInk,strokeWidth:1.5}),jsx(C,{tier:"compact",style:r.toggleLabel,children:mi(a)}),jsx(Tu,{size:Gd,color:t.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?jsx(Kv,{cards:n,styles:r}):null]})}i(Kd,"CitationCards");function Kv({cards:e,styles:t}){let r=Q(),n=vt(r.citationsInMs,{risePx:r.citationsRisePx});return jsx(Animated.View,{style:n,children:jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(o=>jsx(qv,{card:o,styles:t},o.key))})})}i(Kv,"Deck");function qv({card:e,styles:t}){let r=M(),n=zd(e),o=e.url!==null,s=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(xu,{size:Bv,color:r.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null){let a=e.url;return jsx(H,{accessibilityRole:"link",accessibilityLabel:n,style:t.card,onPress:()=>{Linking.openURL(a);},children:s})}return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:n,style:t.card,children:s})}i(qv,"Card");function $v(e){let t=e.color,r=e.space,n=e.radius,o=e.type.size;return StyleSheet.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...E(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:Hv,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:Vv,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:Wd,height:Wd,borderRadius:n.pill},cardTitle:{...E(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:jv,color:t.text.primary,letterSpacing:zv},cardTitleLink:{color:t.linkInk},cardMeta:{...E(e,"monoMedium"),fontSize:o.nano,lineHeight:Wv,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...E(e,"regular"),fontSize:o.tiny,lineHeight:Gv,color:t.text.muted}})}i($v,"makeStyles");var $d=44,eC="rgba(17,17,17,0.55)",Yd=26,tC=36,Xd=4,yi=20,gi=38,rC=18,nC=12;function Qd({visible:e,onSubmit:t,onSkip:r}){let n=M(),o=useMemo(()=>oC(n),[n]),[s,a]=useState(null),[l,u]=useState(""),[d,c]=useState(false),[p,f]=useState(false),m=i(()=>{a(null),u(""),c(false),f(false);},"reset"),g=i(()=>{d||(m(),r());},"skip"),k=i(async()=>{if(d)return;c(true),f(false);let R=l.trim();await t(s,R.length>0?R:null)?m():(c(false),f(true));},"submit");if(!e)return null;let y=[...l].length>Qt;return jsx(Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:g,children:jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsx(Pressable,{style:o.scrim,onPress:g,accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y}),jsxs(View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsx(View,{style:o.handle}),jsxs(View,{style:o.header,children:[jsx(View,{style:o.iconBadge,children:jsx(on,{size:rC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:To.map(R=>{let T=s===R.key;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:R.label,accessibilityState:{selected:T},style:[o.option,T?o.optionSelected:null],onPress:()=>a(O=>O===R.key?null:R.key),children:[jsx(C,{style:[o.optionLabel,T?o.optionLabelSelected:null],children:R.label}),jsx(View,{style:[o.radio,T?o.radioSelected:null],children:T?jsx(Ze,{size:nC,color:n.color.surface,strokeWidth:2}):null})]},R.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(At,{style:o.input,placeholder:h.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:h.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsx(C,{tier:"compact",style:[o.counter,y?o.counterOver:null],children:`${[...l].length}/${Qt}`}):null]}),p?jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(H,{accessibilityRole:"button",accessibilityLabel:h.feedbackSubmit,accessibilityState:{busy:d,disabled:d||y},disabled:d||y,style:[o.submit,d||y?o.submitDisabled:null],onPress:()=>{k();},children:jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:g,style:o.skip,children:jsx(C,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(Qd,"FeedbackReasons");function oC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...StyleSheet.absoluteFillObject,backgroundColor:eC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Yd,borderTopRightRadius:Yd,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:tC,height:Xd,borderRadius:Xd/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:gi,height:gi,borderRadius:gi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...E(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...E(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,backgroundColor:t.surface},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:yi,height:yi,borderRadius:yi/2,borderWidth:2,borderColor:t.brandBorder,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...E(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...E(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:$d,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...ce(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Te(o.primaryButton)},skip:{minHeight:$d,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(oC,"makeStyles");var bC=.88,vC=420,CC=58,EC="rgba(17,17,17,0.28)",RC=.08,SC=.1,PC=.08,TC=.18,kC=.78,xC=.7,hi=36,_C=10,wC=14,IC=12,AC=16,OC=14,bi=8,FC=1.5,MC=.5,LC=an(ur.standard);function DC(e){return Math.min(Math.round(e*bC),vC)}i(DC,"drawerPanelWidth");function Jd({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(NC,{chat:e,history:t,onHidden:o}):null}i(Jd,"HistoryDrawer");function NC({chat:e,history:t,onHidden:r}){let n=M(),o=useMemo(()=>VC(n),[n]),s=Q(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=DC(l),d=t.open,c=useRef(null);c.current===null&&(c.current=new Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let R=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:LC,useNativeDriver:true});return R.start(({finished:T})=>{T&&!d&&r();}),()=>R.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,g=t.rows.length===0,k=g&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:X.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(C,{style:o.emptyBody,children:X.loading})]}):g&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:X.loadFailed}),jsx(C,{style:o.emptyBody,children:t.error}),jsx(H,{accessibilityRole:"button",accessibilityLabel:X.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(C,{tier:"control",style:o.retryText,children:X.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?X.empty:X.noMatch}),jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?X.emptyBody:X.noMatchBody})]}),y=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(C,{style:o.loadMoreLabel,children:X.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:t.close,accessibilityRole:"button",accessibilityLabel:X.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(CC,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxs(KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[jsxs(View,{style:o.searchRow,children:[jsxs(View,{style:o.searchPill,children:[jsx(Fu,{size:OC,color:n.color.text.muted,strokeWidth:1.5}),jsx(At,{value:t.query,onChangeText:R=>t.setQuery(R.replace(/^\s+/,"")),style:o.searchInput,placeholder:X.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:X.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(H,{accessibilityRole:"button",accessibilityLabel:X.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(Mu,{size:AC,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:X.heading}),t.error!==null&&!g?jsx(View,{style:o.errorCard,children:jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:m,keyExtractor:R=>R.id,renderItem:({item:R})=>jsx(UC,{row:R,active:R.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(R.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:y,onEndReached:t.loadMore,onEndReachedThreshold:MC})]})})]})})}i(NC,"DrawerModal");function UC({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(H,{accessibilityRole:"button",accessibilityLabel:uu(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:jsxs(View,{style:n.itemRow,children:[jsx(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:tn(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(UC,"Row");function Cn(e,t){if(!/^#[0-9a-f]{6}$/i.test(e))return "transparent";let r=Math.round(Math.min(1,Math.max(0,t))*255);return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}i(Cn,"inkWash");function VC(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:EC},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.brand,paddingHorizontal:16,borderRightWidth:.5,borderRightColor:t.brandBorder,gap:12},keyboardAvoider:{flex:1,gap:12},searchRow:{flexDirection:"row",alignItems:"center",gap:10},searchPill:{flex:1,flexDirection:"row",alignItems:"center",gap:8,borderRadius:e.radius.pill,backgroundColor:t.surface,paddingHorizontal:14,paddingVertical:10,borderWidth:1,borderColor:Cn(n,SC)},searchInput:{...E(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:hi,height:hi,borderRadius:hi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...E(e,"bold"),fontSize:14,lineHeight:17,color:n,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:_C},itemActive:{backgroundColor:Cn(n,RC)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...E(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:n},itemTitleUnread:E(e,"bold"),unreadDot:{width:bi,height:bi,borderRadius:bi/2,backgroundColor:t.danger,borderWidth:FC,borderColor:n},errorCard:{borderRadius:IC,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...E(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:wC,padding:14,gap:6,backgroundColor:Cn(n,PC),borderWidth:.5,borderColor:Cn(n,TC)},emptyTitle:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...E(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:kC},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...ce(r.primaryButton)},retryText:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n,...Te(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...E(e,"regular"),fontSize:11,lineHeight:14,color:n,opacity:xC}})}i(VC,"makeStyles");function ec(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(ec,"formatMessageTime");var hr=15,WC=15,GC=6,KC=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function ic({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=M(),a=useMemo(()=>qC(s),[s]),l=Q(),u=e.role==="user",d=useMemo(()=>ec(e.createdAt),[e.createdAt]),c=t!==void 0&&e.text.length>0,p=!u&&n!==void 0&&e.responseId!==void 0,[f,m]=useState(false),g=useRef(null);useEffect(()=>()=>{g.current&&clearTimeout(g.current);},[]);let k=i(()=>{t!==void 0&&(Ot(t,e.text),m(true),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{m(false),g.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxs(View,{style:a.wrap,children:[jsxs(View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:WC,onPress:k,style:a.iconHit,children:f?jsx(Ze,{size:hr,color:s.color.success,strokeWidth:2}):jsx(_u,{size:hr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Ml.map(({sentiment:y,label:R})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{selected:r===y},hitSlop:GC,onPress:()=>n?.(y),style:a.iconHit,children:jsx(on,{size:hr,color:s.color.sentiment[y],active:r===y,rotate:KC[y],strokeWidth:1.5})},y)):null]}),o?jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(ic,"MessageFooter");function qC(e){let t=e.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...E(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:hr,height:hr,alignItems:"center",justifyContent:"center"},thanks:{...E(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(qC,"makeStyles");var sc="#000000",$C="#83E0B4",YC=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:$C,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:"#10462E",borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit.",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),XC=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function QC(e){return e==null?e:e.replace(XC,"").trim()}i(QC,"formatBreedForPrompt");var ZC=new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function JC(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return ZC.has(t)}i(JC,"isUninformativeBreed");function eE(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(eE,"unspecifiedBreedLabel");function tE(e,t){return JC(e)?eE(t):String(e).replace(/\s+/gu," ").trim()}i(tE,"resolveBreedLabel");function ac(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(ac,"emptyStateTitle");function lc(e){let t=ri(e?.species),r=t==="cat"?"my cat":"my dog",n=e?.name?.trim()||null,o=n||r,s=tE(QC(e?.breed),t)||null,a=ni(e?.ageYears),l=a===null?null:String(a);return Object.freeze(YC.map(u=>{let d=u.label.includes("{breed}"),c=u.label.includes("{ageYears}"),f=u.fallbackLabel!==void 0&&(d&&!s||c&&!l)&&u.fallbackLabel?u.fallbackLabel:u.label,m=K(f,{petName:o,breed:s??r,species:t,ageYears:l??""}),g=!n&&f.startsWith("{petName}")?m.charAt(0).toUpperCase()+m.slice(1):m;return Object.freeze({id:u.id,intent:u.intent,label:g,background:u.background,borderColor:u.borderColor,borderWidth:u.borderWidth})}))}i(lc,"resolveQuickPrompts");var nE=36,cc=4,oE=340;function pc({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=M(),a=useMemo(()=>sE(s),[s]),l=useMemo(()=>lc(e),[e]),u=ac(e);return jsxs(View,{style:a.block,children:[jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(iE,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(pc,"QuickPrompts");function iE({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=Q(),d=vt(u.followUpInMs,{delayMs:Jr(u,t)}),c={backgroundColor:e.background,borderColor:e.borderColor,borderWidth:e.borderWidth};return e.intent==="vet_report"?s!==void 0?jsx(Animated.View,{style:d,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:cc,style:[l.chip,c],onPress:()=>{Y(s,r);},children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(Lt,{entry:"chat",petRef:n,label:e.label,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},style:[l.chip,c],labelStyle:l.chipLabel})}):jsx(Animated.View,{style:d,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:cc,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(iE,"Chip");function sE(e){let t=e.color;return StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...E(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:oE},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:nE,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...E(e,"bold"),fontSize:12,lineHeight:14,color:sc,textAlign:"center"}})}i(sE,"makeStyles");var Ci=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function fc(e){return e.includes("*")||e.includes("`")}i(fc,"hasInlineMarkup");function mc(e){let t=[],r=0;Ci.lastIndex=0;for(let n=Ci.exec(e);n!==null;n=Ci.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],s=n[2],a=n[3];o!==void 0?t.push({kind:"bold",text:o}):s!==void 0?t.push({kind:"italic",text:s}):a!==void 0&&t.push({kind:"code",text:a}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(mc,"tokenizeInlineMarkdown");function yc(e,t){return fc(e)?mc(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(C,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(yc,"renderInlineMarkdown");var bc=6,Ec=520,pE=Math.round(Ec*.18),vc=.44,fE=.5,Cc=[0,.5,1],mE=[0,1,2];function Rc(){let e=M(),t=useMemo(()=>gE(e),[e]),r=!e.motion.reducedMotion;return jsx(View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:mE.map(n=>r?jsx(yE,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(Rc,"TypingIndicator");function yE({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*pE),Animated.loop(Animated.timing(r,{toValue:1,duration:Ec,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Cc,outputRange:[vc,1,vc]}),o=r.interpolate({inputRange:Cc,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(yE,"AnimatedDot");function gE(e){let t=e.color,r=e.space,n=e.radius;return StyleSheet.create({card:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingHorizontal:r.md,paddingVertical:r.sm,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},dot:{width:bc,height:bc,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:fE}})}i(gE,"makeStyles");function Sc(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),r}i(Sc,"chatVetVisitOptions");var CE=16,EE=.75,Ri=12,Pc=15,RE=18,Rn=22,SE=14,PE=8,TE=20,kE=10,xE=13;function kc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=M(),a=useMemo(()=>_E(s),[s]),l=Q(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(jo,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxs(View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(ht,{render:()=>r(u.level),fallback:jsx(Tc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(Tc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(H,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:PE,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(bt,{size:SE,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(jo,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:kE,onPress:e.expand,children:jsx(wu,{size:TE,color:s.color.text.muted,strokeWidth:2})})})]})}i(kc,"UrgencyBanner");function Tc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=M(),a=pn(Sc(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{Y(r,e.level);}:null;if(u===null)return null;let d=wo(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:h.findVetA11y,accessibilityState:{busy:l},containerStyle:o.findVetSlot,style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,l?o.findVetBusy:null],onPress:u,children:[jsx(Lu,{size:xE,color:d,strokeWidth:1.5}),jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(Tc,"VetAction");function _E(e){let t=wo(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:CE,borderWidth:EE,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...E(e,"monoBold"),fontSize:Ri,lineHeight:Pc},reason:{...E(e,"regular"),fontSize:Ri,lineHeight:RE,paddingRight:Rn},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...ce(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...E(e,"monoBold"),fontSize:Ri,lineHeight:Pc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:Rn,height:Rn,borderRadius:Rn/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(_E,"makeStyles");function xc(){let e=cn(),{handle:t}=q(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(xc,"useChatPets");var NE=300,UE=3e3,_c=120,Ut=44,VE=120,BE="86%",wc=15,Ic=22,Pn=.5,HE=.04,zE=8,jE=2,WE=1,GE=.6,KE=22,qE=48,Ac=1.25,$E=14,YE=18,XE=6,QE=14,ZE=.04,JE=12,eR=2,tR=2,Oc=36,rR=20,Nt=36,Tn=(Ut-Nt)/2,nR=24,oR=22,iR=.4,Pi=30,sR=20,aR=.4,lR=480,uR="12%",dR=Object.freeze(["photo"]),cR=1;function Dc(e){let{style:t,renderPending:r}=e;return jsx(Po,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(pR,{...e})})}i(Dc,"EverfurChat");function pR({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:g,lifecycle:k,draftStore:y,vetReturnTo:R,vetUsState:T}){let{theme:O,styles:w}=_e(),b=Q(),S=useMemo(()=>bu(e,t),[e,t]),P=ar(S),V=yu(P),I=xc(),A=du(P),x=useSafeAreaInsets(),B=gu(P),re=useMemo(()=>l===void 0?void 0:()=>{Y(l,"emergency");},[l]),j=useMemo(()=>R===void 0&&T===void 0?void 0:{returnTo:R,usState:T},[R,T]),se=pi(I.pets,P.petRef),fe=useMemo(()=>fu(P.messages,se?.name??null),[P.messages,se?.name]),W=mu(fe);ln(W.showBanner,b),nu(P.openCheckin,f),Xl(P.askEverfur,P.isBootstrapping,m);let nt=useMemo(()=>Fo(g),[g]);tu(k,{conversationId:P.conversationId===null?null:String(P.conversationId),isTurnInFlight:P.isStreaming,refresh:P.refreshActiveThread});let br=(P.hasUnreadThreads??false)||A.rows.some(we=>we.unreadCount!==null&&we.unreadCount>0)||(P.unreadCount??0)>0,Bt=$l(P.messages),[Pt,Tt]=useState(null),Vc=useCallback(()=>Tt(null),[]),[Ht,kn]=useState(null),[Bc,xi]=useState(null),kt=useRef(null);useEffect(()=>()=>{kt.current&&clearTimeout(kt.current);},[]);let _i=useCallback(we=>{xi(String(we)),kt.current&&clearTimeout(kt.current),kt.current=setTimeout(()=>{xi(null),kt.current=null;},UE);},[]),Hc=useCallback((we,vr)=>{let zt=we.responseId;if(zt===void 0)return;let Gc=P.sentimentByMessage[String(zt)];P.feedback(zt,vr),vr==="down"&&Gc!=="down"&&kn(zt);},[P]),zc=useCallback(async(we,vr)=>Ht===null||!(await P.feedback(Ht,"down",we??"other",vr)).ok?false:(kn(null),_i(Ht),true),[P,Ht,_i]),jc=useCallback(()=>kn(null),[]),Wc=useCallback(we=>{P.send(we);},[P.send]),wi={send:P.send,stop:P.stop,isStreaming:P.isStreaming,conversationId:P.conversationId,seed:nt,draftStore:y,onStage:Bt.stage,onPreview:Tt};return jsxs(KeyboardAvoidingView,{style:[w.container,{paddingTop:x.top},r],behavior:Platform.OS==="ios"?"padding":void 0,children:[jsx(Ad,{pets:I,petRef:P.petRef,historyUnread:br,onOpenHistory:A.show,onPetChange:s,onAddPet:p,vet:j}),c!==void 0?jsx(fR,{petRef:e??null,pet:c,onRegistered:I.refresh}):null,jsx(kc,{surface:W,petRef:P.petRef,renderVetAction:u,onFindVet:l,vet:j}),jsx(View,{style:w.body,children:bR(V,P,{notice:B,vet:j,onCheckinFindVet:re,onSelectPrompt:Wc,renderPending:n,shownPet:se,onVetPrep:a,onCopy:o,onSentiment:Hc,thanksFor:Bc,imagesByMessage:Bt.byMessage,onPreview:Tt,onAddPet:p})}),d!==void 0?jsx(mR,{...wi,attachments:d}):jsx(Nc,{...wi,attachments:null}),jsx(Eu,{}),O.meta.hidePoweredBy?null:jsx(C,{tier:"compact",style:w.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(Jd,{chat:P,history:A}),jsx(Qd,{visible:Ht!==null,onSubmit:zc,onSkip:jc}),jsx(ju,{uri:Pt?.uri??null,label:Pt?.label??"",onClose:Vc})]})}i(pR,"ChatBody");function fR({petRef:e,pet:t,onRegistered:r}){let{styles:n}=_e(),o=jl(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:Tn,children:jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(fR,"PetSetupNotice");function mR({attachments:e,...t}){let r=useMemo(()=>sd(),[]),n=Zr({maxPerMessage:e.maxPerMessage??cR,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??dR,pick:e.pick}),[n,e.sources,e.pick]);return jsx(Nc,{...t,attachments:o})}i(mR,"ComposerWithAttachments");function Nc({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=_e(),p=Q(),[f,m]=su(e,n,s);au(a,n===null?null:String(n),f,m);let[g,k]=useState(false),[y,R]=useState(false);useEffect(()=>{R(false);},[n]);let T=d.meta.placeholder??h.placeholder,O=o?.state.uploading??false,w=o?.state.failed??false,b=O||w,S=o?.state.attachments??yR;ln(S.length,p);let P=useCallback(()=>{if(f.trim().length===0||b||[...f].length>Zt)return;let j=o?.state.s3Keys??gR;o!==null&&j.length>0?(l(o.state.attachments.filter(se=>se.status==="uploaded").map(se=>({uri:se.previewUri,filename:se.filename}))),e(f,{imageS3Keys:j}),o.state.clear()):e(f),m(""),R(false);},[f,e,b,o,l]),V=useCallback(()=>{t();},[t]),I=useCallback(j=>{k(false),o!==null&&(R(false),o.state.dismissRejected(),Ot(o.pick,j).then(se=>{if(!se.ok){R(true);return}se.value!==null&&o.state.add(se.value);}));},[o]),x=useMemo(()=>[...f].length>Zt,[f])||b,B=o!==null&&S.length>=o.state.maxPerMessage,re=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&g?jsx(Ku,{sources:o.sources,full:B,onPick:I,onClose:()=>k(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(nd,{attachments:S,rejected:y?hR:o.state.rejected,uploadFailed:w,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:j=>u({uri:j.previewUri,label:j.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:Vl(S.length,o.state.maxPerMessage),accessibilityState:{disabled:B,expanded:g},disabled:B,hitSlop:(Ut-Pi)/2,style:[c.attachControl,B?c.attachControlDisabled:null],onPress:()=>k(j=>!j),children:jsx(Iu,{size:sR,color:B?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(At,{style:c.input,value:f,onChangeText:m,placeholder:T,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:T,onSubmitEditing:P,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:V,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:Tn,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(Nu,{size:oR,color:re,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:P,disabled:x,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:x,busy:O},hitSlop:Tn,style:[c.sendControl,x?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(Du,{size:nR,color:re,testID:"everfur-send-glyph"})})})]})]})]})}i(Nc,"Composer");var yR=Object.freeze([]),gR=Object.freeze([]),hR=Object.freeze({code:"unknown",retryable:true,filename:""});function bR(e,t,r){switch(e){case "loading":return r.renderPending?jsx(ht,{render:r.renderPending,fallback:jsx(Fc,{})}):jsx(Fc,{});case "empty":return jsx(vR,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(ER,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(RR,{messages:t.messages,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet});default:return qe(e)}}i(bR,"renderView");function Fc(){let{theme:e,styles:t}=_e(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),NE);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(Fc,"LoadingState");function vR({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=_e();return jsxs(ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsx(pc,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(Uc,{prompts:r,onSelectPrompt:n})]})}i(vR,"EmptyState");function Uc({prompts:e,onSelectPrompt:t}){let{styles:r}=_e();return e.length===0?null:jsxs(View,{style:r.followUps,children:[jsx(C,{tier:"compact",style:r.followUpsLabel,accessibilityRole:"header",children:h.followUps}),e.map((n,o)=>jsx(CR,{prompt:n,index:o,onSelectPrompt:t},n))]})}i(Uc,"FollowUps");function CR({prompt:e,index:t,onSelectPrompt:r}){let{styles:n}=_e(),o=Q(),s=vt(o.followUpInMs,{delayMs:Jr(o,t)});return jsx(Animated.View,{style:s,children:jsx(Pressable,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,style:[n.followUpRow,t>0?n.followUpDivider:null],children:jsx(C,{style:n.followUpText,children:e})})})}i(CR,"FollowUpRow");function ER({error:e,onRetry:t,onAddPet:r}){let{styles:n}=_e(),o=zl(e)?Jl(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(ER,"ErrorState");function RR({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:m,onStartNew:g,petRef:k,onFindVet:y,vet:R}){let{styles:T}=_e(),O=Q();ln(e.length,O);let w=hu(e,n),b=e[e.length-1];return jsxs(ScrollView,{style:T.list,contentContainerStyle:T.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(S=>S.checkin?jsx(Ud,{message:S,checkin:S.checkin,onAnswer:o,petRef:k,onFindVet:y,vet:R},S.id):jsx(TR,{message:S,revealing:n&&S===b&&S.role==="assistant",onCopy:s,sentiment:S.responseId===void 0?null:a[String(S.responseId)]??null,onSentiment:l,thanks:u!==null&&S.responseId!==void 0&&String(S.responseId)===u,images:d[S.id]??PR,onPreview:c},S.id)),f?jsx(C,{tier:"compact",style:T.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,w?jsx(Rc,{}):null,p!==null?jsx(SR,{notice:p,onRetry:m,onStartNew:g}):null,n?null:jsx(Uc,{prompts:t,onSelectPrompt:r})]})}i(RR,"PopulatedState");function SR({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=_e(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Tn,style:n.turnNoticeAction,children:jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(SR,"TurnNoticeCard");var PR=Object.freeze([]);function TR({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l}){let{styles:u}=_e(),d=Q(),c=vt(d.messageInMs),p=zu(e.text,t,d),f=e.role==="user",m=f?h.senderUser:h.senderAssistant,g=useCallback(y=>o(e,y),[o,e]),k=e.pending!==true;return jsxs(Animated.View,{style:[u.rowBlock,f?u.rowBlockUser:u.rowBlockAssistant,c],children:[jsx(View,{style:[u.row,f?u.rowUser:u.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${m}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[u.bubble,f?u.bubbleUser:u.bubbleAssistant,e.pending?u.bubblePending:null],children:[f&&a.length>0?jsx(od,{images:a,onPreview:y=>l({uri:y.uri,label:y.filename})}):null,jsx(C,{style:f?u.bubbleTextUser:u.bubbleTextAssistant,children:f?e.text:yc(p,{bold:u.bubbleBold,italic:u.bubbleItalic,code:u.bubbleCode})})]})}),!f&&!t?jsx(Kd,{citations:e.citations}):null,k?jsx(ic,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:g,thanks:s}):null]})}i(TR,"MessageRow");function _e(){let e=M(),t=useMemo(()=>kR(e),[e]);return {theme:e,styles:t}}i(_e,"useChatTheme");function kR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:_c,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:_c,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:uR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:lR,gap:18},errorText:{...E(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Ut,minWidth:Ut,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...ce(s.primaryButton)},retryLabel:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...Te(s.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.lg,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Ut,justifyContent:"center"},turnNoticeActionLabel:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...E(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},list:{flex:1},listContent:{padding:r.lg,gap:r.md},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:BE},bubbleUser:{padding:wc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:Pn,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:HE,shadowRadius:zE,shadowOffset:{width:0,height:jE},elevation:WE,...ce(s.userBubble,Pn)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...ce(s.assistantBubble,Pn)}:{padding:wc,borderRadius:n.xl,...ce(s.assistantBubble,Pn)},bubblePending:{opacity:GE},bubbleTextUser:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:Ic,...Te(s.userBubble)},bubbleTextAssistant:{...E(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:Ic,...Te(s.assistantBubble)},bubbleBold:E(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:E(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,borderRadius:n.md,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},followUpsLabel:{...E(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase",paddingHorizontal:r.md,paddingTop:r.md,paddingBottom:r.sm},followUpRow:{minHeight:Ut,justifyContent:"center",paddingHorizontal:r.md,paddingVertical:r.sm},followUpDivider:{borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.brandBorder},followUpText:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:qE,justifyContent:"center",paddingLeft:$E,paddingRight:YE,paddingVertical:XE,backgroundColor:t.composerFill,borderWidth:Ac,borderColor:t.composerBorder,borderRadius:KE,shadowColor:t.shadow,shadowOpacity:ZE,shadowRadius:JE,shadowOffset:{width:0,height:eR},elevation:tR,...ce(s.composerInput,Ac)},composerRow:{flexDirection:"row",alignItems:"center",gap:QE,minHeight:Oc},attachControl:{width:Pi,height:Pi,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:aR},input:{flex:1,minHeight:Oc,maxHeight:VE,paddingHorizontal:0,paddingVertical:0,...E(e,"regular"),fontSize:o.size.body,lineHeight:rR,color:t.text.primary,...Te(s.composerInput)},sendControl:{minHeight:Nt,minWidth:Nt,alignItems:"center",justifyContent:"center"},sendDisc:{width:Nt,height:Nt,borderRadius:Nt/2,alignItems:"center",justifyContent:"center",...ce(s.sendButton)},sendControlDisabled:{opacity:iR},poweredBy:{...E(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(kR,"makeStyles");function AR(e){let{runtime:t,userRef:r,scopeEpoch:n}=q(),o=useMemo(()=>$e(t.registry.services.authFor(r)),[t,r,n]),s=useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=useRef(0),c=useCallback(async()=>{let p=++d.current;if(s.petRef===null){l({key:s,profile:null,loading:false,error:null});return}l(m=>({key:s,profile:m.key===s?m.profile:null,loading:true,error:null}));let f=await s.repository.getPetProfile(s.petRef);p===d.current&&l(f.ok?{key:s,profile:f.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:f.error});},[s]);return useEffect(()=>(c(),()=>{d.current+=1;}),[c]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(AR,"useEverfurPetProfile");function FR(e){return createElement(Yr,{clientTheme:e.clientTheme??null,seams:Qr,children:e.children})}i(FR,"EverfurThemeProvider");export{Po as CapabilityGate,Dc as EverfurChat,$ as EverfurConfigError,kg as EverfurProvider,FR as EverfurThemeProvider,Cr as EverfurThrownError,Um as THEME_SLOT_KEYS,wt as THEME_SLOT_NAMES,tr as canonicalPetSpecies,_n as categoryFor,Jc as conversationId,mp as createRnRecordsUploadTransport,E as face,$c as isErr,qc as isOk,wn as isRetryableCode,Qc as petRef,by as previewTheme,Yc as unwrap,It as useCapability,Zr as useChatAttachments,cl as useEverfur,ar as useEverfurChat,AR as useEverfurPetProfile,cn as useEverfurPets,M as useEverfurTheme,xt as userFacingError,Zc as userRef};
11
+ `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),em(r.source,l)}i(Jf,"eventSourceByteSource");async function*em(e,t){try{yield*e;}finally{t();}}i(em,"sourceWithCleanup");function tm(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(tm,"createByteQueue");async function rm(e,t){let r=t.fetchImpl??Ns(),n=Us(t.config.apiBaseUrl,e.path,e.query),o=Vs(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=lm(Zf),a=um(s.signal,e.signal),l;try{l=await r(n,Hs({...e,signal:a},o));}catch(d){return v(qn(d))}finally{s.cancel();}let u=await Bs(l);return l.ok?M(u):v(im(l.status,u,Ls(l)))}i(rm,"requestJson");function Ms(e){return {request:i(t=>rm(t,e),"request"),stream:i((t,r)=>nm(am(t,r),e),"stream")}}i(Ms,"createHttpTransport");async function*nm(e,t){let r=Us(t.config.apiBaseUrl,e.path,e.query),n=Vs(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,om(e,n));yield*Ur(Jf(l),()=>sm(l));return}let o=t.fetchImpl??Ns(),s;try{s=await o(r,Hs(e,n));}catch(l){yield As("",true,Gs(l));return}let a=Ls(s);if(!s.ok){let l=await Bs(s),u=zs(l)??Ds(s.status),d=Ws(l)||He(Ae(u));yield As(u,d,js(l),a);return}if(s.body){yield*Ur(Is(s.body),a);return}yield*Ur(Is(null),a);}i(nm,"streamFrames");function om(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(om,"buildEventSourceInit");function im(e,t,r){let n=zs(t),o=n?Ae(n):us(e),s=js(t);return D(o,{httpStatus:e,...Ws(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Os(t)?{reasonCode:Os(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(im,"errorFromResponse");function qn(e){return D("internalError",{retryable:true,wireMessage:Gs(e)})}i(qn,"networkError");function Ls(e){let t=e.headers.get(Fs);return typeof t=="string"&&t.length>0?t:null}i(Ls,"requestIdOf");function sm(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Fs);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(sm,"eventSourceRequestId");function Ds(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Ds,"statusToWireCode");function As(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(As,"syntheticErrorFrame");function Ns(){let e=globalThis.fetch;if(typeof e!="function")throw new Q("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Ns,"getGlobalFetch");function Us(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(Us,"buildUrl");function Vs(e,t,r,n){let o={...ws(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Vs,"mergeHeaders");function Hs(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Hs,"buildInit");function am(e,t){return e.signal?e:{...e,signal:t}}i(am,"withSignal");function lm(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(lm,"timeoutSignal");function um(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(um,"mergeAbortSignals");async function Bs(e){try{return await e.json()}catch{return null}}i(Bs,"safeJson");function Os(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Os,"extractReasonCode");function zs(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(zs,"extractWireCode");function js(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(js,"extractWireMessage");function Ws(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Ws,"extractRetryable");function Gs(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Gs,"describeCause");var dm=3e4,cm=zn*2,pm="idempotency-key",fm=new Set(["POST","PUT","PATCH","DELETE"]),mm=Object.freeze({onEvent(){}}),ym=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function gm(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(gm,"seededIdempotencyKey");function ke(e){let t=e.observer??mm,r=e.timers??ym,n=e.rng??Math.random,o=e.sleep??((f,m)=>wm(f,r,m)),s=e.maxAttempts??Yt,a=e.unaryTimeoutMs??dm,l=e.newIdempotencyKey??bm(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let k=y?.maxAttempts,g=Math.max(1,k??s),R=y?.idempotent??fm.has(m.method),w=y?.idempotencyKey===void 0?null:gm(y.idempotencyKey),_=R?w??l():null,x=hm(m,_),b=0;for(;;){let P=i(j=>Object.freeze({call:f,method:m.method,path:m.path,attempt:b,..._?{idempotencyKey:_}:{},...j}),"stamp");u(P({phase:"attempt"}));let L=xm(a,r),I=_m(L.signal,m.signal),S;try{S=await Rs({...x,signal:I.signal},e.auth);}catch(j){S=v(qn(j));}finally{I.dispose(),L.cancel();}if(S.ok)return u(P({phase:"settled",ok:true,reason:"ok"})),S;let O=S.error,T=Cm(O,b,{maxAttempts:g,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...k!==void 0?{perCallMaxAttempts:k}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:O.code,reason:T.reason,...O.httpStatus!==void 0?{httpStatus:O.httpStatus}:{},...O.requestId!==void 0?{requestId:O.requestId}:{}};if(!T.retry)return u(P({phase:"settled",...V})),v(O);if(u(P({phase:"retry",...V,delayMs:T.delayMs})),await o(T.delayMs,m.signal),m.signal?.aborted===true)return u(P({phase:"settled",...V,reason:"aborted"})),v(O);b+=1;}}i(d,"send");async function c(f){return Xt(f,await km(e.auth))}i(c,"authorize");async function*p(f,m,y){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,y);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(ke,"createRequestFunnel");function hm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==pm&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(hm,"assembleHeaders");function bm(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(bm,"defaultIdempotencyKeyFactory");var vm=10;function Cm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Em(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!He(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(vm,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=Rm(e,r.now);return u!==null?u>cm?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Dr(t,r.rng)}}i(Cm,"decideRetry");function Em(e){let t=e.code==="unknown"?Ae(Pm(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Em,"throttleKind");function Rm(e,t){let r=Sm(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(Rm,"retryOverrideMs");function Sm(e){for(let t of qs(e)){let r=t.resets_at,n=Tm(r);if(n!==null)return n}return null}i(Sm,"findResetsAt");function qs(e){if(!Ks(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Ks(n)&&t.push(n);}return t}i(qs,"candidateScopes");function Tm(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Tm,"parseInstantMs");function Pm(e){for(let t of qs(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Pm,"rawWireCode");function Ks(e){return typeof e=="object"&&e!==null}i(Ks,"isRecord");async function km(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(km,"resolveDeviceAuth");function xm(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(xm,"boundedSignal");function _m(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(_m,"mergeSignals");function wm(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(wm,"delayAbortable");var Vr=Object.freeze(["better","same","worse"]),Yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $s(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i($s,"invalid");function $n(){return v(D("internalError",{retryable:false}))}i($n,"malformed");function Ys(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Re(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Ys,"petPath");var Be=i(e=>typeof e=="string"?e:null,"str"),Xs=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function Qs(e){if(typeof e!="object"||e===null)return null;let t=e,r=Be(t.case_id),n=Be(t.status);if(r===null||n===null)return null;let o=Be(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Be(t.body_location),lastResponse:o!==null&&Vr.includes(o)?o:null,checkInDueAt:Be(t.check_in_due_at),openedAt:Be(t.opened_at),resolvedAt:Be(t.resolved_at),resolutionText:Be(t.resolution_text),checkinAskCount:Xs(t.checkin_ask_count),checkinAnswerCount:Xs(t.checkin_answer_count)})}i(Qs,"caseFromWire");function Zs(e){return {async list(t,r){let n=Ys(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return $n();let a=s.map(Qs);return a.every(l=>l!==null)?M(Object.freeze(a)):$n()},async checkin(t,r,n,o){let s=Ys(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!Yn.test(r))return $s("case_id must be a UUID");if(!Vr.includes(n))return $s("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=Qs(l.case);return u===null?$n():M(Object.freeze({case:u,ctaDeepLink:Be(l.cta_deep_link)}))}}}i(Zs,"createCasesRepositoryOver");var Js=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ea=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Br(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(Br,"delayAbortable");function zr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(zr,"mergeSignals");var Xn=class Xn{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?zr(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(Xn,"MediaStore");var Hr=Xn;function Zn(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Zn,"makeUser");function Jn(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(Jn,"makeAssistant");function Jt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(Jt,"stripPending");function ta(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(ta,"appendText");function eo(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(eo,"finalizeAssistant");function ra(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(ra,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function to(e){let t=Ae(e.code);return D(t,{retryable:e.retryable||Lr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(to,"errorFromFrame");function Oe(e){return pe({code:Im(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Oe,"synthErrorFrame");function Im(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Xe(e)}}i(Im,"canonicalWireCode");function na(e){let t=Array.isArray(e)?e:Qn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!Qn(n))continue;let o=Zt(n.category)??Zt(n.title)??"",s=Am(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(na,"parsePromptCategories");function ro(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(ro,"flattenPrompts");function Qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Qn,"isPlainObject");function Zt(e){return typeof e=="string"?e:null}i(Zt,"asStr");function Am(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Qn(r)){let n=Zt(r.text)??Zt(r.prompt)??Zt(r.title);n!==null&&t.push(n);}return t}i(Am,"asPromptTextList");function oa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(oa,"defaultIdFactory");function ia(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(ia,"defaultIdempotencyFactory");var aa={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*la(e,t,r,n){let o=e[Symbol.asyncIterator](),s=sa(t.overallMs,n),a=sa(t.idleMs,n),l=Mm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Fm();return}if(d.tag==="idle"||d.tag==="overall"){yield Om();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(la,"withWatchdog");function Om(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Om,"synthTimeoutFrame");function Fm(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Fm,"synthStreamErrorFrame");function sa(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(sa,"deadline");function Mm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Mm,"abortPromise");var Lm="checkin",Dm=/^\d{4}-\d{2}-\d{2}$/,jr="watching";function ua(e){return e.status!=null&&e.status!==jr}i(ua,"isCheckinSettled");function da(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(da,"isLiveAskAnswered");function no(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Lm||n===void 0||o===void 0||!Yn.test(n)||!Dm.test(o)?null:{caseId:n,dueDay:o}}i(no,"parseCheckinOrigin");function ca(e){return no(e)?.caseId??null}i(ca,"parseCheckinOriginRef");function oo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Re(o))return v(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(oo,"historyQuery");function rr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(rr,"validConversationId");function tr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(tr,"object");function pa(e){return e==null||typeof e=="string"&&e.length>0&&!Re(e)}i(pa,"cursor");function er(){return v(D("internalError",{retryable:false}))}i(er,"malformed");function fa(e){let t=tr(e);if(!t||!Array.isArray(t.conversations)||!pa(t.next_cursor))return er();let r=[];for(let n of t.conversations){let o=tr(n);if(!o||typeof o.conversation_id!="string"||!rr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return er();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return er();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return M(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(fa,"mapConversationPage");function ma(e){let t=tr(e);if(!t||!Array.isArray(t.messages)||!pa(t.next_cursor))return er();let r=[],n=new Set;for(let o of t.messages){let s=tr(o);if(!s||typeof s.message_id!="string"||!rr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return er();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?ca(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Nm(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Um(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return M(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ma,"mapMessagePage");function Nm(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Nm,"normalizeUrgency");function Um(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=tr(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(Um,"historyCitations");var io=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),At=4e3;var Ot=4e3;function ya(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(ya,"validateImageKeys");function ao(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Ot?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ot}`)}:null}i(ao,"validateMessageText");function ga(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(ga,"urgencyTier");async function*nr(e){yield e;}i(nr,"singleFrameStream");async function*ha(){}i(ha,"emptyStream");var Vm=6e4,Hm=18e4,Bm=24,zm=512,jm=false;function ba(e){return new lo(e)}i(ba,"createChatController");var uo=class uo extends Hr{constructor(r){super(ra({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??ke({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Zs(this.funnel),this.telemetry=r.telemetry??Nr,this.errorPolicy=r.errorPolicy??ps,this.timers=r.timers??aa,this.rng=r.rng??Math.random,this.newId=r.newId??oa(),this.makeIdempotencyKey=r.makeIdempotencyKey??ia(),this.budget={idleMs:r.budget?.idleMs??Vm,overallMs:r.budget?.overallMs??Hm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):nr(Oe(u))}let a=ao(r)??ya(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):nr(Oe(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return nr(Oe(U("accessDenied",false)));let o=ao(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),nr(Oe(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):ha()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Zn(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?Jt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(ro(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=oo(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=fa(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?M(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return M(null);let l=await this.resumeConversation(a.id);return l.ok?M(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return M(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),M(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Re(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!io.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${io.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>At)return v(U("validationFailed",false,`notes is over ${At} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return M(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!rr(r))return v(U("validationFailed",false));let o=oo(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?ma(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!rr(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),M(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===jr).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId),f=c.openedAt??p?.openedAt??null,m=s.has(c.caseId),y=p!==void 0&&(!m||da({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?jr:p?.status??"resolved",answer:c.answer??y,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return M(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),M(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return M(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),M(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Oe(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return M(n);let o=this.snapshot.conversationId;return o!==null?M(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):M(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Re(o))return v(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?M(na(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=zr(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Zn(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let g=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;g.ok&&this.snapshot.conversationId===null&&this.adoptConversation(g.value);}if(u&&this.snapshot.conversationId===null){let g=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!g.ok){yield*this.emitTerminal(r,g.error,Oe(g.error));return}this.adoptConversation(g.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let g=U("internalError",!0);yield*this.emitTerminal(r,g,Oe(g));return}this.clearAssistantInProgress(r);let p=new AbortController,f=zr(o.signal,p.signal),m=null;try{let g;try{g=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let w=this.authRejected();yield*this.emitTerminal(r,w,Oe(w));return}if(o.signal.aborted||!this.alive(o.epoch))return;let R=this.funnel.stream("chat.send",g,f);for await(let w of la(R,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(w.kind==="error"&&w.terminal){m=w;break}if(this.applyFrame(w,r),yield w,w.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let g=U("streamIncomplete",!0);yield*this.emitTerminal(r,g,Oe(g));return}let y=Ae(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let g=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!g){let R=this.authRejected();yield*this.emitTerminal(r,R,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let g=this.authRejected();yield*this.emitTerminal(r,g,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,to(m),m);return}if(ds(y)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let k=m.retryable&&Lr(y,!0);if(jm&&k&&s+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,to(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Xe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?Jt(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,Jn(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=zm){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Bm);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?ta(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?eo(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?Jt(d):d),eo(Jn(l,"",this.stamp()),r)];}let a=ro([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=ga(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?Jt(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(uo,"ChatControllerImpl");var lo=uo;async function Ea(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(x=>x.ok?M(o):x):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),k=null;if(m.ok)k=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let x=m.error;c=x,va(x)?(l=true,d=x):(Ca(x)&&(a=true),u=true);}let g=[];y.ok?g=y.value:R(y.error);function R(x){va(x)?(l=true,d===null&&(d=x)):Ca(x)&&(a=true);}i(R,"recordAuthSignals");let w=d!==null?d.displayMessage:null;return Object.freeze({conversationId:k,petRef:n,suggestedPrompts:g,error:w,warning:w===null&&k===null&&u?Wm:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Ea,"bootstrapChat");var Wm="Chat is ready. Your first message will start the conversation.";function va(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(va,"isUnauthorized");function Ca(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ca,"isForbidden");var co=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ra(e){return e!==co}i(Ra,"isUploadTransportAvailable");var Gm=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Wr=10*1024*1024,Gr=5,or=120,Km="/widget/v1/uploads/initiate";function qm(e){return typeof e=="string"&&Gm.includes(e.trim().toLowerCase())}i(qm,"isAttachmentMime");function po(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=or)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,or);let n=t.slice(r);return n.length>=or?t.slice(0,or):`${t.slice(0,r).slice(0,or-n.length)}${n}`}i(po,"sanitizeFilename");function fo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(fo,"formatBytes");var ir=i(e=>Object.freeze({ok:true,value:e}),"ok"),xe=i(e=>Object.freeze({ok:false,error:e}),"err");function oe(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(oe,"failure");function $m(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i($m,"attachmentSize");function Ym(e){let t=po(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!qm(r))return xe(oe("unsupported_type",false,t));let n=$m(e);return n===null?xe(oe("unknown",false,t)):n>Wr?xe(oe("too_large",false,t,{sizeBytes:n})):ir(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Ym,"validateAttachment");function Xm(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),a=r(t.s3_key);if(o===null||s===null||a===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Wr,s3_key:a,purpose:r(t.purpose)})}i(Xm,"parsePolicy");function Qm(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return oe("quota_exceeded",false,t,{cause:e});case "rateLimited":return oe("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return oe("idempotency_conflict",true,t,{cause:e});case "validationFailed":return oe("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return oe("network",true,t,{cause:e});default:return r===429?oe("rate_limited",true,t,{cause:e}):r===503?oe("network",true,t,{cause:e}):r===void 0?oe("network",true,t,{cause:e}):oe("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Qm,"initiateFailure");async function Zm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Km,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return xe(Qm(n.error,t.filename));let o=Xm(n.value);return o===null?xe(oe("server",false,t.filename)):ir(o)}i(Zm,"initiateAttachmentUpload");async function Jm(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return xe(oe("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),ir(void 0)}catch{return o()?xe(oe("cancelled",true,r.filename)):xe(oe("server",true,r.filename))}}i(Jm,"uploadAttachmentBytes");var ey=2,ty=3,ry=Object.freeze([1e3,2e3,4e3]),Sa=0;function ny(){return Sa+=1,`attachment-${Sa}`}i(ny,"defaultNewId");function Ta(e){let t=Math.max(1,e.concurrency??ey),r=Math.max(1,e.maxAttempts??ty),n=e.backoffMs??ry,o=Math.max(1,e.maxPerMessage??Gr),s=e.timers??ea,a=e.newId??ny,l=Ra(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,k=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let P=u.get(b);return P===void 0?[]:[P.state]}))});for(let b of f)b();},"publish"),g=i((b,P)=>{b.state=Object.freeze({...b.state,...P}),k();},"patch"),R=i(()=>{for(;!y&&p.size<t&&c.length>0;){let b=c.shift(),P=u.get(b);P!==void 0&&(p.add(b),w(P).finally(()=>{p.delete(b),R();}));}},"pump"),w=i(async b=>{let{attachment:P}=b;for(;b.attempts<r;){if(y||b.controller.signal.aborted)return;b.attempts+=1;let L=b.controller.signal;g(b,{status:"uploading",error:null,progress:0});let I=await Zm(e.funnel,P,{signal:L});if(y||L.aborted)return;let S;if(!I.ok)S=xe(I.error);else {let j=await Jm(e.transport,I.value,P,{signal:L,onProgress:i(G=>{!L.aborted&&b.state.status==="uploading"&&g(b,{progress:oy(G)});},"onProgress")});if(y||L.aborted)return;S=j.ok?ir(I.value.s3_key):xe(j.error);}if(S.ok){g(b,{status:"uploaded",s3Key:S.value,error:null,progress:1});return}let O=S.error,T=O.retryable&&b.attempts<r;if(g(b,{status:T?"uploading":"failed",error:O,progress:0}),!T)return;let V=n[Math.min(b.attempts-1,n.length-1)]??0;await Br(V,L,s);}},"run"),_=i(b=>{c.push(b.state.id),R();},"enqueue"),x={available:l,subscribe(b){return f.add(b),()=>{f.delete(b);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(b=>b.status==="uploading")},get s3Keys(){return m.attachments.flatMap(b=>b.status==="uploaded"&&b.s3Key!==null?[b.s3Key]:[])},add(b){let P=Ym(b);if(!P.ok)return P;if(y||d.length>=o)return xe(oe("too_many",false,P.value.filename));let L=a(),I={attachment:P.value,controller:new AbortController,attempts:0,state:Object.freeze({id:L,filename:P.value.filename,previewUri:b.uri,contentType:P.value.contentType,sizeBytes:P.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(L,I),d.push(L),k(),_(I),ir(I.state)},retry(b){let P=u.get(b);P===void 0||y||P.state.status!=="failed"||(P.controller=new AbortController,P.attempts=0,g(P,{status:"uploading",error:null,progress:0,s3Key:null}),_(P));},remove(b){let P=u.get(b);if(P===void 0)return;P.controller.abort(),u.delete(b);let L=d.indexOf(b);L>=0&&d.splice(L,1);let I=c.indexOf(b);I>=0&&c.splice(I,1),k();},clear(){for(let b of [...d])x.remove(b);},dispose(){y=true;for(let b of u.values())b.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return x}i(Ta,"createAttachmentQueue");function oy(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(oy,"clamp");var Pa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function sr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Pa,t)?Pa[t]:null}i(sr,"canonicalPetSpecies");var ka=50,iy=128,mo=120,xa=120,sy=2e3,_a=120,ay=80,Aa=new Set(["male","female","unknown"]),Oa=new Set(["day","month","year"]),Fa=new Set(["low","medium","high","athletic"]),Ma=new Set(["indoor","outdoor","both"]),La=new Set(["mild","moderate","severe"]),ly=/^(\d{4})-(\d{2})-(\d{2})$/,Da=[["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"]],Na=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Da,...Na].map(([e])=>e));function uy(e){let t=ly.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(uy,"isRealDate");var lr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),dy=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),qr=i((e,t)=>typeof t=="string"&&uy(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Fe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Re(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=it(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),cy={sex:lr(Aa),spayedNeutered:dy,birthDate:qr,birthDatePrecision:lr(Oa),activityLevel:lr(Fa),indoorOutdoor:lr(Ma),foodBrand:Fe(_a),foodType:Fe(_a),microchipId:Fe(ay)},yo=["ref","ref",false,Fe(iy,{required:true,trimmed:true})],go=["notes","notes",false,Fe(sy,{trimmed:true})],wa=[yo,["name","name",true,Fe(mo,{required:true,trimmed:true})],["dose","dose",false,Fe(xa,{trimmed:true})],["frequency","frequency",false,Fe(xa,{trimmed:true})],["startDate","start_date",false,qr],["endDate","end_date",false,qr],go],py={allergies:[yo,["allergen","allergen",true,Fe(mo,{required:true,trimmed:true})],["severity","severity",false,lr(La)],go],medications:wa,supplements:wa,conditions:[yo,["conditionName","condition_name",true,Fe(mo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,qr],go]};function fy(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[u,d,c,p]of py[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};s[d]=f;}let a=s.start_date,l=s.end_date;return typeof a=="string"&&typeof l=="string"&&l<a?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(fy,"itemToWire");function my(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>ka)return {error:`${e} has ${t.length} items; the server accepts at most ${ka}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=fy(e,o,t[o]);if("error"in s)return s;let a=s.item.ref;if(typeof a=="string"){let l=a.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(s.item);}return {items:r}}i(my,"listToWire");function Ua(e,t){let r=e,n={};for(let[a,l]of Da){let u=r[a];if(u!==void 0){if(u!==null){let d=cy[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[a,l]of Na){let u=r[a];if(u===void 0)continue;let d=my(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&sr(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Ua,"petHealthToWire");var ee=i(e=>typeof e=="string"?e:null,"str"),ar=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),yy=i(e=>typeof e=="boolean"?e:null,"bool");function Kr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Kr,"itemsFromWire");function Ia(e){let t=ee(e.name);return t===null||t.length===0?null:Object.freeze({ref:ee(e.ref),name:t,dose:ee(e.dose),frequency:ee(e.frequency),startDate:ee(e.start_date),endDate:ee(e.end_date),notes:ee(e.notes)})}i(Ia,"medicationFromWire");function Va(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ar(Aa,e.sex),spayedNeutered:yy(e.spayed_neutered),birthDate:ee(e.birth_date),birthDatePrecision:ar(Oa,e.birth_date_precision),activityLevel:ar(Fa,e.activity_level),indoorOutdoor:ar(Ma,e.indoor_outdoor),foodBrand:ee(e.food_brand),foodType:ee(e.food_type),microchipId:ee(e.microchip_id),allergies:Kr(e.allergies,r=>{let n=ee(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),allergen:n,severity:ar(La,r.severity),notes:ee(r.notes)})}),medications:Kr(e.medications,Ia),supplements:Kr(e.supplements,Ia),conditions:Kr(e.conditions,r=>{let n=ee(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),conditionName:n,diagnosedDate:ee(r.diagnosed_date),notes:ee(r.notes)})})})}i(Va,"petHealthFromWire");var za=100,ja=50,Wa=100,Ga=50,Ka=500,gy=128,hy=6e4;function Le(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Le,"invalid");function st(e,t,r){if(typeof t!="string")return Le(`${e} must be a string`);let n=it(t);return n<=r?null:Le(`${e} is ${n} characters; the server accepts at most ${r}`)}i(st,"checkString");function $r(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Le(`${e} must be a finite number between 0 and ${r}`)}i($r,"outOfRange");function Ha(e,t){if(typeof e!="string")return Le("pet_ref must be a string");if(e.trim().length===0)return Le("pet_ref must not be blank");if(Re(e))return Le("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Le("profile must be an object");let r=[st("pet_ref",e,gy)];return t?.name!==void 0&&r.push(st("name",t.name,za)),t?.species!==void 0&&r.push(st("species",t.species,ja)),t?.breed!==void 0&&r.push(st("breed",t.breed,Wa)),t?.ageYears!==void 0&&r.push($r("age_years",t.ageYears,Ga)),t?.weightKg!==void 0&&r.push($r("weight_kg",t.weightKg,Ka)),r.find(n=>n!==null)??null}i(Ha,"validate");function qa(e,t){let r=Ua(e,t);return "error"in r?{error:Le(r.error)}:r}i(qa,"healthToWire");function by(e){if(typeof e!="object"||e===null)return {error:Le("patch must be an object")};let t=e,r=[["name","name",s=>st("name",s,za)],["species","species",s=>st("species",s,ja)],["breed","breed",s=>st("breed",s,Wa)],["ageYears","age_years",s=>$r("age_years",s,Ga)],["weightKg","weight_kg",s=>$r("weight_kg",s,Ka)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=qa(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Le("patch must change at least one field")}:{body:n})}i(by,"patchToWire");function vy(e){if(e==null)return {body:{}};let t=qa(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(vy,"toWire");var Me=i(e=>typeof e=="string"?e:null,"str"),Yr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ba(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Me(r.pet_ref)??t,name:Me(r.name),species:Me(r.species),breed:Me(r.breed),ageYears:Yr(r.age_years),weightKg:Yr(r.weight_kg)})}i(Ba,"fromWire");function $a(e){if(typeof e!="object"||e===null)return null;let t=e,r=Me(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Me(t.pet_id),petRef:r,name:Me(t.name),species:Me(t.species),breed:Me(t.breed),ageYears:Yr(t.age_years),weightKg:Yr(t.weight_kg),updatedAt:Me(t.updated_at)})}i($a,"widgetPetFromWire");function Cy(e){let t=$a(e);return t===null?null:Object.freeze({...t,...Va(e)})}i(Cy,"widgetPetProfileFromWire");function Ey(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=$a(r);return n===null?[]:[n]}))}i(Ey,"petListFromWire");function Qe(e){return Ry(ke({auth:e}),ke({auth:e,unaryTimeoutMs:hy}))}i(Qe,"createPetsRepository");function Ry(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Ha(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?M(Ey(s.value)):v(s.error)},async registerPet(o,s,a){let l=Ha(o,s);if(l!==null)return v(l);let u=vy(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?M(Ba(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=by(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?M(Ba(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=Cy(l.value);return u===null?v(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):M(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?M(void 0):v(l.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?M(void 0):v(s.error)}}}i(Ry,"createPetsRepositoryOver");var bo=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Sy(e){return bo[e]}i(Sy,"requires");function Ya(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(bo))for(let a of bo[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Ya,"deniedDecisionsFor");function Xa(e,t,r){let n=Sy(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return ho({name:e,enabled:false,isPending:true,limits:{}});let s=Ty(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?ho({name:e,enabled:true,isPending:false,limits:s}):ho({name:e,enabled:false,isPending:false,limits:s,disabled:Py(n,o)})}i(Xa,"decideCapability");function Ty(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[s,a]of Object.entries(o)){let l=r[s];r[s]=l===void 0?a:Math.min(l,a);}}return r}i(Ty,"mergeLimits");function Py(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:It("accessDenied"),level:"user_entitlement",recoverable:false})}i(Py,"disabledFor");function ho(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(ho,"freezeDecision");function ye(e){let t=ie(e);return t===null?null:xy(t)}i(ye,"parseColor");function ie(e){if(typeof e=="number")return Qa(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return vo(t.slice(1));if(t.toLowerCase().startsWith("0x"))return vo(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return ky(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=vo(t);if(r!==null)return r}return /^\d+$/.test(t)?Qa(Number.parseInt(t,10)):null}i(ie,"toRgba");function vo(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Co(t[0]),g:Co(t[1]),b:Co(t[2]),a:1};if(t.length===6)return {r:at(t,0),g:at(t,2),b:at(t,4),a:1};if(t.length===8){let r=at(t,0);return {r:at(t,2),g:at(t,4),b:at(t,6),a:r/255}}return null}i(vo,"fromHex");function ky(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=Eo(Number(n[0])),s=Eo(Number(n[1])),a=Eo(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(ky,"fromRgbFunc");function Qa(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(Qa,"argbIntToRgba");function at(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(at,"byte");function Co(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Co,"dup");function Eo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Eo,"clampByte");function xy(e){if(e.a>=1)return ut(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(xy,"normalizeRgba");function ut(e,t,r){return `#${Ro(e)}${Ro(t)}${Ro(r)}`.toUpperCase()}i(ut,"rgbToHex");function Ro(e){return e.toString(16).padStart(2,"0")}i(Ro,"hex2");var _y="#111111",Ft="#FFFFFF",Xr="#000000";function Ja(e){let t=ie(e);if(t===null)return Ft;let r=lt(t),n=lt({r:17,g:17,b:17}),o=lt({r:255,g:255,b:255});return Po(r,o)>=Po(r,n)?Ft:_y}i(Ja,"readableOn");function ur(e,t){let r=Ja(e);return ue(r,e)>=t?r:ue(Ft,e)>=ue(Xr,e)?Ft:Xr}i(ur,"legibleOn");function dr(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ft)>=t(Xr)?Ft:Xr}i(dr,"poleForGrounds");function lt(e){let t=So(e.r/255),r=So(e.g/255),n=So(e.b/255);return .2126*t+.7152*r+.0722*n}i(lt,"relativeLuminance");function So(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(So,"linearize");function Po(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Po,"luminanceContrast");function ue(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:el(r,o);return Po(lt(s),lt(o))}i(ue,"contrastRatio");function el(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(el,"composite");function dt(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return null;let o=r.a>=1?r:el(r,{...n});return ut(o.r,o.g,o.b)}i(dt,"flattenOnto");function tl(e,t){let r=ie(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i(tl,"withAlpha");var Za=.05;function Ze(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(ie(e)===null)return r;if(s(e))return e;let a=dt(e,o),l=a===null?null:ie(a),u=ie(r);if(l===null||u===null)return r;for(let d=1;d<1/Za;d+=1){let c=d*Za,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=ut(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(Ze,"pushToContrast");function rl(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(rl,"rgbToHsl");function ko(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:To(c+l),g:To(p+l),b:To(f+l)}}i(ko,"hslToRgb");function To(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(To,"channel");function ze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ze(e[t]);}return e}i(ze,"deepFreeze");var Zr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ol={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},il={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},nl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},wy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Iy={regular:"400",medium:"500",bold:"700"},Ay={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},xo=0,ct="System",De="monospace",Oy=["content","heading","control","compact","badge"];function Fy(e){let t={};for(let r of Oy)t[r]=e;return t}i(Fy,"authoredTierSizes");function sl(){return {family:ct,mono:De,fontUrl:null,families:{regular:ct,medium:ct,bold:ct,mono:De,monoMedium:De,monoBold:De},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:nl,tierSizes:Fy(nl),lineHeight:wy,weight:Iy,letterSpacing:Ay,scale:1,maxScale:xo,scaleCaps:Zr}}i(sl,"baseType");var al={},pt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Qr(e){return `cubic-bezier(${e.join(", ")})`}i(Qr,"cssCubicBezier");var ll={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Qr(pt.standard),emphasized:Qr(pt.emphasized),exit:Qr(pt.exit)},reducedMotion:false},My={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:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",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:"#B91C1C",errorRed:"#FF1B00",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(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ft=ze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:My,space:ol,radius:il,type:sl(),motion:ll,slots:al}),Ly={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:"#9A938C",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",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",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Jr=ze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ly,space:ol,radius:il,type:sl(),motion:ll,slots:al});var Dy="#23272C",ul=4.5,Ny=.6,_o=.9,Uy=.02,Vy="#FFFFFF",Hy="#111111";function By(e){return ue(e,Dy)>=ul&&Math.max(ue(e,Vy),ue(e,Hy))>=ul}i(By,"readsOnDark");function pl(e){let t=ie(e);if(t===null)return null;let{h:r,s:n,l:o}=rl(t.r,t.g,t.b),s=Math.min(Math.max(o,Ny),_o);for(let l=0;;l+=1){let u=s+l*Uy;if(u>_o)break;let d=ko({h:r,s:n,l:u}),c=ut(d.r,d.g,d.b);if(By(c))return c}let a=ko({h:r,s:n,l:_o});return ut(a.r,a.g,a.b)}i(pl,"deriveDarkVariant");var zy=7,dl=.05,jy="#000000",Wy="#FFFFFF";function Gy(e,t,r,n){let o=dt(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let s=ie(o),a=ie(r);if(s===null||a===null)return r;for(let l=1;l<1/dl;l+=1){let u=l*dl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=ut(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(ue(c,t)>=n)return c}return r}i(Gy,"pushContrast");function Ky(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=cl(n);for(let s of r){let a=cl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(Ky,"hardestGround");function cl(e){let t=ie(e);return t===null?0:lt(t)}i(cl,"luminanceOf");function Je(e,t){return dt(e,t)??ye(e)??t}i(Je,"solid");function fl(e){let t=e.color,r=e.brightness==="dark",n=r?Wy:jy,o=Ky(t,r),s=i(l=>Gy(l,o,n,zy),"text"),a={...t,brandSoft:Je(t.brandSoft,t.surface),brandSofter:Je(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:Je(t.badgeBgPositive,t.surface),badgeBgCaution:Je(t.badgeBgCaution,t.surface),badgeBgCritical:Je(t.badgeBgCritical,t.surface),badgeBgNeutral:Je(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Je(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Je(t.checkupCardConcernBg,t.surface)};return ze({...e,highContrast:true,color:a})}i(fl,"deriveHighContrast");var mt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),qy=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),_e=4.5,$y=Object.freeze({});function Yy(e){return mt.includes(e)}i(Yy,"isSlotName");function Xy(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Xy,"parseRadius");function ml(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Yy(n)||o===null||typeof o!="object")continue;let s=Qy(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(ml,"parseThemeSlots");function en(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(en,"pick");function Qy(e){let t={},r=ye(en(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(en(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Xy(en(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ye(en(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Qy,"parseSlot");function yl(e,t){return t===null||Object.keys(t).length===0?e??$y:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(yl,"mergeThemeSlots");var wo=3;function Zy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>dt(e,r)??r)}i(Zy,"seatsOf");function Jy(e,t){let r=dr(e);return e.every(n=>ue(r,n)>=t)}i(Jy,"someInkReads");function eg(e,t){let r=t[0];return r===void 0?null:dt(e,r)}i(eg,"collapseUnsatisfiableFill");function tg(e){let t=ur(e[0],_e);return e.every(r=>ue(t,r)>=_e)?t:dr(e)}i(tg,"inkFor");function gl(e,t){let r=false,n={};for(let o of mt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=Zy(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!Jy(u,_e)){let p=eg(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>ue(p,f)<_e))&&(d.textColor=tg(u),c=true);else if(p!==void 0){let f=Ze(p,u,dr(u),_e);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=Ze(s.borderColor,u,dr(u),wo);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(gl,"guardSlotContrast");var vl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),cr="slots.",Cl=Object.freeze([1,2]);function tn(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(tn,"isEmptyBranding");function El(e){let t=e?.schemaVersion??null;return t===null||Cl.includes(t)}i(El,"isKnownBrandingSchema");function Rl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Rl,"lockedFieldsOf");function rg(e){return e==="hide_powered_by"||vl.includes(e)?true:e.startsWith(cr)&&mt.includes(e.slice(cr.length))}i(rg,"isThemeLockName");function je(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:yt($(t,"display_name","displayName")),logoUrl:yt($(t,"logo_url","logoUrl")),primaryColor:ye($(t,"primary_color","primaryColor")),accentColor:ye($(t,"accent_color","accentColor")),brightness:sg($(t,"brightness","color_scheme","colorScheme")),fontFamily:yt($(t,"font_family","fontFamily")),fontUrl:yt($(t,"font_url","fontUrl")),fonts:hl($(t,"fonts")),fontUrls:hl($(t,"font_urls","fontUrls")),placeholder:yt($(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:ng($(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye($(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye($(t,"accent_color_dark","accentColorDark")),surfaceStyle:bl($(t,"surface_style","surfaceStyle"),og),radiusScale:bl($(t,"radius_scale","radiusScale"),ig),logoUrlDark:yt($(t,"logo_url_dark","logoUrlDark")),slots:ml($(t,"slots")),accessibilityMaxFontScale:lg($(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:dg($(t,"locked_fields","lockedFields")),schemaVersion:ug($(t,"schema_version","schemaVersion"))};return tn(r)?null:Object.freeze(r)}i(je,"parseClientBranding");function ng(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(ng,"parseBool");function $(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i($,"pick");function yt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(yt,"parseNonEmptyString");var pr=["regular","medium","bold","mono","monoMedium","monoBold"];function hl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of pr){let o=yt($(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(hl,"parseFaceMap");var og=["white","cream","subtle"],ig=["sharp","default","round"];function bl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(bl,"parseEnum");function sg(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(sg,"parseBrightness");function Sl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(Sl,"parseNumber");var ag=1,Tl=3.1;function lg(e){let t=Sl(e);return t===null?null:t<=0?0:Math.min(Tl,Math.max(ag,t))}i(lg,"parseMaxFontScale");function ug(e){if(e==null)return null;let t=Sl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(ug,"parseSchemaVersion");function Io(e){let t=e.trim();return t.startsWith(cr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Io,"toWireName");function dg(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Io(r);rg(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(dg,"parseLockedFields");function Ao(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Ao,"hardenHttpsUrl");function Pl(e,t){if(t===null||tn(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Jr:ft:e,n=r.brightness==="dark"?Jr:ft,o=r.brightness==="dark",s=o?t.primaryColorDark??kl(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??kl(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&yg(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ie(c):null,f=i(k=>Math.round(k+(255-k)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?gg(n,r.color.text):{},y={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...mg(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:bg(t.radiusScale??null,r.radius,n),type:{...r.type,...fg(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:yl(r.slots,t.slots??null)};return ze(y)}i(Pl,"withServerBranding");var cg={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},pg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Oo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(Oo,"isMonoFace");function fg(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of pr){let u=cg[l].map(p=>r[p]).find(p=>p!==void 0),d=Oo(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of pg)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(fg,"mergeFaces");function kl(e){return e===null?null:pl(e)}i(kl,"darkVariantOf");function mg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(mg,"surfaceOf");function xl(e,t){return e==null?false:ye(e)===ye(t)}i(xl,"sameColor");function yg(e,t,r,n){return xl(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&xl(e.primaryColor,ft.color.primary)}i(yg,"isCompiledPrimary");function gg(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(gg,"compiledBrandFamily");var hg={sharp:.5,default:1,round:1.5};function bg(e,t,r){if(e===null)return t;let n=hg[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(bg,"radiusOf");var vg="Everfur",Cg=.5;function Fo(e){let t=e?.branding??null,r=El(t)?t:null,n=Pg(e?.clientOverride??null,Rl(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=Pl((s==="auto"?o:s)==="dark"?Jr:ft,_l(r)),d=Pl(u,_l(n));return Ng(d,e)}i(Fo,"resolveTheme");function Eg(e,t,r){return Fo({...r,branding:je(t),clientOverride:je(e)})}i(Eg,"previewTheme");function Rg(e){return e==="placeholder"?"chat_placeholder":Io(e)}i(Rg,"wireNameOf");var Sg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Tg(e,t){return t.has(Rg(e))?true:(Sg[e]??[]).some(r=>t.has(r))}i(Tg,"isLocked");function Pg(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Tg(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of mt){let d=o[u];d!==void 0&&(t.has(`${cr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return tn(s)?null:s}i(Pg,"withoutFields");function _l(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(_l,"withoutBrightness");function kg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(kg,"scaledSizes");function xg(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Cg,e)}i(xg,"effectiveScale");var wl=["content","heading","control","compact","badge"];function _g(e){if(!(e>0))return Zr;let t={};for(let r of wl){let n=Zr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(_g,"tierCaps");function wg(e,t){return t>0?Math.min(e,t):e}i(wg,"capped");function Ig(e,t,r,n){let o={};for(let s of wl)o[s]=n?kg(e,wg(t,r[s])):e;return o}i(Ig,"sizesByTier");function Ag(e){return e==="dark"?"#FFFFFF":"#000000"}i(Ag,"inkPole");function Og(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Og,"textGrounds");function Fg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Fg,"controlGrounds");function Il(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Il,"linkGrounds");function Mg(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Il(e)}}i(Mg,"slotGrounds");function Lg(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Lg,"registration");function Dg(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of pr)!(o[a]===ct||o[a]===De)&&r!==void 0&&Lg(r,o[a])===false&&(o[a]=Oo(a)?De:ct,s[a]=false),n!==null&&Oo(a)&&o[a]===De&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Dg,"platformFaces");function Ng(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?vg:e.meta.displayName,s=Ao(e.meta.logoUrl),a={};for(let _ of pr){let x=e.type.fontUrls[_];x!==void 0&&(a[_]=Ao(x));}let l=a.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:xo,p=xg(t?.textScale),f=_g(c),m=Ig(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,k=Ag(e.brightness),g=Og(y),R={...y,primary:r,accent:n,onPrimary:ur(r,_e),onAccent:ur(n,_e),brandInk:Ze(y.brandInk,g,k,_e),linkInk:Ze(e.slots.link?.textColor??n,Il(y),k,_e),text:{...y.text,secondary:Ze(y.text.secondary,g,k,_e)},brandBorderStrong:Ze(y.brandBorderStrong,Fg(y),k,wo)},w={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:R,space:e.space,radius:e.radius,type:{...e.type,...Dg(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:gl(e.slots,Mg(R))};return t?.highContrast===true?fl(ze(w)):ze(w)}i(Ng,"finalize");var Al="/widget/v1/entitlements",Ug=304,Vg=Object.freeze({kind:"notModified"});async function Fl(e,t={},r=ke({auth:e})){let n=await r.send("entitlements.fetch",Bg(t));return n.ok?zg(n.value):n.error.httpStatus===Ug?Vg:{kind:"failed",error:n.error}}i(Fl,"fetchEntitlements");var Hg=64;function Bg(e){let t={};return Mo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Hg?{method:"GET",path:Al,headers:t,query:{region:e.region}}:{method:"GET",path:Al,headers:t}}i(Bg,"buildRequest");function zg(e){if(e===null||typeof e!="object"||!Mo(e.revision))return Ol();let t=typeof e.region=="string"?e.region:"",r=Mo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Wg(e.capabilities),branding:jg(e)})}i(zg,"parseUpdated");function jg(e){let t=je(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=je(r.branding);return n!==null?n:je(r)}return null}i(jg,"parseBranding");function Wg(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Gg(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Wg,"mapCapabilities");function Gg(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Gg,"isEnabled");function Ol(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Ol,"malformed");function Mo(e){return typeof e=="number"&&Number.isFinite(e)}i(Mo,"isFiniteNumber");var Kg=30;function Ml(e){let t=e.scheduler??qg,r=e.resolve??Fl,n=Math.max(1,e.floorSeconds??Kg),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(R=>{l||!a||(c=Math.max(n,R),u=t.set(()=>{u=null,g();},c*1e3));},"schedule"),y=null,k=i(async()=>{if(l)return null;let R=p;e.onFetch?.();let w=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},_;try{_=await r(e.authFor(),w);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:$g(x)}),!l&&R===p&&(e.onSettled?.(),m(s())),null}if(l||R!==p)return null;switch(_.kind){case "updated":d=_.revision,e.update(_.decisions,_.branding??null),m(_.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:_.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),_},"tick"),g=i(()=>{let R=k().finally(()=>{y===R&&(y=null);});return y=R,R},"run");return {start(){a||l||(a=true,g());},prime(){return l?Promise.resolve(null):y??g()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),g());}}}i(Ml,"createEntitlementPoller");var qg={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function $g(e){return e instanceof Error?e.message:"poll failed"}i($g,"describe");var Ll="everfur.notifications.device";var Yg=3e3,Dl=Object.freeze([Ll]);function Nl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),a=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:a.length});}catch{}},"report"),u=Promise.allSettled(a).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",a.length),p();},Yg);u.then(p,p);})}i(Nl,"startBeforeLogoutHooks");function Ul(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let a={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:a,userRef:t.userRef,sessionId:o}}i(Ul,"graceAuth");async function Vl(e,t){if(Dl.length===0)return;let r=await Promise.allSettled(Dl.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Vl,"sweepPerUserKv");function Xg(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Xg,"compiledDefaultDecisions");function Lo(e=Xg){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Lo,"createEntitlementStore");function Do(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Do,"notConfiguredError");function Hl(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return _s(r,t===void 0?void 0:{platform:t})}i(Hl,"tryResolveClient");function Bl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Bl,"guardTelemetry");function zl(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
+ [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(zl,"reportConfigFailure");function No(e){return Object.freeze({request(){return Promise.resolve(v(Do(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(No,"refusingTransport");function jl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(jl,"createInMemoryKv");var Wl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function ql(e,t){return new Vo(e,t)}i(ql,"createEverfurRuntime");var Qg=6e4,Ho=class Ho{constructor(t,r){this.sessionId=Wn();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new Q("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Bl(n.telemetry):Nr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Kn(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=No(s);else if(n.transport!==void 0)l=n.transport;else {let c=Hl(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=Ms({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=No(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&zl(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??fs,this.upload=n.upload??Js,this.uploadTransport=n.uploadTransport??co,this.imageCache=n.imageCache??Wl,this.kv=n.storage??jl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Lo():Lo(()=>Ya("sdk_config",It("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Uo(c),()=>this.buildChatController(c),Gl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Uo(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Es(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Qg,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Ml({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=ba({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Ea(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=Wn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Vl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Nl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Ul({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v(Kl(t)):r(Qe(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Kl("prepare"):n===null?null:Do(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?M(void 0):s.currentToken().then(()=>M(void 0),()=>v(D("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):M(void 0):v(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Uo(r),()=>this.buildChatController(r),Gl,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):M(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Ho,"EverfurRuntimeImpl");var Vo=Ho;function Uo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Uo,"chatScopeKey");function Gl(e){e.dispose();}i(Gl,"disposeChat");function Kl(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Kl,"disposedError");var $l=Symbol.for("@everfur/sdk#EverfurContext@v1"),Yl=globalThis,rn=Yl[$l]??(Yl[$l]=createContext(null));rn.displayName??="EverfurContext";function Y(){let e=useContext(rn);if(e===null)throw new Q("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Y,"useEverfurContext");function Xl(){return Y().handle}i(Xl,"useEverfur");var Ql=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Zl=globalThis,fr=Zl[Ql]??(Zl[Ql]=createContext(ft));fr.displayName??="EverfurThemeContext";function F(){return useContext(fr)}i(F,"useEverfurTheme");function nn(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?oh(e.clientTheme):"",f=useMemo(()=>e.clientTheme?je(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>Fo({branding:m,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(y),createElement(fr.Provider,{value:y},e.children)}i(nn,"EverfurThemeProviderCore");function oh(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(oh,"stableKey");function nu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=useRef(null),c=useRef(null),[p,f]=useReducer(T=>T+1,0),m=useRef(null),y=useRef(void 0),k=r?.userRef??null;y.current!==k&&(y.current!==void 0&&(m.current=null),y.current=k);let g=m.current!==null?m.current.user:r??null,R=useRef(null),w=useRef(void 0),_=n??null;w.current!==_&&(w.current!==void 0&&(R.current=null),w.current=_);let x=R.current!==null?R.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:ql({config:l.withDefaults?l.withDefaults(t):t,user:g,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,P=useRef(null);useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||P.current!==T&&(P.current=T,f());}),useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let L=g?.userRef??null;useLayoutEffect(()=>{b.setUser(g);},[b,L]),useLayoutEffect(()=>{b.setActivePet(x);},[b,x]),useEffect(()=>()=>b.dispose(),[b]),useEffect(()=>{s==="onMount"&&b.prepare(x===null?{}:{petRef:x});},[b,s,L,x]);let I=useMemo(()=>({setUser:i(T=>{m.current={user:T},b.setUser(T),f();},"setUser"),setActivePet:i(T=>{R.current={pet:T},b.setActivePet(T),f();},"setActivePet"),open:i(T=>b.open(T),"open"),prepare:i(T=>b.prepare(T),"prepare"),registerPet:i((T,V)=>b.registerPet(T,V),"registerPet"),updatePet:i((T,V)=>b.updatePet(T,V),"updatePet"),deletePet:i(T=>b.deletePet(T),"deletePet"),eraseUserData:i(()=>b.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let T=b.logout();return f(),T},"logout")}),[b,f]),S=useMemo(()=>({runtime:b,handle:I,userRef:L,activePet:x,scopeEpoch:b.scopeEpoch}),[b,I,L,x,p]),O=createElement(nn,{clientTheme:o??null,seams:l.theme,children:a});return createElement(rn.Provider,{value:S},l.wrap?l.wrap(O):O)}i(nu,"EverfurProviderCore");var ah=2;function lh(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<ah)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(lh,"readEventSourceResponseHeader");function ou(){let e=sh;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>lh(n,o),"getResponseHeader")})}}i(ou,"createRnEventSourceFactory");function ph(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(ph,"useRnColorScheme");function fh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(fh,"isThenable");function mh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,n=AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(mh,"useRnReducedMotion");function au(){let e=PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(au,"readFontScale");function yh(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(yh,"subscribeFontScale");function gh(){return useSyncExternalStore(yh,au,au)}i(gh,"useRnTextScale");function cu(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(cu,"platformOS");function hh(){return cu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(hh,"contrastSignal");function bh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=hh(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);fh(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(bh,"useRnHighContrast");function vh(){return cu()==="ios"?"Menlo":De}i(vh,"rnPlatformMonoFamily");function Ch(){return globalThis.__DEV__!==false}i(Ch,"isDevelopment");var lu=new Set;function Eh(e){if(!Ch()||lu.has(e))return;lu.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(Eh,"warnUnregisteredFace");function Rh(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||Eh(e),o}i(Rh,"rnIsFontRegistered");var sn=Object.freeze({useColorScheme:ph,useReducedMotion:mh,useTextScale:gh,useHighContrast:bh,scaleTypeSizes:false,platformMonoFamily:vh,isFontRegistered:Rh});function Th(e){return createElement(SafeAreaProvider,null,e)}i(Th,"wrapInSafeArea");var Ph=Object.freeze({platform:"react-native",eventSourceFactory:ou(),wrap:Th,theme:sn});function kh(e){return createElement(nu,{...e,seams:Ph})}i(kh,"EverfurProvider");function Mt(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Xa(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Mt,"useCapability");function Oh(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Oh,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=F(),n=Oh(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Lt=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Fh=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function E(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Fh[t]]}}i(E,"face");var zo=class zo extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(zo,"HostRenderBoundary");var Bo=zo;function Lh({render:e}){return e()}i(Lh,"RenderHost");function bt({render:e,fallback:t,resetKey:r}){return createElement(Bo,{fallback:t,resetKey:r,children:createElement(Lh,{render:e})})}i(bt,"HostRender");var Dh=48;function Nh(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Nh,"selectView");function Go(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Mt(t),l=useMemo(()=>Nh(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(bt,{render:o,fallback:jsx(gu,{capability:t,style:s})}):jsx(gu,{capability:t,style:s});case "disabled":return n?jsx(bt,{render:()=>n(a),fallback:jsx(hu,{decision:a,style:s}),resetKey:a}):jsx(hu,{decision:a,style:s});default:return Xe(l)}}i(Go,"CapabilityGate");function gu({capability:e,style:t}){let r=F(),n=useMemo(()=>bu(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(gu,"PendingSkeleton");function hu({decision:e,style:t}){let r=F(),n=useMemo(()=>bu(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(C,{style:n.offstateText,children:o}):null})}i(hu,"OffState");function bu(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:Dh,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...E(e,"regular"),fontSize:o.size.body,lineHeight:Math.round(o.size.body*o.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}i(bu,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",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\u2026",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",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another 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 K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var Ko=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),vu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Uh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Uh,"sentimentToFeedbackType");function Cu(e,t){if(e==="down"&&t!==null){let r=Ko.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Uh(e)}i(Cu,"feedbackTypeFor");var zh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function mr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=Y(),s=e?.petRef??n??null,a=e?.conversationId??null,l=useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[u,d]=useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=useRef(null);useEffect(()=>{let S=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=S,d({scope:l,controller:S}),()=>{p.current=null,d(O=>O?.controller===S?null:O),t.registry.releaseChat(S);}},[t,r,s,a,o,l]);let f=useCallback(S=>c?c.subscribe(S):jh,[c]),m=useCallback(()=>c?c.getSnapshot():zh,[c]),y=useSyncExternalStore(f,m,m),k=useCallback((S,O)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?$o(c,c.send(S,O?.imageS3Keys===void 0?{}:{imageS3Keys:O.imageS3Keys}),()=>p.current===c):Promise.resolve(Yo()),[c]),g=useCallback(S=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?$o(c,c.askEverfur(S),()=>p.current===c):Promise.resolve(Yo()),[c]),R=useCallback(()=>c&&p.current===c?$o(c,c.retryLast(),()=>p.current===c):Promise.resolve(Yo()),[c]),w=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),_=useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[x,b]=useState({controller:null,byMessage:{}}),P=x.controller===c?x.byMessage:Wh,L=useCallback(async(S,O,T,V)=>{if(!c||p.current!==c)return v(D("accessDenied"));let j=String(S),G=x.controller===c?x.byMessage[j]:void 0;if(G===O&&T==null)return b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return delete Pe[j],{controller:c,byMessage:Pe}}),M(Object.freeze({feedbackId:""}));b(de=>({controller:c,byMessage:{...de.controller===c?de.byMessage:{},[j]:O}}));let ne=await c.submitFeedback(S,Cu(O,T??null),V??null);return p.current!==c?v(D("accessDenied")):(ne.ok||b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return G===void 0?delete Pe[j]:Pe[j]=G,{controller:c,byMessage:Pe}}),ne)},[c,x]),I=useMemo(()=>{let S=i(async O=>{if(!c||p.current!==c)return v(D("accessDenied"));let T=await O(c);return p.current===c?T:v(D("accessDenied"))},"run");return {listConversations:i(O=>S(T=>T.listConversations({...s?{petRef:s}:{},...O})),"listConversations"),getMessages:i((O,T)=>S(V=>V.getMessages(O,T)),"getMessages"),resumeConversation:i(O=>S(T=>T.resumeConversation(O)),"resumeConversation"),loadOlderMessages:i(()=>S(O=>O.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>S(O=>O.markRead()),"markRead"),refreshActiveThread:i(()=>S(O=>O.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((O,T)=>S(V=>V.answerCheckin(O,T)),"answerCheckin"),openCheckin:i(O=>S(T=>T.openCheckin(O)),"openCheckin")}},[c,s]);return useMemo(()=>({status:y.status,messages:y.messages,conversationId:y.conversationId,petRef:s,error:y.error,isStreaming:y.isStreaming,isBootstrapping:y.isBootstrapping,historyCursor:y.historyCursor??null,isLoadingHistory:y.isLoadingHistory??false,stopped:y.stopped??false,reconnecting:y.reconnecting??false,...I,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:_,sentimentByMessage:P,feedback:L,send:k,askEverfur:g,retryLast:R,stop:w}),[y,s,k,g,R,w,I,_,P,L])}i(mr,"useEverfurChat");var jh=i(()=>{},"NOOP_UNSUBSCRIBE"),Wh=Object.freeze({});async function $o(e,t,r){for await(let o of t);if(!r())return v(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):M(Gh(n.messages))}i($o,"driveToResult");function Gh(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i(Gh,"lastAssistantResponseId");function Yo(){return v(D("internalError",{retryable:true}))}i(Yo,"notReadyError");function Su(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:fo(Wr),filename:e.filename,size:fo(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Gr});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(Su,"attachmentErrorMessage");function Tu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(Tu,"attachControlLabel");var Yh=Object.freeze({attachments:Object.freeze([])});function an(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??Gr,s=useMemo(()=>{if(e.queue)return e.queue;let{services:g}=t.registry;return Ta({funnel:ke({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.queue,e.transport]);useEffect(()=>()=>{s!==e.queue&&s.dispose();},[s,e.queue]);let a=useSyncExternalStore(s.subscribe,s.getSnapshot,()=>Yh),[l,u]=useState(null),d=useCallback(g=>{let w=(Array.isArray(g)?g:[g]).map(x=>s.add(x)),_=w.find(x=>!x.ok);return _!==void 0&&!_.ok&&u(_.error),w},[s,u]),c=useCallback(g=>s.retry(g),[s]),p=useCallback(g=>s.remove(g),[s]),f=useCallback(()=>s.clear(),[s]),m=useCallback(()=>u(null),[u]),y=a.attachments.some(g=>g.status==="uploading"),k=a.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:s.available,attachments:a.attachments,maxPerMessage:o,uploading:y,failed:k,blocked:y||k,s3Keys:a.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:l,add:d,retry:c,remove:p,clear:f,dismissRejected:m}),[s.available,a,o,y,k,l,d,c,p,f,m])}i(an,"useChatAttachments");var Zh="pet_not_registered";function xu(e){return e!=null&&e.reasonCode===Zh}i(xu,"isPetNotRegistered");var Jh=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function _u(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Y(),a=useCallback(()=>Qe(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:Qo(t),[t]),[u,d]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=useCallback(()=>{if(e===null||t===void 0||f===null)return;let k=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(g=>{k===c.current&&(g.ok?(d({key:f,status:"registered",error:null,registered:g.value}),p.current?.()):d({key:f,status:"failed",error:g.error,registered:null}));});},[a,e,f]);useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let y=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?Jh:u.key!==f?{status:"registering",error:null,registered:null,retry:y}:{status:u.status,error:u.error,registered:u.registered,retry:y},[f,u,y])}i(_u,"useChatPetRegistration");function Qo(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Qo).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${Qo(n)}`).join(",")}}`}i(Qo,"stableKey");var Zo=Object.freeze({});function Iu(e){let[t,r]=useState(Zo),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Zo?u:Zo);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[l.id]:a.images})));},[e]);let s=useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return useMemo(()=>({byMessage:t,stage:s}),[t,s])}i(Iu,"useSentImages");var ib=500;function Jo(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,ib):null}i(Jo,"sanitizeSeedPrompt");function Ou(e,t,r){let n=Jo(r),o=useRef(e);o.current=e;let s=useRef(null);useEffect(()=>{if(n===null||t||s.current===n)return;let a=o.current;a!==void 0&&(s.current=n,Promise.resolve(a(n)).catch(()=>{}));},[n,t]);}i(Ou,"useInitialAsk");function sb(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(sb,"isCoalesced");function Fu(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:sb(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Fu,"decideChatRefresh");function ei(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ei,"reportHostFailure");function ab(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(ab,"isThenable");function q(e,...t){if(typeof e=="function")try{let r=e(...t);return ab(r)&&Promise.resolve(r).then(void 0,ei),r}catch(r){ei(r);return}}i(q,"callHost");var Mu=new WeakMap;function Lu(e){if(typeof e!="function")return;let t=Mu.get(e);if(t!==void 0)return t;let r=i((...n)=>{q(e,...n);},"guarded");return Mu.set(e,r),r}i(Lu,"guardHost");function Dt(e,...t){let r;try{r=e(...t);}catch(n){return ei(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Dt,"callHostAsync");function Nu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:q(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=Fu(l,{activeConversationId:u,isTurnInFlight:d,isOffline:s,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},c!==void 0&&Promise.resolve(c()).catch(()=>{});}},useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),useEffect(()=>{if(e===void 0)return;let l=[],u=i((d,c)=>{if(d===void 0)return;let p=q(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)q(d);}},[e]);}i(Nu,"useChatLifecycle");function ub(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(ub,"targetKey");function Vu(e,t){let r=ub(t),n=useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=useRef(null);useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:s,target:a}=n.current;s===void 0||a===void 0||Promise.resolve(s(a)).catch(()=>{});},[r]);}i(Vu,"useCheckinTarget");function zu(e,t,r){let[n,o]=useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);useEffect(()=>{o(l=>{let u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let a=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(zu,"useChatDraft");function ju(e,t,r,n){let o=useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=useRef(null),[a,l]=useState(null);useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await Dt(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),useEffect(()=>{e===void 0||a!==`${t??""}`||q(()=>e.write(t,r));},[e,t,r,a]);}i(ju,"usePersistedDraft");var Z=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function un(e){let t=e?.replace(/\s+/g," ").trim();return t||Z.untitled}i(un,"conversationTitle");function Gu(e){return `${e.unreadCount!==null&&e.unreadCount>0?Z.unreadPrefix:""}${Z.openConversation} ${un(e.title)}`}i(Gu,"openConversationLabel");function Wu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Wu,"normalizeForSearch");function yb(e,t){let r=Wu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Wu(un(o.title)),a=s.indexOf(r);if(a<0)continue;let l=a===0?0:s.charAt(a-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(yb,"filterConversations");function ni(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(ni,"fresh");function Ku(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>ni(s)),d=l.scope===s?l:ni(s);useEffect(()=>(a.current+=1,r(false),o(""),u(ni(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async _=>{let x=++a.current,b=_!==void 0;u(L=>({...L,scope:s,loading:!b,loadingMore:b,error:null}));let P=await e.listConversations(_?{cursor:_}:void 0);if(x===a.current){if(!P.ok){u(L=>({...L,loading:false,loadingMore:false,error:P.error.displayMessage}));return}u(L=>{let I=_&&L.scope===s?L.rows:[],S=new Set(I.map(O=>O.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...I,...P.value.conversations.filter(O=>!S.has(O.id))],cursor:P.value.nextCursor===_?null:P.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async _=>{let x=++a.current;u(P=>({...P,loading:true,error:null}));let b=await e.resumeConversation(_);x===a.current&&(u(P=>({...P,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),y=i(async()=>{let _=a.current,x=await e.loadOlderMessages();_===a.current&&!x.ok&&u(b=>({...b,error:x.error.displayMessage}));},"earlier"),k=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),g=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),R=useMemo(()=>yb(d.rows,n),[d.rows,n]),w=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:k,loadMore:g,query:n,setQuery:o,searching:w,filtered:R,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Ku,"useHistoryPanel");var dn="#111111",cn="#FFFFFF",bb=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:dn,pillColor:cn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:dn,pillColor:cn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false})});function vb(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(vb,"urgencySignature");function Cb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Cb,"generalUrgencyReason");function Yu(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Cb(t)}:null}return null}i(Yu,"latestUrgencySource");function Xu(e){let t=e===null?null:vb(e),[r,n]=useState(null),[o,s]=useState(false);useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:bb[e.level],d=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=useCallback(()=>s(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Xu,"useUrgencySurface");function Qu(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Qu,"selectView");function Eb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Eb,"needsNewConversation");function Zu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Eb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(Zu,"turnNotice");function Ju(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Ju,"awaitingAssistant");function ed(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(ed,"buildChatOpts");var gr=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function nd(e){let t=F(),r=useMemo(()=>Tb(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${gr.title}. ${gr.body}`,children:[jsx(C,{style:r.title,children:gr.title}),jsx(C,{style:r.body,children:gr.body})]})}i(nd,"ClinicalDisclaimer");function Tb(e){let{color:t,space:r,type:n}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...E(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...E(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Tb,"makeStyles");var se={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function te(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(te,"box");function fe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(fe,"stroke");function od({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[te(e),{gap:e*.22}],...se,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(od,"MenuGlyph");function id({size:e,color:t,strokeWidth:r,rotate:n}){let o=fe(e,r),s=e*.78;return jsxs(View,{style:[te(e),{transform:[{rotate:n}]}],...se,children:[jsx(View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsx(View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(id,"Cross");function sd(e){return jsx(id,{...e,rotate:"0deg"})}i(sd,"PlusGlyph");function vt(e){return jsx(id,{...e,rotate:"45deg"})}i(vt,"CloseGlyph");function tt({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsx(View,{style:te(e),...se,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(tt,"CheckGlyph");var xb={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function pn({size:e,color:t,strokeWidth:r,direction:n}){let o=fe(e,r),s=e*.46,a=xb[n];return jsx(View,{style:te(e),...se,children:jsx(View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}i(pn,"ChevronGlyph");function ad({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxs(View,{style:[te(e),{flexDirection:"row",gap:1}],...se,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(ad,"BookGlyph");function ld({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.5;return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}i(ld,"ArrowUpRightGlyph");function ud({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(ud,"CopyGlyph");function fn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=fe(e,r),a=n?t:"transparent";return jsxs(View,{style:[te(e),{transform:[{rotate:o}]}],...se,children:[jsx(View,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),jsx(View,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),jsx(View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}i(fn,"ThumbGlyph");function dd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...se,children:[jsx(View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsx(View,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}i(dd,"InfoGlyph");function cd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.34;return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}i(cd,"UploadGlyph");function pd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...se,children:[jsx(View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(pd,"PhotoGlyph");function fd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),jsx(View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}i(fd,"CameraGlyph");function md({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.66;return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsx(View,{style:{position:"absolute",bottom:e*.02,right:e*.02,width:n,height:e*.4,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}})]})}i(md,"SearchGlyph");function yd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}i(yd,"EditGlyph");function gd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.62;return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsx(View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(gd,"MapPinGlyph");function hd({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:te(e),testID:r,...se,children:jsx(View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}i(hd,"SendGlyph");function bd({size:e,color:t,testID:r}){return jsx(View,{style:te(e),testID:r,...se,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(bd,"StopGlyph");function mn({size:e,strokeWidth:t,color:r,children:n}){return jsx(View,{style:[te(e),{borderRadius:e/2,borderWidth:t??StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(mn,"Ring");var hr=Object.freeze({standard:pt.standard,emphasized:pt.emphasized,exit:pt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var vd=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,reduced:false}),_b=Object.freeze({...vd,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,reduced:true});function Cd(e){return e.motion.reducedMotion?_b:vd}i(Cd,"chatMotion");function yn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(yn,"followUpDelayMs");function Ed(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(Ed,"nextRevealLength");function X(){let e=F();return Cd(e)}i(X,"useChatMotion");var Mb=8;function Sd(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Sd,"bezierComponent");function Lb(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Lb,"bezierSlope");function gn(e){let[t,r,n,o]=e;return s=>{if(s<=0)return 0;if(s>=1)return 1;let a=s;for(let l=0;l<Mb;l+=1){let u=Lb(a,t,n);if(u===0)break;a-=(Sd(a,t,n)-s)/u;}return Sd(Math.min(1,Math.max(0,a)),r,o)}}i(gn,"bezierEasing");var oi=gn(hr.standard),Db=gn(hr.outQuad);function li(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(li,"useAnimatedValue");function Ct(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=li(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:Db,useNativeDriver:true}),a=n>0?Animated.sequence([Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[o,r])}i(Ct,"useFadeIn");function ui({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=li(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:oi,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=Animated.timing(l,{toValue:0,duration:r,easing:oi,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsx(Animated.View,{style:[n,{opacity:l}],children:o})}i(ui,"FadePresence");var Nb=12;function B({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=X(),u=li(1),d=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(u,{toValue:c,duration:l.pressMs,easing:oi,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??Nb,style:t,onPressIn:c=>{d(l.pressScale),n?.(c);},onPressOut:c=>{d(1),o?.(c);},children:jsx(Animated.View,{style:[e,{transform:[{scale:u}]}],children:r})})}i(B,"PressScale");function kd(e,t,r){let n=t&&r.revealTickMs>0,[o,s]=useState(0),a=useRef(e);return a.current=e,useEffect(()=>{if(!n)return;let l=setInterval(()=>{s(u=>Ed(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(kd,"useRevealedText");var Td=false;function Ub(e){e.layoutMs<=0||(Td||(Td=true,Platform.OS==="android"&&typeof UIManager.setLayoutAnimationEnabledExperimental=="function"&&UIManager.setLayoutAnimationEnabledExperimental(true)),LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}));}i(Ub,"animateLayout");function br(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Ub(t));}i(br,"useAnimateLayoutOn");var di=36,Gb=22,Kb=12,qb=12,$b=16,Yb="#000",Xb="rgba(0,0,0,0.45)";function xd({uri:e,label:t,onClose:r}){let n=F(),o=useSafeAreaInsets();return e===null?null:jsxs(Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.closePreview,style:hn.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:hn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[hn.closeWrap,{top:o.top+qb}],children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:Kb,style:hn.closeButton,onPress:r,children:jsx(vt,{size:Gb,color:n.color.surface,strokeWidth:2})})})]})}i(xd,"AttachmentImageLightbox");var hn=StyleSheet.create({backdrop:{flex:1,backgroundColor:Yb,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:$b},closeButton:{width:di,height:di,borderRadius:di/2,backgroundColor:Xb,alignItems:"center",justifyContent:"center"}});var bn=12,tv=80,ci=44,_d=22,rv=.14,nv=18,ov=8,wd=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Id({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>iv(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(B,{accessibilityRole:"button",accessibilityLabel:wd[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsx(View,{style:s.tileIconWrap,children:a==="photo"?jsx(pd,{size:_d,color:o.color.brandInk,strokeWidth:1.5}):jsx(fd,{size:_d,color:o.color.brandInk,strokeWidth:1.5})}),jsx(C,{tier:"control",style:s.tileLabel,children:wd[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Id,"AttachmentPickerPopover");function iv(e){let t=e.color,r=e.radius;return StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:rv,shadowRadius:nv,shadowOffset:{width:0,height:ov},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:tv,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:ci,height:ci,borderRadius:ci/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...E(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-bn/2,width:bn,height:bn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:bn+4,height:2,backgroundColor:t.surfaceCream}})}i(iv,"makeStyles");var Ad=56,Od=12,lv=14,uv=10,dv=.45,cv="rgba(7,193,104,0.55)",pv="rgba(185,28,28,0.55)",fv=200,mv=300,Hd=20,fi=22,yv=12,gv="rgba(0,0,0,0.78)",Fd=220,Md=100,Ld="rgba(255,255,255,0.15)";function Bd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=useMemo(()=>jd(a),[a]);return e.length===0&&t===null?null:jsxs(View,{style:l.strip,children:[e.length>0?jsx(View,{style:l.cards,children:e.map(u=>jsx(hv,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:Su(t)}):null]})}i(Bd,"AttachmentStrip");function hv({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=F(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=useRef(e.status),[c,p]=useState(false);return useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxs(View,{style:t.card,children:[jsx(Pressable,{accessibilityRole:u?"button":"image",accessibilityLabel:u?K(h.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!u},disabled:!u,style:t.thumbHit,onPress:()=>o(e),children:jsxs(View,{style:t.thumb,children:[jsx(Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsx(View,{style:t.uploadingOverlay,children:jsx(ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsx(bv,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(vt,{size:Hd,color:s.color.surface,strokeWidth:2})})}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:K(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(vt,{size:yv,color:s.color.surface,strokeWidth:1.5})})]})}i(hv,"PreviewCard");function bv({styles:e,onDone:t}){let r=F(),n=X(),o=useRef(null);o.current===null&&(o.current=new Animated.Value(0));let s=o.current;return useEffect(()=>{let a=Animated.sequence([Animated.timing(s,{toValue:1,duration:fv,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:mv,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsx(Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsx(tt,{size:Hd,color:r.color.surface,strokeWidth:2})})}i(bv,"SuccessFlash");function zd({images:e,onPreview:t}){let r=F(),n=useMemo(()=>jd(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsx(View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsx(Image,{source:{uri:s.uri},style:o?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${s.uri}-${a}`))})}i(zd,"SentImages");function jd(e){let t=e.color,r=e.type;return StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Ad,height:Ad,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Od,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:tl(e.color.brandInk,dv)??e.color.brandSofter},successOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:cv},failedOverlay:{...StyleSheet.absoluteFillObject,borderRadius:Od,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:pv},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:fi,height:fi,borderRadius:fi/2,backgroundColor:gv,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Fd,height:Fd,borderRadius:lv,backgroundColor:Ld},gridImage:{width:Md,height:Md,borderRadius:uv,backgroundColor:Ld}})}i(jd,"makeStyles");var vv="file",Cv="chat attachment upload: the file handle has no uri",Ev="chat attachment upload failed";function Rv(e){return {uri:e.uri,name:po(e.name),type:e.mimeType}}i(Rv,"filePartOf");function Wd(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Cv));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Ev)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(vv,Rv(r));let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(Wd,"createRnChatAttachmentTransport");function vn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Y(),o=useMemo(()=>Qe(e.registry.services.authFor(t)),[e,t,n]),[s,a]=useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},u=useRef(0),d=useCallback(async()=>{let p=++u.current;a(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&a(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:d}),[l.pets,l.loading,l.error,c,d])}i(vn,"useEverfurPets");function Gd(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Gd,"headerPetOf");function me(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(me,"slotBox");function hi(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(hi,"ownGroundSlot");function we(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(we,"slotText");var Kd=Object.freeze({visitButton:"Talk to a vet"});var qd=Symbol.for("@everfur/sdk/televet");function Ge(){let e=globalThis,t=e[qd];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[qd]=r,r}i(Ge,"televetGlobal");function Cn(e){let t=Ge();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Cn,"publish");function $d(e){let t=Ge().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i($d,"callTelevetPresenter");function Yd(e){let t=Ge();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Yd,"subscribeTelevetExperience");function bi(){return Ge().snapshot}i(bi,"televetExperienceSnapshot");function xv(){return Ge().hosts.length>0}i(xv,"hasTelevetHost");function Xd(e){if(!xv())return false;let t=Object.freeze({...e});return Cn({request:t,serial:Ge().snapshot.serial+1}),true}i(Xd,"presentTelevetExperience");function vi(){Ge().snapshot.request!==null&&Cn({request:null});}i(vi,"dismissTelevetExperience");function Qd(){let e=Ge(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Cn({activeHost:e.hosts[0]??null}),t}i(Qd,"claimTelevetHost");function Zd(e){let t=Ge();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Cn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(Zd,"releaseTelevetHost");var Jd=false;function En(e,t){return t!==void 0?(q(t,e),"onStartInApp"):$d(e)==="presented"?"presenter":Xd(e)?"experience":(Jd||(Jd=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(En,"openVetVisitInApp");function rc(e){let t=null;return ()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null);}),r}}i(rc,"memoizeTelevetLoader");function nc(e){let[t,r]=useState(null);useEffect(()=>{let d=Qd();return r(d),()=>{Zd(d);}},[]);let n=useSyncExternalStore(Yd,bi,bi),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=useState(null),u=s!==null&&a===null;return useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),vi());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:vi}}i(nc,"useTelevetExperienceHost");var wv=rc(()=>import('@everfur/sdk/televet/booking'));function Er(){let e=nc(wv);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(Er,"EverfurTelevetHost");var Ci=Object.freeze(["visit","join","summary","messages"]);function Ei(e){return typeof e=="string"&&Ci.includes(e)}i(Ei,"isVetVisitIntent");var Av="/widget/v1/televet/handoffs",Ov="/widget/v1/televet/availability",Fv="/widget/v1/televet/chat-entry",Mv=/^[a-z0-9][a-z0-9_-]{0,39}$/,Lv=/^[A-Za-z0-9_-]{22}$/;var oc=32,ic=128,sc=64;function Si(e){let t=e.httpStatus;switch(e.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 t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(Si,"vetVisitErrorReasonOf");function ac(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(ac,"invalid");function Ri(e){return v(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Ri,"unusable");function Dv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Mv.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let s=t?.visitRef,a=t?.intent,l=s!=null;if(l){let u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>sc)return {ok:false,message:`visitRef must be 1..${sc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Ei(a))return {ok:false,message:`intent must be one of ${Ci.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(Dv,"handoffBody");function Nv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Ei(r)?null:Object.freeze({visitRef:t,intent:r})}i(Nv,"parseVisitEcho");function uc(e){let t=e.funnel??ke({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(lc(r,"televet.visit.handoff_failed",{reason:Si(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let g=typeof o=="string"?[...o].length:0;if(g<1||g>ic)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${ic} characters`}));a=o;}let l=Dv(a,s);if(!l.ok){let g=ac(l.message);return g.ok?g:n(g.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:Av,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Uv(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!Lv.test(f))){let g=Ri("the handoff response carried no usable return flow id");return g.ok?g:n(g.error)}let m=u.visit_ref!==void 0,y=m?Nv(d.value?.visit):null;if(m&&y===null){let g=Ri("the handoff response did not confirm the visit it opens");return g.ok?g:n(g.error)}let k=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return k===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(lc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(k))},async checkAvailability(o){if(typeof o!="string"||o.length>oc)return ac(`state must be at most ${oc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Ov,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?Ri("the availability response carried no usable answer"):M(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Fv},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(uc,"createVetVisitController");function Uv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!zv(t)?null:Object.freeze({url:t,expiresAt:r})}i(Uv,"parseHandoff");var Vv=new Set(["localhost","127.0.0.1","[::1]"]),Hv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Bv=/[\s\u0000-\u001f\u007f]/;function zv(e){if(Bv.test(e))return false;let t=Hv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),s=r==="https",a=r==="http"&&Vv.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(zv,"isOpenableVisitUrl");function lc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(lc,"safeTrack");var Ti=Object.freeze({status:"idle",error:null,errorReason:null});function Wv(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=useState(null);if(useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let y=await f.checkAvailability(n);return y.ok&&y.value.available}catch{return false}},"ask")().then(y=>{p&&d({key:l,open:y});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(Wv,"usePreflight");var Gv=Object.freeze({status:"opening",error:null,errorReason:null});function pc(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Y(),s=Mt("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:T}=r.registry;return uc({auth:T.authFor(n),telemetry:T.telemetry,...T.errorPolicy?{errorPolicy:T.errorPolicy}:{}})},[r,n,o,t.controller]),f=useRef(p);f.current=p;let m=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),y=Wv(f,a,{usState:l,chat:u,scope:m}),k=a&&(y===null||y.open)&&(!u||d!==null),g=t.returnTo??null,[R,w]=useState(Ti),_=useRef(null),x=useRef({runtime:r,userRef:n,scopeEpoch:o});x.current={runtime:r,userRef:n,scopeEpoch:o};let b=useRef(p);b.current=p;let P=useRef(k);P.current=k;let L=useCallback((T,V)=>{if(_.current)return _.current;let j=i((ce,ot)=>(w({status:ce==="cancelled"?"idle":"error",error:ot,errorReason:ce==="cancelled"?null:ce}),Object.freeze({opened:false,reason:ce,error:ot})),"fail");if(!P.current)return Promise.resolve(j("unavailable",null));let G=e.prepare();if(!G.ok)return Promise.resolve(j(G.reason,null));let ne=x.current,de=b.current;w(Gv);let Gt=(async()=>{let ce,ot={...g!==null?{returnTo:g}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},wr=Object.keys(ot).length===0?void 0:ot,Kt=T===void 0?d:T;try{ce=await(wr===void 0?de.createHandoff(Kt):de.createHandoff(Kt,wr));}catch{return e.abandon(G.value),j("unknown",null)}let xt=x.current;if(xt.runtime!==ne.runtime||xt.userRef!==ne.userRef||xt.scopeEpoch!==ne.scopeEpoch)return e.abandon(G.value),j("cancelled",null);if(!ce.ok)return e.abandon(G.value),j(Si(ce.error),ce.error);let _t=await e.finish(G.value,ce.value);return _t!==null?j(_t,null):(w(Ti),Object.freeze(ce.value.flowId===void 0?{opened:true}:{opened:true,flowId:ce.value.flowId}))})().finally(()=>{_.current===Gt&&(_.current=null);});return _.current=Gt,Gt},[e,d,g,u]),I=useCallback((T,V)=>{if(!P.current)return w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let j=T===void 0?d:T,G={...j!==null?{petRef:j}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return En(G)===null?(w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(w(Ti),Promise.resolve(Object.freeze({opened:true})))},[d,l]),S=useCallback(T=>c?L(T,null):I(T,null),[c,L,I]),O=useCallback((T,V)=>c?L(void 0,{visitRef:T,intent:V??null}):I(void 0,{visitRef:T,intent:V??null}),[c,L,I]);return {available:k,isPending:s.isPending||(y?.pending??false),status:R.status,error:R.error,errorReason:R.errorReason,open:S,openVisit:O}}i(pc,"useVetVisitWith");var $v=i(e=>Linking.openURL(e),"defaultOpenUrl");function Sn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??$v;return {prepare:i(()=>({ok:true,value:null}),"prepare"),async finish(s,a){try{return await o(a.url),null}catch{return "openFailed"}},abandon:i(()=>{},"abandon")}},[t]);return pc(n,r)}i(Sn,"useVetVisit");var fc=44,Jv=.6;function Vt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:m,onStartInApp:y,prefer:k}=e,g=k==="redirect",R=Sn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:g?"redirect":"in-app"}),w=F(),_=useMemo(()=>eC(w),[w]),x=useRef(false);if(!R.available)return jsxs(Fragment,{children:[null,jsx(Er,{})]});let b=R.status==="opening",P=r??Kd.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(b||x.current)){if(!g){let I={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};En(I,y)===null&&q(s,"unavailable",null);return}x.current=true,(f==null?R.open():R.openVisit(f,m??null)).then(I=>{I.opened?q(o,I.flowId??null):I.reason!=="cancelled"&&q(s,I.reason,I.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:P,accessibilityState:{busy:b,disabled:b},style:[_.button,b?_.busy:null,a],children:jsx(C,{style:[_.label,l],children:P})}),jsx(Er,{})]})}i(Vt,"VetVisitButton");function eC(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:fc,minWidth:fc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...me(s.vetVisitButton)},busy:{opacity:Jv},label:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...we(s.vetVisitButton)}})}i(eC,"makeStyles");function Pi(e){return sr(e)==="cat"?"cat":"dog"}i(Pi,"speciesOf");function ki(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(ki,"petAgeYears");function hc(e){let t=ki(e.ageYears),r=Pi(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(hc,"formatPetMeta");var gc=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function tC(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return gc[t%gc.length]}i(tC,"pickInitialsPalette");function xi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(xi,"getInitial");function bc(e){return {...tC(e.petRef),initial:xi(e.name)}}i(bc,"petInitials");function iC(e){return Math.max(12,Math.round(e*.42))}i(iC,"letterSize");function Sr({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>sC(n),[n]),s=t-r*2,a=e===null?null:bc(e),l=iC(s);return jsx(mn,{size:t,strokeWidth:r,color:n.color.success,children:jsx(View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsx(C,{tier:"badge",style:[o.letter,{fontSize:l,lineHeight:Math.round(l*1.2),color:a===null?n.color.text.muted:a.foreground}],children:a===null?xi(null):a.initial})})})}i(Sr,"PetDisc");function sC(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...E(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(sC,"makeStyles");var wi=48,Rc=2,cC=320,pC="80%",fC="rgba(17,17,17,0.45)",mC=18,vc=22,yC=12,Cc=.4,gC=44;function Ii(e){return e?.name?.trim()||h.yourPet}i(Ii,"petDisplayName");function Sc({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>hC(a),[a]);return e?jsx(Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxs(View,{style:l.root,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=Ii(u),p=hc(u);return jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(Sr,{pet:u,size:wi,ringStroke:Rc}),jsxs(View,{style:l.copy,children:[jsx(C,{style:l.name,numberOfLines:1,children:c}),jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsx(tt,{size:mC,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(C,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(Sc,"PetSwitcherSheet");function hC(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:fC},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:vc,borderTopRightRadius:vc,gap:14,maxHeight:pC},title:{...E(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:cC,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:gC,paddingHorizontal:8},addDisc:{width:wi,height:wi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Rc,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...E(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...E(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...E(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...E(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Cc},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:yC,backgroundColor:t.brandSoft},closeText:{...E(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Cc}})}i(hC,"makeStyles");var CC=44,Pn=36,EC=22,Oi=9,RC=1.5,Tc=6,Rt=35,kn=1.75,Fi=12.4,SC=.5,TC=8,PC=28,kC=160;function Li(e,t){return Gd(e,t)}i(Li,"headerPet");function kc({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=useMemo(()=>_C(l),[l]),[d,c]=useState(false),p=Li(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,y=Ii(p),k=i(R=>{c(false),e.setActivePet(R),q(o,R);},"select"),g=s===void 0?null:()=>{c(false),q(s);};return jsxs(View,{style:u.row,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsx(od,{size:EC,color:l.color.text.primary,strokeWidth:2}),r?jsx(View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsx(View,{style:u.center,pointerEvents:"box-none",children:jsx(xC,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(Vt,{entry:"chat",petRef:m,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsx(View,{style:u.right,children:f?jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(h.switchActivePet,{name:y}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(Sr,{pet:p,size:Rt,ringStroke:kn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(sd,{size:TC,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(mn,{size:Rt,strokeWidth:kn,color:l.color.success,children:jsx(View,{style:u.placeholderDisc})})}):jsx(View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:y,children:jsx(Sr,{pet:p,size:Rt,ringStroke:kn})})}),jsx(Sc,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:k,onAddPet:g,onClose:()=>c(false)})]})}i(kc,"ChatHeader");function xC({logoUrl:e,name:t,styles:r}){let[n,o]=useState(null);return e===null||n===e?null:jsx(View,{style:r.logoBar,children:jsx(Image,{source:{uri:e},style:r.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:()=>o(e)})})}i(xC,"BrandLogo");function _C(e){let t=e.color,r=Rt-kn*2;return StyleSheet.create({vetEntry:{minHeight:CC,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...E(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:t.surface},iconSlot:{borderRadius:Pn/2},iconButton:{width:Pn,height:Pn,borderRadius:Pn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Tc,right:Tc,width:Oi,height:Oi,borderRadius:Oi,backgroundColor:t.danger,borderWidth:RC,borderColor:t.surface},center:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:PC,width:kC},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Rt/2},avatarWrap:{width:Rt,height:Rt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Fi,height:Fi,borderRadius:Fi/2,borderWidth:SC,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(_C,"makeStyles");var _c=44,FC="rgba(17,17,17,0.55)",wc=26,MC=36,Ic=4,Ni=20,Ui=38,LC=18,DC=12;function Ac({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>NC(n),[n]),[s,a]=useState(null),[l,u]=useState(""),[d,c]=useState(false),[p,f]=useState(false),m=i(()=>{a(null),u(""),c(false),f(false);},"reset"),y=i(()=>{d||(m(),r());},"skip"),k=i(async()=>{if(d)return;c(true),f(false);let R=l.trim();await t(s,R.length>0?R:null)?m():(c(false),f(true));},"submit");if(!e)return null;let g=[...l].length>At;return jsx(Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsx(Pressable,{style:o.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y}),jsxs(View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsx(View,{style:o.handle}),jsxs(View,{style:o.header,children:[jsx(View,{style:o.iconBadge,children:jsx(fn,{size:LC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:Ko.map(R=>{let w=s===R.key;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:R.label,accessibilityState:{selected:w},style:[o.option,w?o.optionSelected:null],onPress:()=>a(_=>_===R.key?null:R.key),children:[jsx(C,{style:[o.optionLabel,w?o.optionLabelSelected:null],children:R.label}),jsx(View,{style:[o.radio,w?o.radioSelected:null],children:w?jsx(tt,{size:DC,color:n.color.surface,strokeWidth:2}):null})]},R.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(Lt,{style:o.input,placeholder:h.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:h.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsx(C,{tier:"compact",style:[o.counter,g?o.counterOver:null],children:`${[...l].length}/${At}`}):null]}),p?jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(B,{accessibilityRole:"button",accessibilityLabel:h.feedbackSubmit,accessibilityState:{busy:d,disabled:d||g},disabled:d||g,style:[o.submit,d||g?o.submitDisabled:null],onPress:()=>{k();},children:jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:y,style:o.skip,children:jsx(C,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(Ac,"FeedbackReasons");function NC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...StyleSheet.absoluteFillObject,backgroundColor:FC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:wc,borderTopRightRadius:wc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:MC,height:Ic,borderRadius:Ic/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Ui,height:Ui,borderRadius:Ui/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...E(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...E(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,backgroundColor:t.surface},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:Ni,height:Ni,borderRadius:Ni/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...E(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...E(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...me(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...we(o.primaryButton)},skip:{minHeight:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(NC,"makeStyles");var QC=.88,ZC=420,JC=58,eE="rgba(17,17,17,0.28)",tE=.08,rE=.1,nE=.08,oE=.18,iE=.78,sE=.7,Vi=36,aE=10,lE=14,uE=12,dE=16,cE=14,Hi=8,pE=1.5,fE=.5,mE=gn(hr.standard);function yE(e){return Math.min(Math.round(e*QC),ZC)}i(yE,"drawerPanelWidth");function Fc({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(gE,{chat:e,history:t,onHidden:o}):null}i(Fc,"HistoryDrawer");function gE({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>bE(n),[n]),s=X(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=yE(l),d=t.open,c=useRef(null);c.current===null&&(c.current=new Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let R=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:mE,useNativeDriver:true});return R.start(({finished:w})=>{w&&!d&&r();}),()=>R.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,y=t.rows.length===0,k=y&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:Z.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(C,{style:o.emptyBody,children:Z.loading})]}):y&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:Z.loadFailed}),jsx(C,{style:o.emptyBody,children:t.error}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(C,{tier:"control",style:o.retryText,children:Z.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?Z.empty:Z.noMatch}),jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?Z.emptyBody:Z.noMatchBody})]}),g=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(C,{style:o.loadMoreLabel,children:Z.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Z.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(JC,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxs(KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[jsxs(View,{style:o.searchRow,children:[jsxs(View,{style:o.searchPill,children:[jsx(md,{size:cE,color:n.color.text.muted,strokeWidth:1.5}),jsx(Lt,{value:t.query,onChangeText:R=>t.setQuery(R.replace(/^\s+/,"")),style:o.searchInput,placeholder:Z.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Z.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(yd,{size:dE,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:Z.heading}),t.error!==null&&!y?jsx(View,{style:o.errorCard,children:jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:m,keyExtractor:R=>R.id,renderItem:({item:R})=>jsx(hE,{row:R,active:R.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(R.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:g,onEndReached:t.loadMore,onEndReachedThreshold:fE})]})})]})})}i(gE,"DrawerModal");function hE({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(B,{accessibilityRole:"button",accessibilityLabel:Gu(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:jsxs(View,{style:n.itemRow,children:[jsx(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:un(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(hE,"Row");function wn(e,t){if(!/^#[0-9a-f]{6}$/i.test(e))return "transparent";let r=Math.round(Math.min(1,Math.max(0,t))*255);return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}i(wn,"inkWash");function bE(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:eE},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.brand,paddingHorizontal:16,borderRightWidth:.5,borderRightColor:t.brandBorder,gap:12},keyboardAvoider:{flex:1,gap:12},searchRow:{flexDirection:"row",alignItems:"center",gap:10},searchPill:{flex:1,flexDirection:"row",alignItems:"center",gap:8,borderRadius:e.radius.pill,backgroundColor:t.surface,paddingHorizontal:14,paddingVertical:10,borderWidth:1,borderColor:wn(n,rE)},searchInput:{...E(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:Vi,height:Vi,borderRadius:Vi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...E(e,"bold"),fontSize:14,lineHeight:17,color:n,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:aE},itemActive:{backgroundColor:wn(n,tE)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...E(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:n},itemTitleUnread:E(e,"bold"),unreadDot:{width:Hi,height:Hi,borderRadius:Hi/2,backgroundColor:t.danger,borderWidth:pE,borderColor:n},errorCard:{borderRadius:uE,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...E(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:lE,padding:14,gap:6,backgroundColor:wn(n,nE),borderWidth:.5,borderColor:wn(n,oE)},emptyTitle:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...E(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:iE},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...me(r.primaryButton)},retryText:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n,...we(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...E(e,"regular"),fontSize:11,lineHeight:14,color:n,opacity:sE}})}i(bE,"makeStyles");function Mc(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}i(Mc,"chatVetVisitOptions");var RE=16,SE=.75,Bi=12,Lc=15,TE=18,In=22,PE=14,kE=8,xE=20,_E=10,wE=13;function Nc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>IE(s),[s]),l=X(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(ui,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxs(View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(bt,{render:()=>r(u.level),fallback:jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(B,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:kE,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(vt,{size:PE,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(ui,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:_E,onPress:e.expand,children:jsx(dd,{size:xE,color:s.color.text.muted,strokeWidth:2})})})]})}i(Nc,"UrgencyBanner");function Dc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=Sn(Mc(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{q(r,e.level);}:null;if(u===null)return null;let d=hi(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.findVetA11y,accessibilityState:{busy:l},containerStyle:o.findVetSlot,style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,l?o.findVetBusy:null],onPress:u,children:[jsx(gd,{size:wE,color:d,strokeWidth:1.5}),jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(Dc,"VetAction");function IE(e){let t=hi(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:RE,borderWidth:SE,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...E(e,"monoBold"),fontSize:Bi,lineHeight:Lc},reason:{...E(e,"regular"),fontSize:Bi,lineHeight:TE,paddingRight:In},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...me(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...E(e,"monoBold"),fontSize:Bi,lineHeight:Lc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:In,height:In,borderRadius:In/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(IE,"makeStyles");function Uc(){let e=vn(),{handle:t}=Y(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(Uc,"useChatPets");var Kc=300,qc=3e3,Hc=120,Bt=44,LE=120,DE="86%",Bc=15,zc=22,An=.5,NE=.04,UE=8,VE=2,HE=1,BE=.6,zE=22,jE=48,jc=1.25,WE=14,GE=18,KE=6,qE=14,$E=.04,YE=12,XE=2,QE=2,Wc=36,ZE=20,Ht=36,zt=(Bt-Ht)/2,$c=24,Yc=22,JE=.4,On=30,Xc=20,eR=.4,tR=480,rR=8,Gc=14,nR=10,oR=14,iR=12,sR=13,aR=18,lR="12%";function Ce(){let e=F(),t=useMemo(()=>uR(e),[e]);return {theme:e,styles:t}}i(Ce,"useChatTheme");function uR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:Hc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Hc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:lR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:tR,gap:18},errorText:{...E(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Bt,minWidth:Bt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...me(s.primaryButton)},retryLabel:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...we(s.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.lg,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Bt,justifyContent:"center"},turnNoticeActionLabel:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...E(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},list:{flex:1},listContent:{padding:r.lg,gap:r.md},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:DE},bubbleUser:{padding:Bc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:An,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:NE,shadowRadius:UE,shadowOffset:{width:0,height:VE},elevation:HE,...me(s.userBubble,An)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...me(s.assistantBubble,An)}:{padding:Bc,borderRadius:n.xl,...me(s.assistantBubble,An)},bubblePending:{opacity:BE},bubbleTextUser:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:zc,...we(s.userBubble)},bubbleTextAssistant:{...E(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:zc,...we(s.assistantBubble)},bubbleBold:E(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:E(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:rR},followUpSlot:{alignSelf:"stretch",borderRadius:Gc},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:iR,paddingVertical:nR,paddingHorizontal:oR,borderRadius:Gc,backgroundColor:t.brandSoft},followUpText:{...E(e,"medium"),flex:1,color:t.text.primary,fontSize:sR,lineHeight:aR},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:jE,justifyContent:"center",paddingLeft:WE,paddingRight:GE,paddingVertical:KE,backgroundColor:t.composerFill,borderWidth:jc,borderColor:t.composerBorder,borderRadius:zE,shadowColor:t.shadow,shadowOpacity:$E,shadowRadius:YE,shadowOffset:{width:0,height:XE},elevation:QE,...me(s.composerInput,jc)},composerRow:{flexDirection:"row",alignItems:"center",gap:qE,minHeight:Wc},attachControl:{width:On,height:On,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:eR},input:{flex:1,minHeight:Wc,maxHeight:LE,paddingHorizontal:0,paddingVertical:0,...E(e,"regular"),fontSize:o.size.body,lineHeight:ZE,color:t.text.primary,...we(s.composerInput)},sendControl:{minHeight:Ht,minWidth:Ht,alignItems:"center",justifyContent:"center"},sendDisc:{width:Ht,height:Ht,borderRadius:Ht/2,alignItems:"center",justifyContent:"center",...me(s.sendButton)},sendControlDisabled:{opacity:JE},poweredBy:{...E(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(uR,"makeStyles");var dR=Object.freeze({kind:"live"}),cR=Object.freeze({kind:"folded"});function ji(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=no(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(ji,"askOf");function Zc(e){let t=new Map,r=new Map;for(let o of e){let s=ji(o);if(s===null)continue;let a=r.get(s.caseId);(a===void 0||s.dueDay>=a.dueDay)&&r.set(s.caseId,{messageId:o.id,dueDay:s.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let s=ji(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,dR),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,cR);continue}let a=[s.dueDay];n={id:o.id,caseId:s.caseId,days:a},t.set(o.id,{kind:"past",runDueDays:a});}return t}i(Zc,"placeCheckins");var Qc=864e5,pR=365;function Fn(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let o=Math.floor(n/Qc)-Math.floor(r/Qc);return o<1||o>pR?null:o}i(Fn,"checkinDayNumber");function Jc(e){return ji(e)?.dueDay||null}i(Jc,"checkinDueDay");var Se=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),ep=Object.freeze(Vr.map(e=>Object.freeze({answer:e,label:Se.answers[e]})));function tp(e,t){let[r,n]=useState(null),[o,s]=useState(null),[a,l]=useState(null),u=useCallback(c=>{t!==null&&(n(c),s(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):s(p.error);}));},[t,e.caseId]),d=a??e.answer;return {answer:d,answerable:!ua(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(tp,"useCheckinCard");var op=44,yR=.6;function sp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s}){let a=F(),l=useMemo(()=>gR(a),[a]),u=tp(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable,p=Fn(t.openedAt,Jc(e));return jsxs(View,{style:l.card,accessibilityLabel:Se.eyebrow,children:[jsxs(View,{style:l.head,children:[jsx(C,{tier:"compact",style:l.eyebrow,children:Se.eyebrow}),p!==null?jsx(C,{tier:"compact",style:l.headDay,children:K(Se.day,{day:p})}):null]}),jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsx(View,{style:[l.row,u.pending?l.rowPending:null],children:ep.map(({answer:f,label:m})=>{let y=(u.pending??u.answer)===f;return jsx(Pressable,{onPress:()=>u.choose(f),disabled:d,accessibilityRole:"button",accessibilityLabel:m,accessibilityState:{selected:y,disabled:d,busy:u.pending===f},style:[l.pill,y?l.pillSelected:null],children:jsx(C,{tier:"control",style:[l.pillLabel,y?l.pillLabelSelected:null],children:m})},f)})}):null,u.answer!==null?jsx(C,{style:l.logged,children:Se.logged}):null,u.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Se.findVet,style:l.findVet,children:jsx(C,{tier:"control",style:l.findVetLabel,children:Se.findVet})}):n?jsx(Vt,{entry:"chat",petRef:n,label:Se.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:l.findVet,labelStyle:l.findVetLabel}):null:null,t.resolutionText?jsx(C,{style:l.resolution,children:t.resolutionText}):null,u.error?jsx(C,{style:l.error,accessibilityRole:"alert",children:u.error.displayMessage}):null]})}i(sp,"CheckinCard");function gR(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:yR},pill:{flex:1,minHeight:op,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brand},pillLabel:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:op,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...E(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(gR,"makeStyles");var vR=1.5,CR=3;function lp({text:e,runDueDays:t,openedAt:r}){let n=F(),o=useMemo(()=>ER(n),[n]),s=t.map(l=>Fn(r,l)).filter(l=>l!==null),a=t.length>1;return a&&s.length===0?null:jsxs(View,{style:o.row,children:[jsx(View,{style:o.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),jsxs(View,{style:o.body,children:[s.length>0?jsx(C,{tier:"compact",style:o.days,children:s.map(l=>K(Se.day,{day:l})).join(Se.daySeparator)}):null,a?null:jsx(C,{style:o.question,accessibilityRole:"text",children:e})]})]})}i(lp,"CheckinPastAsk");function ER(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:vR,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:CR},days:{...E(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...E(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(ER,"makeStyles");var RR=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),up="#C8BEB4";function SR(e){return e?RR[e.toUpperCase()]??up:up}i(SR,"tierColor");function TR(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(TR,"tierLabel");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ve,"text");function PR(e){let t=Ve(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(PR,"httpsUrl");function kR(e,t){let r=Ve(e.source_name)??Ve(e.sourceName),n=Ve(e.section),o=Ve(e.authority_tier)??Ve(e.authorityTier),s=TR(o),a=r??Ve(e.title)??`Source ${t+1}`,l=Ve(e.monograph_chunk_id)??Ve(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:PR(e.url),excerpt:Ve(e.excerpt),tierColor:SR(o),key:`${a}-${l??"none"}-${t}`})}i(kR,"toCitationCard");function dp(e){return e===void 0||e.length===0?xR:Object.freeze(e.map((t,r)=>kR(t,r)))}i(dp,"toCitationCards");var xR=Object.freeze([]);function $i(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i($i,"sourcesLabel");function cp(e,t){return `${t?h.hideSources:h.showSources} ${$i(e)}`}i(cp,"sourcesToggleLabel");function pp(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(pp,"citationA11yLabel");var OR=244,mp=8,yp=13,FR=14,MR=.3,LR=-0.24,DR=22,NR=10,UR=15;function gp({citations:e,onOpenUrl:t}){let r=F(),n=useMemo(()=>BR(r),[r]),o=useMemo(()=>dp(e),[e]),[s,a]=useState(false);if(o.length===0)return null;let l=o.length;return jsxs(View,{style:n.block,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:cp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsx(ad,{size:yp,color:r.color.brandInk,strokeWidth:1.5}),jsx(C,{tier:"compact",style:n.toggleLabel,children:$i(l)}),jsx(pn,{size:yp,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(VR,{cards:o,styles:n,open:t}):null]})}i(gp,"CitationCards");function VR({cards:e,styles:t,open:r}){let n=X(),o=Ct(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(HR,{card:s,styles:t,open:r},s.key))})})}i(VR,"Deck");function HR({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=pp(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(ld,{size:FR,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsx(B,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>r(l),children:a})}return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}i(HR,"Card");function BR(e){let t=e.color,r=e.space,n=e.radius,o=e.type.size;return StyleSheet.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...E(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:MR,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:OR,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:mp,height:mp,borderRadius:n.pill},cardTitle:{...E(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:DR,color:t.text.primary,letterSpacing:LR},cardTitleLink:{color:t.linkInk},cardMeta:{...E(e,"monoMedium"),fontSize:o.nano,lineHeight:NR,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...E(e,"regular"),fontSize:o.tiny,lineHeight:UR,color:t.text.muted}})}i(BR,"makeStyles");function hp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(hp,"formatMessageTime");var kr=15,qR=15,$R=6,YR=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function Rp({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>XR(s),[s]),l=X(),u=e.role==="user",d=useMemo(()=>hp(e.createdAt),[e.createdAt]),c=t!==void 0&&e.text.length>0,p=!u&&n!==void 0&&e.responseId!==void 0,[f,m]=useState(false),y=useRef(null);useEffect(()=>()=>{y.current&&clearTimeout(y.current);},[]);let k=i(()=>{t!==void 0&&(Dt(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxs(View,{style:a.wrap,children:[jsxs(View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:qR,onPress:k,style:a.iconHit,children:f?jsx(tt,{size:kr,color:s.color.success,strokeWidth:2}):jsx(ud,{size:kr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?vu.map(({sentiment:g,label:R})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{selected:r===g},hitSlop:$R,onPress:()=>n?.(g),style:a.iconHit,children:jsx(fn,{size:kr,color:s.color.sentiment[g],active:r===g,rotate:YR[g],strokeWidth:1.5})},g)):null]}),o?jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(Rp,"MessageFooter");function XR(e){let t=e.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...E(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:kr,height:kr,alignItems:"center",justifyContent:"center"},thanks:{...E(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(XR,"makeStyles");var Sp="#10462E",Tp="#000000",QR="#83E0B4",ZR=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:QR,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:Sp,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit.",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),JR=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function eS(e){return e==null?e:e.replace(JR,"").trim()}i(eS,"formatBreedForPrompt");var tS=new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function rS(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return tS.has(t)}i(rS,"isUninformativeBreed");function nS(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(nS,"unspecifiedBreedLabel");function oS(e,t){return rS(e)?nS(t):String(e).replace(/\s+/gu," ").trim()}i(oS,"resolveBreedLabel");function Pp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(Pp,"emptyStateTitle");function kp(e,t=Sp){let r=Pi(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=oS(eS(e?.breed),r)||null,l=ki(e?.ageYears),u=l===null?null:String(l);return Object.freeze(ZR.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),m=d.fallbackLabel!==void 0&&(c&&!a||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,y=K(m,{petName:s,breed:a??n,species:r,ageYears:u??""}),k=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:k,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(kp,"resolveQuickPrompts");var sS=36,wp=4,aS=340;function Ip({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>uS(s),[s]),l=useMemo(()=>kp(e,s.color.brandInk),[e,s.color.brandInk]),u=Pp(e);return jsxs(View,{style:a.block,children:[jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(lS,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Ip,"QuickPrompts");function lS({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=X(),d=Ct(u.followUpInMs,{delayMs:yn(u,t)}),c={backgroundColor:e.background,borderColor:e.borderColor,borderWidth:e.borderWidth};return e.intent==="vet_report"?s!==void 0?jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>{q(s,r);},children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(Vt,{entry:"chat",petRef:n,label:e.label,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:[l.chip,c],labelStyle:l.chipLabel})}):jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(lS,"Chip");function uS(e){let t=e.color;return StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...E(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:aS},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:sS,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...E(e,"bold"),fontSize:12,lineHeight:14,color:Tp,textAlign:"center"}})}i(uS,"makeStyles");var Xi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Ap(e){return e.includes("*")||e.includes("`")}i(Ap,"hasInlineMarkup");function Op(e){let t=[],r=0;Xi.lastIndex=0;for(let n=Xi.exec(e);n!==null;n=Xi.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],s=n[2],a=n[3];o!==void 0?t.push({kind:"bold",text:o}):s!==void 0?t.push({kind:"italic",text:s}):a!==void 0&&t.push({kind:"code",text:a}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(Op,"tokenizeInlineMarkdown");function Fp(e,t){return Ap(e)?Op(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(C,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Fp,"renderInlineMarkdown");var Dp=6,Vp=520,yS=Math.round(Vp*.18),Np=.44,gS=.5,Up=[0,.5,1],hS=[0,1,2];function Hp(){let e=F(),t=useMemo(()=>vS(e),[e]),r=!e.motion.reducedMotion;return jsx(View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:hS.map(n=>r?jsx(bS,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(Hp,"TypingIndicator");function bS({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*yS),Animated.loop(Animated.timing(r,{toValue:1,duration:Vp,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Up,outputRange:[Np,1,Np]}),o=r.interpolate({inputRange:Up,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(bS,"AnimatedDot");function vS(e){let t=e.color,r=e.space,n=e.radius;return StyleSheet.create({card:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingHorizontal:r.md,paddingVertical:r.sm,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},dot:{width:Dp,height:Dp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:gS}})}i(vS,"makeStyles");function Wp(e,t,r){switch(e){case "loading":return r.renderPending?jsx(bt,{render:r.renderPending,fallback:jsx(Bp,{})}):jsx(Bp,{});case "empty":return jsx(PS,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(xS,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(_S,{messages:t.messages,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl});default:return Xe(e)}}i(Wp,"renderView");function Bp(){let{theme:e,styles:t}=Ce(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),Kc);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(Bp,"LoadingState");function PS({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=Ce();return jsxs(ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsx(Ip,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(Gp,{prompts:r,onSelectPrompt:n})]})}i(PS,"EmptyState");function Gp({prompts:e,onSelectPrompt:t}){let{styles:r}=Ce();return e.length===0?null:jsx(View,{style:r.followUps,children:e.map((n,o)=>jsx(kS,{prompt:n,index:o,onSelectPrompt:t},n))})}i(Gp,"FollowUps");function kS({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Ce(),s=X(),a=Ct(s.followUpInMs,{delayMs:yn(s,t)});return jsx(Animated.View,{style:a,children:jsxs(B,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:o.followUpSlot,style:o.followUpRow,children:[jsx(C,{style:o.followUpText,children:e}),jsx(pn,{size:AS,color:n.color.brandInk,direction:"right"})]})})}i(kS,"FollowUpRow");function xS({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ce(),o=xu(e)?Lu(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(xS,"ErrorState");function _S({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:m,onStartNew:y,petRef:k,onFindVet:g,vet:R,onOpenUrl:w}){let{styles:_}=Ce(),x=X();br(e.length,x);let b=useMemo(()=>Zc(e),[e]),P=Ju(e,n),L=e[e.length-1];return jsxs(ScrollView,{style:_.list,contentContainerStyle:_.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(I=>{let S=I.checkin?b.get(I.id):void 0;return S?.kind==="folded"?null:S?.kind==="past"?jsx(lp,{text:I.text,runDueDays:S.runDueDays,openedAt:I.checkin?.openedAt},I.id):I.checkin&&S!==void 0?jsx(sp,{message:I,checkin:I.checkin,onAnswer:o,petRef:k,onFindVet:g,vet:R},I.id):jsx(OS,{message:I,revealing:n&&I===L&&I.role==="assistant",onCopy:s,sentiment:I.responseId===void 0?null:a[String(I.responseId)]??null,onSentiment:l,thanks:u!==null&&I.responseId!==void 0&&String(I.responseId)===u,images:d[I.id]??IS,onPreview:c,onOpenUrl:w},I.id)}),f?jsx(C,{tier:"compact",style:_.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,P?jsx(Hp,{}):null,p!==null?jsx(wS,{notice:p,onRetry:m,onStartNew:y}):null,n?null:jsx(Gp,{prompts:t,onSelectPrompt:r})]})}i(_S,"PopulatedState");function wS({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Ce(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:zt,style:n.turnNoticeAction,children:jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(wS,"TurnNoticeCard");var IS=Object.freeze([]),AS=14;function OS({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u}){let{styles:d}=Ce(),c=X(),p=Ct(c.messageInMs),f=kd(e.text,t,c),m=e.role==="user",y=m?h.senderUser:h.senderAssistant,k=useCallback(R=>o(e,R),[o,e]),g=e.pending!==true;return jsxs(Animated.View,{style:[d.rowBlock,m?d.rowBlockUser:d.rowBlockAssistant,p],children:[jsx(View,{style:[d.row,m?d.rowUser:d.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[d.bubble,m?d.bubbleUser:d.bubbleAssistant,e.pending?d.bubblePending:null],children:[m&&a.length>0?jsx(zd,{images:a,onPreview:R=>l({uri:R.uri,label:R.filename})}):null,jsx(C,{style:m?d.bubbleTextUser:d.bubbleTextAssistant,children:m?e.text:Fp(f,{bold:d.bubbleBold,italic:d.bubbleItalic,code:d.bubbleCode})})]})}),!m&&!t?jsx(gp,{citations:e.citations,onOpenUrl:u}):null,g?jsx(Rp,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:k,thanks:s}):null]})}i(OS,"MessageRow");var NS=Object.freeze(["photo"]),US=1;function qp(e){let{style:t,renderPending:r}=e;return jsx(Go,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(VS,{...e})})}i(qp,"EverfurChat");function VS({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:y,lifecycle:k,draftStore:g,vetReturnTo:R,vetUsState:w,vetPrefer:_,onOpenUrl:x}){let{theme:b,styles:P}=Ce(),L=X(),I=useMemo(()=>ed(e,t),[e,t]),S=mr(I),O=Qu(S),T=Uc(),V=Ku(S),j=useSafeAreaInsets(),G=Zu(S),ne=useMemo(()=>l===void 0?void 0:()=>{q(l,"emergency");},[l]),de=useMemo(()=>R===void 0&&w===void 0&&_===void 0?void 0:{returnTo:R,usState:w,prefer:_},[R,w,_]),Pe=Li(T.pets,S.petRef),Gt=useMemo(()=>Yu(S.messages,Pe?.name??null),[S.messages,Pe?.name]),ce=Xu(Gt);br(ce.showBanner,L),Vu(S.openCheckin,f),Ou(S.askEverfur,S.isBootstrapping,m);let ot=useMemo(()=>Jo(y),[y]);Nu(k,{conversationId:S.conversationId===null?null:String(S.conversationId),isTurnInFlight:S.isStreaming,refresh:S.refreshActiveThread});let wr=(S.hasUnreadThreads??false)||V.rows.some(Ee=>Ee.unreadCount!==null&&Ee.unreadCount>0)||(S.unreadCount??0)>0,Kt=Iu(S.messages),[xt,_t]=useState(null),Yp=useCallback(()=>_t(null),[]),[qt,Un]=useState(null),[Xp,es]=useState(null),wt=useRef(null);useEffect(()=>()=>{wt.current&&clearTimeout(wt.current);},[]);let ts=useCallback(Ee=>{es(String(Ee)),wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{es(null),wt.current=null;},qc);},[]),Qp=useCallback((Ee,Ir)=>{let $t=Ee.responseId;if($t===void 0)return;let rf=S.sentimentByMessage[String($t)];S.feedback($t,Ir),Ir==="down"&&rf!=="down"&&Un($t);},[S]),Zp=useCallback(async(Ee,Ir)=>qt===null||!(await S.feedback(qt,"down",Ee??"other",Ir)).ok?false:(Un(null),ts(qt),true),[S,qt,ts]),Jp=useCallback(()=>Un(null),[]),ef=useCallback(Ee=>{S.send(Ee);},[S.send]),tf=useMemo(()=>x===void 0?void 0:Ee=>{q(x,Ee,"citation");},[x]),rs={send:S.send,stop:S.stop,isStreaming:S.isStreaming,conversationId:S.conversationId,seed:ot,draftStore:g,onStage:Kt.stage,onPreview:_t};return jsxs(KeyboardAvoidingView,{style:[P.container,{paddingTop:j.top},r],behavior:Platform.OS==="ios"?"padding":void 0,children:[jsx(kc,{pets:T,petRef:S.petRef,historyUnread:wr,onOpenHistory:V.show,onPetChange:s,onAddPet:p,vet:de}),c!==void 0?jsx(HS,{petRef:e??null,pet:c,onRegistered:T.refresh}):null,jsx(Nc,{surface:ce,petRef:S.petRef,renderVetAction:u,onFindVet:l,vet:de}),jsx(View,{style:P.body,children:Wp(O,S,{notice:G,vet:de,onCheckinFindVet:ne,onSelectPrompt:ef,renderPending:n,shownPet:Pe,onVetPrep:a,onCopy:o,onSentiment:Qp,thanksFor:Xp,imagesByMessage:Kt.byMessage,onPreview:_t,onAddPet:p,onOpenUrl:tf})}),d!==void 0?jsx(BS,{...rs,attachments:d}):jsx($p,{...rs,attachments:null}),jsx(nd,{}),b.meta.hidePoweredBy?null:jsx(C,{tier:"compact",style:P.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(Fc,{chat:S,history:V}),jsx(Ac,{visible:qt!==null,onSubmit:Zp,onSkip:Jp}),jsx(xd,{uri:xt?.uri??null,label:xt?.label??"",onClose:Yp}),jsx(Er,{})]})}i(VS,"ChatBody");function HS({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ce(),o=_u(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:zt,children:jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(HS,"PetSetupNotice");function BS({attachments:e,...t}){let r=useMemo(()=>Wd(),[]),n=an({maxPerMessage:e.maxPerMessage??US,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??NS,pick:e.pick}),[n,e.sources,e.pick]);return jsx($p,{...t,attachments:o})}i(BS,"ComposerWithAttachments");function $p({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=Ce(),p=X(),[f,m]=zu(e,n,s);ju(a,n===null?null:String(n),f,m);let[y,k]=useState(false),[g,R]=useState(false);useEffect(()=>{R(false);},[n]);let w=d.meta.placeholder??h.placeholder,_=o?.state.uploading??false,x=o?.state.failed??false,b=_||x,P=o?.state.attachments??zS;br(P.length,p);let L=useCallback(()=>{if(f.trim().length===0||b||[...f].length>Ot)return;let G=o?.state.s3Keys??jS;o!==null&&G.length>0?(l(o.state.attachments.filter(ne=>ne.status==="uploaded").map(ne=>({uri:ne.previewUri,filename:ne.filename}))),e(f,{imageS3Keys:G}),o.state.clear()):e(f),m(""),R(false);},[f,e,b,o,l]),I=useCallback(()=>{t();},[t]),S=useCallback(G=>{k(false),o!==null&&(R(false),o.state.dismissRejected(),Dt(o.pick,G).then(ne=>{if(!ne.ok){R(true);return}ne.value!==null&&o.state.add(ne.value);}));},[o]),T=useMemo(()=>[...f].length>Ot,[f])||b,V=o!==null&&P.length>=o.state.maxPerMessage,j=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&y?jsx(Id,{sources:o.sources,full:V,onPick:S,onClose:()=>k(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Bd,{attachments:P,rejected:g?WS:o.state.rejected,uploadFailed:x,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:G=>u({uri:G.previewUri,label:G.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:Tu(P.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:y},disabled:V,hitSlop:(Bt-On)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>k(G=>!G),children:jsx(cd,{size:Xc,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Lt,{style:c.input,value:f,onChangeText:m,placeholder:w,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:w,onSubmitEditing:L,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:I,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:zt,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(bd,{size:Yc,color:j,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:L,disabled:T,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:T,busy:_},hitSlop:zt,style:[c.sendControl,T?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(hd,{size:$c,color:j,testID:"everfur-send-glyph"})})})]})]})]})}i($p,"Composer");var zS=Object.freeze([]),jS=Object.freeze([]),WS=Object.freeze({code:"unknown",retryable:true,filename:""});function YS(e){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=useMemo(()=>Qe(t.registry.services.authFor(r)),[t,r,n]),s=useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=useRef(0),c=useCallback(async()=>{let p=++d.current;if(s.petRef===null){l({key:s,profile:null,loading:false,error:null});return}l(m=>({key:s,profile:m.key===s?m.profile:null,loading:true,error:null}));let f=await s.repository.getPetProfile(s.petRef);p===d.current&&l(f.ok?{key:s,profile:f.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:f.error});},[s]);return useEffect(()=>(c(),()=>{d.current+=1;}),[c]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(YS,"useEverfurPetProfile");function QS(e){return createElement(nn,{clientTheme:e.clientTheme??null,seams:sn,children:e.children})}i(QS,"EverfurThemeProvider");export{Go as CapabilityGate,qp as EverfurChat,Q as EverfurConfigError,kh as EverfurProvider,QS as EverfurThemeProvider,Ar as EverfurThrownError,qy as THEME_SLOT_KEYS,mt as THEME_SLOT_NAMES,sr as canonicalPetSpecies,Hn as categoryFor,cf as conversationId,kf as createRnRecordsUploadTransport,E as face,sf as isErr,of as isOk,Bn as isRetryableCode,uf as petRef,Eg as previewTheme,af as unwrap,Mt as useCapability,an as useChatAttachments,Xl as useEverfur,mr as useEverfurChat,YS as useEverfurPetProfile,vn as useEverfurPets,F as useEverfurTheme,It as userFacingError,df as userRef};