@everfur/sdk 0.3.0 → 0.4.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 (165) hide show
  1. package/CHANGELOG.md +69 -4
  2. package/README.md +6 -1
  3. package/dist/{Chat-DwAC2vhB.d.ts → Chat-BZZ-Py5l.d.ts} +3 -3
  4. package/dist/{Chat-DPUD6dnc.d.cts → Chat-Dq4fffIO.d.cts} +3 -3
  5. package/dist/{DepthViews-DNEM96Se.d.ts → DepthViews-BG3E25MD.d.ts} +1 -1
  6. package/dist/{DepthViews-DP0R-DhB.d.cts → DepthViews-B_hIypI6.d.cts} +1 -1
  7. package/dist/{DepthViews-DbFhR4Du.d.cts → DepthViews-CL75jyRA.d.cts} +1 -1
  8. package/dist/{DepthViews-D_3hl4xk.d.ts → DepthViews-CkYri51q.d.ts} +1 -1
  9. package/dist/animations/index.cjs +1 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +1 -1
  13. package/dist/{attachments-CQgFrEQ7.d.cts → attachments-BorG422I.d.cts} +2 -2
  14. package/dist/{attachments-5NeobOCd.d.ts → attachments-BrUWQYNK.d.ts} +5 -4
  15. package/dist/{attachments-D8T5re7e.d.cts → attachments-D_SECjr1.d.cts} +5 -4
  16. package/dist/{attachments-Bw3iMQgu.d.ts → attachments-DpldrvIW.d.ts} +2 -2
  17. package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
  18. package/dist/bookingCopy-SREvkG19.d.cts +732 -0
  19. package/dist/{entitlementRepository-DSbzuyAW.d.ts → branding-CsRdeNwK.d.cts} +1 -133
  20. package/dist/{entitlementRepository-DKdXFgTo.d.cts → branding-CsRdeNwK.d.ts} +1 -133
  21. package/dist/callCopy-DoQKG3-L.d.cts +40 -0
  22. package/dist/callCopy-DoQKG3-L.d.ts +40 -0
  23. package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
  24. package/dist/casesRepository-v6QczS9N.d.ts +51 -0
  25. package/dist/chat/index.cjs +1 -1
  26. package/dist/chat/index.d.cts +9 -8
  27. package/dist/chat/index.d.ts +9 -8
  28. package/dist/chat/index.js +1 -1
  29. package/dist/client/index.cjs +5 -5
  30. package/dist/client/index.d.cts +10 -8
  31. package/dist/client/index.d.ts +10 -8
  32. package/dist/client/index.js +5 -5
  33. package/dist/{config-CzTZGlfF.d.cts → config--Wu1Umhd.d.cts} +2 -2
  34. package/dist/{config-DW60uRb9.d.ts → config-C7eb_IMD.d.ts} +2 -2
  35. package/dist/consent/index.cjs +1 -1
  36. package/dist/consent/index.d.cts +5 -5
  37. package/dist/consent/index.d.ts +5 -5
  38. package/dist/consent/index.js +1 -1
  39. package/dist/{context-XvTzq1tE.d.cts → context-CL3lyuy1.d.cts} +6 -6
  40. package/dist/{context-DXhqHlPU.d.ts → context-CahAEha8.d.ts} +6 -6
  41. package/dist/{copy-Mjoo91aS.d.ts → copy-DdVFDL01.d.ts} +2 -2
  42. package/dist/{copy-bKDNigLb.d.cts → copy-UeUJVk8X.d.cts} +2 -2
  43. package/dist/core/index.cjs +7 -7
  44. package/dist/core/index.d.cts +118 -29
  45. package/dist/core/index.d.ts +118 -29
  46. package/dist/core/index.js +7 -7
  47. package/dist/{depth-CErXCU8J.d.cts → depth-D5HwcvKC.d.cts} +34 -3
  48. package/dist/{depth-DjDcJ6kH.d.ts → depth-DvPwPuT_.d.ts} +34 -3
  49. package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
  50. package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
  51. package/dist/{identity-DI4eVx9S.d.cts → identity-C2-08BZW.d.cts} +2 -2
  52. package/dist/{identity-BMx2SUOM.d.ts → identity-CEi9GRFZ.d.ts} +2 -2
  53. package/dist/index.cjs +6 -6
  54. package/dist/index.d.cts +17 -16
  55. package/dist/index.d.ts +17 -16
  56. package/dist/index.js +6 -6
  57. package/dist/notifications/index.cjs +2 -2
  58. package/dist/notifications/index.d.cts +2 -2
  59. package/dist/notifications/index.d.ts +2 -2
  60. package/dist/notifications/index.js +2 -2
  61. package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
  62. package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
  63. package/dist/{pets-CtQdRpWo.d.ts → pets-DJv2sj2H.d.ts} +1 -1
  64. package/dist/{pets-aB8q0JyX.d.cts → pets-JVCXgRgR.d.cts} +1 -1
  65. package/dist/{casesRepository-DHwtGRYY.d.cts → petsRepository-B_gKbAzJ.d.cts} +2 -48
  66. package/dist/{casesRepository-ClLv6qMl.d.ts → petsRepository-Bk6GDwLs.d.ts} +2 -48
  67. package/dist/photo/index.cjs +1 -1
  68. package/dist/photo/index.js +1 -1
  69. package/dist/{ports-DEBzEhbp.d.cts → ports-BY2ph0_y.d.cts} +5 -15
  70. package/dist/{ports-DMolTRzU.d.ts → ports-D7YW8qz9.d.ts} +5 -15
  71. package/dist/records/depth/index.cjs +2 -2
  72. package/dist/records/depth/index.d.cts +7 -7
  73. package/dist/records/depth/index.d.ts +7 -7
  74. package/dist/records/depth/index.js +2 -2
  75. package/dist/records/index.cjs +3 -3
  76. package/dist/records/index.d.cts +9 -9
  77. package/dist/records/index.d.ts +9 -9
  78. package/dist/records/index.js +3 -3
  79. package/dist/{requestFunnel-L-BQfi0z.d.cts → requestFunnel-BjDpqqvm.d.cts} +25 -2
  80. package/dist/{requestFunnel-CjW7uDuA.d.ts → requestFunnel-DFMGcluw.d.ts} +25 -2
  81. package/dist/{runtime-B8s-_hv8.d.cts → runtimeTypes-gZEJu-da.d.cts} +9 -99
  82. package/dist/{runtime-BR9ysG0J.d.ts → runtimeTypes-w5KqBMcs.d.ts} +9 -99
  83. package/dist/server/events/index.cjs +1 -1
  84. package/dist/server/events/index.d.cts +2 -2
  85. package/dist/server/events/index.d.ts +2 -2
  86. package/dist/server/events/index.js +1 -1
  87. package/dist/server/index.cjs +1 -1
  88. package/dist/server/index.d.cts +3 -3
  89. package/dist/server/index.d.ts +3 -3
  90. package/dist/server/index.js +1 -1
  91. package/dist/televet/booking/index.cjs +1 -0
  92. package/dist/televet/booking/index.d.cts +294 -0
  93. package/dist/televet/booking/index.d.ts +294 -0
  94. package/dist/televet/booking/index.js +1 -0
  95. package/dist/televet/call/index.cjs +1 -0
  96. package/dist/televet/call/index.d.cts +141 -0
  97. package/dist/televet/call/index.d.ts +141 -0
  98. package/dist/televet/call/index.js +1 -0
  99. package/dist/televet/index.cjs +1 -1
  100. package/dist/televet/index.d.cts +87 -5
  101. package/dist/televet/index.d.ts +87 -5
  102. package/dist/televet/index.js +1 -1
  103. package/dist/testing/index.cjs +3 -3
  104. package/dist/testing/index.d.cts +2 -2
  105. package/dist/testing/index.d.ts +2 -2
  106. package/dist/testing/index.js +3 -3
  107. package/dist/testing/rn/index.cjs +1 -1
  108. package/dist/testing/rn/index.d.cts +9 -8
  109. package/dist/testing/rn/index.d.ts +9 -8
  110. package/dist/testing/rn/index.js +1 -1
  111. package/dist/testing/web/index.cjs +1 -1
  112. package/dist/testing/web/index.d.cts +9 -8
  113. package/dist/testing/web/index.d.ts +9 -8
  114. package/dist/testing/web/index.js +1 -1
  115. package/dist/{timelineRows-DZed6dAM.d.ts → timelineRows-C15jxFFH.d.ts} +1 -1
  116. package/dist/{timelineRows-CaohZzXS.d.cts → timelineRows-odO8g9r2.d.cts} +1 -1
  117. package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
  118. package/dist/typeStyle-DmoyacDG.d.ts +111 -0
  119. package/dist/{useRecordsDepth-BHBzJ76R.d.cts → useRecordsDepth-C6rjEaLn.d.cts} +1 -1
  120. package/dist/{useRecordsDepth-BU-OhzH6.d.ts → useRecordsDepth-crhBllQK.d.ts} +1 -1
  121. package/dist/video/index.cjs +1 -1
  122. package/dist/video/index.js +1 -1
  123. package/dist/{view-DtSPYpKa.d.ts → view-Bxwxp4xD.d.ts} +2 -2
  124. package/dist/{view-C3qPIXGX.d.cts → view-DyitEO0m.d.cts} +2 -2
  125. package/dist/web/consent/index.cjs +1 -1
  126. package/dist/web/consent/index.d.cts +5 -5
  127. package/dist/web/consent/index.d.ts +5 -5
  128. package/dist/web/consent/index.js +1 -1
  129. package/dist/web/index.cjs +7 -7
  130. package/dist/web/index.d.cts +18 -17
  131. package/dist/web/index.d.ts +18 -17
  132. package/dist/web/index.js +7 -7
  133. package/dist/web/notifications/index.cjs +2 -2
  134. package/dist/web/notifications/index.d.cts +3 -3
  135. package/dist/web/notifications/index.d.ts +3 -3
  136. package/dist/web/notifications/index.js +2 -2
  137. package/dist/web/records/depth/index.cjs +2 -2
  138. package/dist/web/records/depth/index.d.cts +7 -7
  139. package/dist/web/records/depth/index.d.ts +7 -7
  140. package/dist/web/records/depth/index.js +2 -2
  141. package/dist/web/records/index.cjs +3 -3
  142. package/dist/web/records/index.d.cts +102 -11
  143. package/dist/web/records/index.d.ts +102 -11
  144. package/dist/web/records/index.js +3 -3
  145. package/dist/web/televet/booking/index.cjs +1 -0
  146. package/dist/web/televet/booking/index.d.cts +349 -0
  147. package/dist/web/televet/booking/index.d.ts +349 -0
  148. package/dist/web/televet/booking/index.js +1 -0
  149. package/dist/web/televet/call/index.cjs +1 -0
  150. package/dist/web/televet/call/index.d.cts +142 -0
  151. package/dist/web/televet/call/index.d.ts +142 -0
  152. package/dist/web/televet/call/index.js +1 -0
  153. package/dist/web/televet/index.cjs +1 -1
  154. package/dist/web/televet/index.d.cts +90 -4
  155. package/dist/web/televet/index.d.ts +90 -4
  156. package/dist/web/televet/index.js +1 -1
  157. package/package.json +72 -4
  158. package/televet/booking/package.json +8 -0
  159. package/televet/call/package.json +8 -0
  160. package/web/televet/booking/native-blocked.cjs +12 -0
  161. package/web/televet/booking/package.json +8 -0
  162. package/web/televet/call/native-blocked.cjs +12 -0
  163. package/web/televet/call/package.json +8 -0
  164. package/dist/typeStyle-0TydiZ1w.d.cts +0 -19
  165. 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 Pg 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 Ep=Object.defineProperty;var i=(e,t)=>Ep(e,"name",{value:t,configurable:true});function Ee(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(Ee,"hasLoneSurrogate");function rt(e){return [...e].length}i(rt,"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 Rp(e){return e.ok}i(Rp,"isOk");function Sp(e){return !e.ok}i(Sp,"isErr");var _r=class _r 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,_r.prototype);}};i(_r,"EverfurThrownError");var xr=_r;function Pp(e){if(e.ok)return e.value;throw new xr(e.error)}i(Pp,"unwrap");var wr=class wr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,wr.prototype);}};i(wr,"EverfurConfigError");var Z=wr;var Bi=128,Hi=128,zi=/[\u0000-\u001F\u007F]/,Tp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kp(e){let t=e,r=rt(t);if(r===0||r>Hi)throw new Z("invalid-argument",`petRef must be 1..${Hi} characters`);if(zi.test(t))throw new Z("invalid-argument","petRef must be printable (no control characters)");return t}i(kp,"petRef");function xp(e){let t=e,r=rt(t);if(r===0||r>Bi)throw new Z("invalid-argument",`userRef must be 1..${Bi} characters`);if(t.includes("@"))throw new Z("invalid-argument","userRef must not contain '@'");if(zi.test(t))throw new Z("invalid-argument","userRef must be printable (no control characters)");return t}i(xp,"userRef");function _p(e){if(!Tp.test(e))throw new Z("invalid-argument","conversationId must be a UUID");return e}i(_p,"conversationId");var On=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(On.map(e=>e.wireCode));var wp=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"}),Wi=Object.freeze(On.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:wp[e.wireCode]}))),Ip=new Map(Wi.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Ap=Object.freeze(["http_envelope",...[...new Set(Wi.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ir(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...Ap]){let o=Ip.get(n+r);if(o)return o}}i(Ir,"contractErrorFor");function Op(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Op,"contractDocUrl");function Gi(e){return null}i(Gi,"publishedDocUrl");var Fp=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 Fn(e){return Fp[e]}i(Fn,"categoryFor");function we(e){let t=Ir(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(we,"fromWire");function Ki(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(Ki,"fromHttpStatus");var Mp=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Ue(e){return Mp.has(e)}i(Ue,"isAutoRetryable");var Lp=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Mn(e){return Ue(e)||Lp.has(e)}i(Mn,"isRetryableCode");function Ar(e,t=false){return t||Ue(e)}i(Ar,"shouldRetry");var Dp=500,Ln=8e3,Kt=4;function Or(e,t=Math.random){let r=Math.max(0,e),n=Math.min(Dp*2**r,Ln);return Math.floor(t()*n)}i(Or,"backoffDelayMs");function qi(e){return e==="conversationNotFound"}i(qi,"canRecreateOnNotFound");var Np=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 wt(e){return Np[e]}i(wt,"userFacingError");function $i(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i($i,"defineHidden");var Up=/^[a-z][a-z0-9_]{0,63}$/;function L(e,t){let r=Ir(t?.wireCode,t?.wireEnvelope),n={code:e,category:Fn(e),retryable:t?.retryable??Mn(e),displayMessage:wt(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&&$i(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&$i(n,"raw",t.raw),Object.freeze(n)}i(L,"makeEverfurError");var Vp="file",Bp="document.pdf",Hp="records upload: the file handle has no uri",zp="records upload failed";function jp(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Hp));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(zp)),"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(Vp,{uri:r.uri,name:Bp,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(jp,"createRnRecordsUploadTransport");var Fr=Object.freeze({track(){},trackExpectedFailure(){}});var Yi=Object.freeze({shouldRetry(e,t){return Ue(e)&&t<Kt},maxAttempts(){return Kt}});var Xi=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Ke(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Ke,"assertNever");function Qi(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Qi,"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 es(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(es,"doneFrame");function ce(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(ce,"errorFrame");function ts(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ts,"analysisStartedFrame");function rs(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(rs,"analysisCompleteFrame");function ns(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(ns,"unknownFrame");function os(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 Z("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:Kp(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new Z("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(os,"createIdentityProvider");function Kp(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(Kp,"expiryMs");function Nn(){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(Nn,"newSessionId");function qp(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(qp,"authHeaders");function qt(e,t){return {...e,headers:{...$p(e.headers),...qp(t)}}}i(qt,"withAuthHeaders");function $p(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($p,"stripAuthHeaders");async function is(e,t){if(t.mode==="anonymous")return t.transport.request(qt(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(Dn())}let n=await t.transport.request(qt(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(Dn())}let s=await t.transport.request(qt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(Dn(s.error.httpStatus)):s}i(is,"authedSend");function Dn(e){return L("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Dn,"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
+ `,Yp=1048576,Xp=z.record(z.string(),z.unknown()),Qp=["emergency","schedule_soon","home_care"];async function*Mr(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=as(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>Yp){yield ce({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=as(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield ce({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Mr,"parseSse");function as(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=Xp.safeParse(o);return s.success?Zp(s.data,r,t):null}i(as,"parseBlock");function Zp(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return ce({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 es({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:tf(e.follow_up_questions),citations:ls(e.citations),citationStatus:le(e.citation_status),urgencyLevel:us(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:ef(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return Qi(le(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=le(e.delta)??le(e.token)??"";return Ji(s,t,r)}return o==="analysis_started"?ts(le(e.request_id),t,r):o==="analysis_complete"?rs({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:Jp(e.confidence),detections:ls(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):ns(e,t,r)}i(Zp,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function Jp(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Jp,"asNumber");function us(e){return typeof e=="string"&&Qp.includes(e)?e:null}i(us,"asUrgency");function ef(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||us(t)!==null}i(ef,"urgencySlotProvided");function tf(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(tf,"asStringList");function rf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(rf,"isPlainObject");function ls(e){return Array.isArray(e)?e.filter(rf):[]}i(ls,"asMapList");var nf="0.4.0",of="react-native",sf="2026-09-19",ds="EVERFUR_API_BASE_URL";function $t(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i($t,"configFailure");function Vn(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(Vn,"checkPublishableKey");function cs(e,t){let r=Vn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=af(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||sf;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:nf,platform:t?.platform??of,debug:e.debug===true})})}i(cs,"tryResolveClientConfig");function af(e){let t=e?.trim(),r=t&&t.length>0?t:yf(ds);return r?ff(r):$t("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ds}. The SDK never ships a hardcoded host.`)}i(af,"tryResolveApiBaseUrl");function ps(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(ps,"buildBaseHeaders");var lf=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function uf(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(uf,"hostOf");function df(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(df,"isPrintableHost");function cf(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:df(t)}i(cf,"canEchoOrigin");function pf(e,t){return `${e}://${t}`}i(pf,"safeOrigin");function ff(e){let t=e.trim(),r=lf.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return $t("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=uf(r[2]);if(o.length===0)return $t("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=cf(t,o)?`: ${pf(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&mf(o)))return n==="http"?$t("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):$t("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(ff,"normalizeBaseUrl");function mf(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(mf,"isLoopbackHost");function yf(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(yf,"readEnv");var gf=3e4,gs="x-request-id";async function*fs(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(fs,"fetchByteSource");function hf(e){let t=new TextEncoder,r=vf(),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=vs(d),p=Ue(we(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"),bf(r.source,l)}i(hf,"eventSourceByteSource");async function*bf(e,t){try{yield*e;}finally{t();}}i(bf,"sourceWithCleanup");function vf(){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(vf,"createByteQueue");async function Cf(e,t){let r=t.fetchImpl??Cs(),n=Es(t.config.apiBaseUrl,e.path,e.query),o=Rs(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=kf(gf),a=xf(s.signal,e.signal),l;try{l=await r(n,Ss({...e,signal:a},o));}catch(d){return v(Bn(d))}finally{s.cancel();}let u=await Ps(l);return l.ok?M(u):v(Sf(l.status,u,bs(l)))}i(Cf,"requestJson");function hs(e){return {request:i(t=>Cf(t,e),"request"),stream:i((t,r)=>Ef(Tf(t,r),e),"stream")}}i(hs,"createHttpTransport");async function*Ef(e,t){let r=Es(t.config.apiBaseUrl,e.path,e.query),n=Rs(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Rf(e,n));yield*Mr(hf(l),()=>Pf(l));return}let o=t.fetchImpl??Cs(),s;try{s=await o(r,Ss(e,n));}catch(l){yield ms("",true,_s(l));return}let a=bs(s);if(!s.ok){let l=await Ps(s),u=Ts(l)??vs(s.status),d=xs(l)||Ue(we(u));yield ms(u,d,ks(l),a);return}if(s.body){yield*Mr(fs(s.body),a);return}yield*Mr(fs(null),a);}i(Ef,"streamFrames");function Rf(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Rf,"buildEventSourceInit");function Sf(e,t,r){let n=Ts(t),o=n?we(n):Ki(e),s=ks(t);return L(o,{httpStatus:e,...xs(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...ys(t)?{reasonCode:ys(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Sf,"errorFromResponse");function Bn(e){return L("internalError",{retryable:true,wireMessage:_s(e)})}i(Bn,"networkError");function bs(e){let t=e.headers.get(gs);return typeof t=="string"&&t.length>0?t:null}i(bs,"requestIdOf");function Pf(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(gs);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Pf,"eventSourceRequestId");function vs(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(vs,"statusToWireCode");function ms(e,t,r,n=null){return ce({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(ms,"syntheticErrorFrame");function Cs(){let e=globalThis.fetch;if(typeof e!="function")throw new Z("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Cs,"getGlobalFetch");function Es(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(Es,"buildUrl");function Rs(e,t,r,n){let o={...ps(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Rs,"mergeHeaders");function Ss(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(Ss,"buildInit");function Tf(e,t){return e.signal?e:{...e,signal:t}}i(Tf,"withSignal");function kf(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(kf,"timeoutSignal");function xf(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(xf,"mergeAbortSignals");async function Ps(e){try{return await e.json()}catch{return null}}i(Ps,"safeJson");function ys(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(ys,"extractReasonCode");function Ts(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Ts,"extractWireCode");function ks(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(ks,"extractWireMessage");function xs(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(xs,"extractRetryable");function _s(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(_s,"describeCause");var _f=3e4,wf=Ln*2,If="idempotency-key",Af=new Set(["POST","PUT","PATCH","DELETE"]),Of=Object.freeze({onEvent(){}}),Ff=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Mf(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Mf,"seededIdempotencyKey");function Re(e){let t=e.observer??Of,r=e.timers??Ff,n=e.rng??Math.random,o=e.sleep??((f,m)=>qf(f,r,m)),s=e.maxAttempts??Kt,a=e.unaryTimeoutMs??_f,l=e.newIdempotencyKey??Df(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,g){let x=g?.maxAttempts,y=Math.max(1,x??s),S=g?.idempotent??Af.has(m.method),_=g?.idempotencyKey===void 0?null:Mf(g.idempotencyKey),A=S?_??l():null,k=Lf(m,A),b=0;for(;;){let R=i(K=>Object.freeze({call:f,method:m.method,path:m.path,attempt:b,...A?{idempotencyKey:A}:{},...K}),"stamp");u(R({phase:"attempt"}));let P=Gf(a,r),V=Kf(P.signal,m.signal),I;try{I=await is({...k,signal:V.signal},e.auth);}catch(K){I=v(Bn(K));}finally{V.dispose(),P.cancel();}if(I.ok)return u(R({phase:"settled",ok:true,reason:"ok"})),I;let w=I.error,T=Uf(w,b,{maxAttempts:y,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...x!==void 0?{perCallMaxAttempts:x}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),B={ok:false,code:w.code,reason:T.reason,...w.httpStatus!==void 0?{httpStatus:w.httpStatus}:{},...w.requestId!==void 0?{requestId:w.requestId}:{}};if(!T.retry)return u(R({phase:"settled",...B})),v(w);if(u(R({phase:"retry",...B,delayMs:T.delayMs})),await o(T.delayMs,m.signal),m.signal?.aborted===true)return u(R({phase:"settled",...B,reason:"aborted"})),v(w);b+=1;}}i(d,"send");async function c(f){return qt(f,await Wf(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 ce({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 Lf(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==If&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Lf,"assembleHeaders");function Df(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Df,"defaultIdempotencyKeyFactory");var Nf=10;function Uf(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Vf(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!Ue(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(Nf,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=Bf(e,r.now);return u!==null?u>wf?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Or(t,r.rng)}}i(Uf,"decideRetry");function Vf(e){let t=e.code==="unknown"?we(jf(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Vf,"throttleKind");function Bf(e,t){let r=Hf(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(Bf,"retryOverrideMs");function Hf(e){for(let t of Is(e)){let r=t.resets_at,n=zf(r);if(n!==null)return n}return null}i(Hf,"findResetsAt");function Is(e){if(!ws(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];ws(n)&&t.push(n);}return t}i(Is,"candidateScopes");function zf(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(zf,"parseInstantMs");function jf(e){for(let t of Is(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(jf,"rawWireCode");function ws(e){return typeof e=="object"&&e!==null}i(ws,"isRecord");async function Wf(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(Wf,"resolveDeviceAuth");function Gf(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Gf,"boundedSignal");function Kf(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(Kf,"mergeSignals");function qf(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(qf,"delayAbortable");var Lr=Object.freeze(["better","same","worse"]),zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function As(e){return v(L("validationFailed",{retryable:false,wireMessage:e}))}i(As,"invalid");function Hn(){return v(L("internalError",{retryable:false}))}i(Hn,"malformed");function Os(e){return typeof e!="string"||e.trim().length===0?L("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Ee(e)?L("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Os,"petPath");var Ve=i(e=>typeof e=="string"?e:null,"str");function Fs(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ve(t.case_id),n=Ve(t.status);if(r===null||n===null)return null;let o=Ve(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Ve(t.body_location),lastResponse:o!==null&&Lr.includes(o)?o:null,checkInDueAt:Ve(t.check_in_due_at),openedAt:Ve(t.opened_at),resolvedAt:Ve(t.resolved_at),resolutionText:Ve(t.resolution_text)})}i(Fs,"caseFromWire");function Ms(e){return {async list(t,r){let n=Os(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 Hn();let a=s.map(Fs);return a.every(l=>l!==null)?M(Object.freeze(a)):Hn()},async checkin(t,r,n,o){let s=Os(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!zn.test(r))return As("case_id must be a UUID");if(!Lr.includes(n))return As("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=Fs(l.case);return u===null?Hn():M(Object.freeze({case:u,ctaDeepLink:Ve(l.cta_deep_link)}))}}}i(Ms,"createCasesRepositoryOver");var Ls=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var Ds=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Nr(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(Nr,"delayAbortable");function Ur(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(Ur,"mergeSignals");var jn=class jn{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?Ur(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(jn,"MediaStore");var Dr=jn;function Gn(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Gn,"makeUser");function Kn(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(Kn,"makeAssistant");function Xt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(Xt,"stripPending");function Ns(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(Ns,"appendText");function qn(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(qn,"finalizeAssistant");function Us(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(Us,"freezeSnapshot");function N(e,t,r){return L(e,{retryable:t,...r?{wireMessage:r}:{}})}i(N,"makeError");function $n(e){let t=we(e.code);return L(t,{retryable:e.retryable||Ar(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i($n,"errorFromFrame");function Ie(e){return ce({code:$f(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Ie,"synthErrorFrame");function $f(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 Ke(e)}}i($f,"canonicalWireCode");function Vs(e){let t=Array.isArray(e)?e:Wn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!Wn(n))continue;let o=Yt(n.category)??Yt(n.title)??"",s=Yf(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(Vs,"parsePromptCategories");function Yn(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(Yn,"flattenPrompts");function Wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Wn,"isPlainObject");function Yt(e){return typeof e=="string"?e:null}i(Yt,"asStr");function Yf(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Wn(r)){let n=Yt(r.text)??Yt(r.prompt)??Yt(r.title);n!==null&&t.push(n);}return t}i(Yf,"asPromptTextList");function Bs(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(Bs,"defaultIdFactory");function Hs(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Hs,"defaultIdempotencyFactory");var js={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*Ws(e,t,r,n){let o=e[Symbol.asyncIterator](),s=zs(t.overallMs,n),a=zs(t.idleMs,n),l=Zf(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 Qf();return}if(d.tag==="idle"||d.tag==="overall"){yield Xf();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(Ws,"withWatchdog");function Xf(){return ce({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Xf,"synthTimeoutFrame");function Qf(){return ce({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Qf,"synthStreamErrorFrame");function zs(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(zs,"deadline");function Zf(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Zf,"abortPromise");var Jf="checkin",em=/^\d{4}-\d{2}-\d{2}$/,Vr="watching";function Gs(e){return e.status!=null&&e.status!==Vr}i(Gs,"isCheckinSettled");function Ks(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Jf||n===void 0||o===void 0||!zn.test(n)||!em.test(o)?null:n}i(Ks,"parseCheckinOriginRef");function Xn(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(L("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||Ee(o))return v(L("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(Xn,"historyQuery");function Jt(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(Jt,"validConversationId");function Zt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Zt,"object");function qs(e){return e==null||typeof e=="string"&&e.length>0&&!Ee(e)}i(qs,"cursor");function Qt(){return v(L("internalError",{retryable:false}))}i(Qt,"malformed");function $s(e){let t=Zt(e);if(!t||!Array.isArray(t.conversations)||!qs(t.next_cursor))return Qt();let r=[];for(let n of t.conversations){let o=Zt(n);if(!o||typeof o.conversation_id!="string"||!Jt(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return Qt();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return Qt();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($s,"mapConversationPage");function Ys(e){let t=Zt(e);if(!t||!Array.isArray(t.messages)||!qs(t.next_cursor))return Qt();let r=[],n=new Set;for(let o of t.messages){let s=Zt(o);if(!s||typeof s.message_id!="string"||!Jt(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return Qt();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"?Ks(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:tm(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:rm(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(Ys,"mapMessagePage");function tm(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(tm,"normalizeUrgency");function rm(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=Zt(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(rm,"historyCitations");var Qn=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),It=4e3;var At=4e3;function Xs(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:N("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:N("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(Xs,"validateImageKeys");function Jn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:N("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>At?{reason:"too_long",error:N("validationFailed",false,`message is ${r} characters; the server accepts at most ${At}`)}:null}i(Jn,"validateMessageText");function Qs(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Qs,"urgencyTier");async function*er(e){yield e;}i(er,"singleFrameStream");async function*Zs(){}i(Zs,"emptyStream");var nm=6e4,om=18e4,im=24,sm=512,am=false;function Js(e){return new eo(e)}i(Js,"createChatController");var to=class to extends Dr{constructor(r){super(Us({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=Ms(this.funnel),this.telemetry=r.telemetry??Fr,this.errorPolicy=r.errorPolicy??Yi,this.timers=r.timers??js,this.rng=r.rng??Math.random,this.newId=r.newId??Bs(),this.makeIdempotencyKey=r.makeIdempotencyKey??Hs(),this.budget={idleMs:r.budget?.idleMs??nm,overallMs:r.budget?.overallMs??om};}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=N(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):er(Ie(u))}let a=Jn(r)??Xs(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),()=>{}):er(Ie(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 er(Ie(N("accessDenied",false)));let o=Jn(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),er(Ie(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):Zs()}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,Gn(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?Xt(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(Yn(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=Xn(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(N("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(N("accessDenied",false));if(!a.ok)return a;let l=$s(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(N("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(N("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(N("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(N("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Ee(r))return v(N("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Qn.includes(n))return v(N("validationFailed",false,`feedback_type must be one of ${Qn.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>It)return v(N("validationFailed",false,`notes is over ${It} 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(N("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(N("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(N("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(N("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(!Jt(r))return v(N("validationFailed",false));let o=Xn(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(N("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(N("accessDenied",false)):a.ok?Ys(a.value):a}async resumeConversation(r){if(this.disposed)return v(N("accessDenied",false));if(!Jt(r))return v(N("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(N("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===Vr).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)?Vr: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(N("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(N("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(N("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(N("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 Ie(n.error));}async primeConversation(r){if(this.disposed)return v(N("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(N("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(N("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(N("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(N("internalError",true)):M(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(N("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Ee(o))return v(L("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(N("accessDenied",false)):a.ok?M(Vs(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=Ur(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,Gn(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,Ie(y.error));return}this.adoptConversation(y.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let y=N("internalError",!0);yield*this.emitTerminal(r,y,Ie(y));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Ur(o.signal,p.signal),m=null;try{let y;try{y=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let _=this.authRejected();yield*this.emitTerminal(r,_,Ie(_));return}if(o.signal.aborted||!this.alive(o.epoch))return;let S=this.funnel.stream("chat.send",y,f);for await(let _ of Ws(S,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(_.kind==="error"&&_.terminal){m=_;break}if(this.applyFrame(_,r),yield _,_.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=N("streamIncomplete",!0);yield*this.emitTerminal(r,y,Ie(y));return}let g=we(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 S=this.authRejected();yield*this.emitTerminal(r,S,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,$n(m),m);return}if(qi(g)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let x=m.retryable&&Ar(g,!0);if(am&&x&&s+1<this.errorPolicy.maxAttempts(g));yield*this.emitTerminal(r,$n(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 Ke(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?Xt(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,Kn(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=sm){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);},im);}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?Ns(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?qn(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?Xt(d):d),qn(Kn(l,"",this.stamp()),r)];}let a=Yn([{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=Qs(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?Xt(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 N("authRejected",false)}};i(to,"ChatControllerImpl");var eo=to;async function ra(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(k=>k.ok?M(o):k):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,g]=await Promise.all([p,f]),x=null;if(m.ok)x=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let k=m.error;c=k,ea(k)?(l=true,d=k):(ta(k)&&(a=true),u=true);}let y=[];g.ok?y=g.value:S(g.error);function S(k){ea(k)?(l=true,d===null&&(d=k)):ta(k)&&(a=true);}i(S,"recordAuthSignals");let _=d!==null?d.displayMessage:null;return Object.freeze({conversationId:x,petRef:n,suggestedPrompts:y,error:_,warning:_===null&&x===null&&u?lm:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(ra,"bootstrapChat");var lm="Chat is ready. Your first message will start the conversation.";function ea(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(ea,"isUnauthorized");function ta(e){return e.httpStatus===403||e.code==="accessDenied"}i(ta,"isForbidden");var ro=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function na(e){return e!==ro}i(na,"isUploadTransportAvailable");var um=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Br=10*1024*1024,Hr=5,tr=120,dm="/widget/v1/uploads/initiate";function cm(e){return typeof e=="string"&&um.includes(e.trim().toLowerCase())}i(cm,"isAttachmentMime");function no(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<=tr)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,tr);let n=t.slice(r);return n.length>=tr?t.slice(0,tr):`${t.slice(0,r).slice(0,tr-n.length)}${n}`}i(no,"sanitizeFilename");function oo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(oo,"formatBytes");var rr=i(e=>Object.freeze({ok:true,value:e}),"ok"),Se=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 pm(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(pm,"attachmentSize");function fm(e){let t=no(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!cm(r))return Se(oe("unsupported_type",false,t));let n=pm(e);return n===null?Se(oe("unknown",false,t)):n>Br?Se(oe("too_large",false,t,{sizeBytes:n})):rr(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(fm,"validateAttachment");function mm(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)??Br,s3_key:a,purpose:r(t.purpose)})}i(mm,"parsePolicy");function ym(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(ym,"initiateFailure");async function gm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:dm,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Se(ym(n.error,t.filename));let o=mm(n.value);return o===null?Se(oe("server",false,t.filename)):rr(o)}i(gm,"initiateAttachmentUpload");async function hm(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return Se(oe("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),rr(void 0)}catch{return o()?Se(oe("cancelled",true,r.filename)):Se(oe("server",true,r.filename))}}i(hm,"uploadAttachmentBytes");var bm=2,vm=3,Cm=Object.freeze([1e3,2e3,4e3]),oa=0;function Em(){return oa+=1,`attachment-${oa}`}i(Em,"defaultNewId");function ia(e){let t=Math.max(1,e.concurrency??bm),r=Math.max(1,e.maxAttempts??vm),n=e.backoffMs??Cm,o=Math.max(1,e.maxPerMessage??Hr),s=e.timers??Ds,a=e.newId??Em,l=na(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),g=false,x=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let R=u.get(b);return R===void 0?[]:[R.state]}))});for(let b of f)b();},"publish"),y=i((b,R)=>{b.state=Object.freeze({...b.state,...R}),x();},"patch"),S=i(()=>{for(;!g&&p.size<t&&c.length>0;){let b=c.shift(),R=u.get(b);R!==void 0&&(p.add(b),_(R).finally(()=>{p.delete(b),S();}));}},"pump"),_=i(async b=>{let{attachment:R}=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 gm(e.funnel,R,{signal:P});if(g||P.aborted)return;let I;if(!V.ok)I=Se(V.error);else {let K=await hm(e.transport,V.value,R,{signal:P,onProgress:i(W=>{!P.aborted&&b.state.status==="uploading"&&y(b,{progress:Rm(W)});},"onProgress")});if(g||P.aborted)return;I=K.ok?rr(V.value.s3_key):Se(K.error);}if(I.ok){y(b,{status:"uploaded",s3Key:I.value,error:null,progress:1});return}let w=I.error,T=w.retryable&&b.attempts<r;if(y(b,{status:T?"uploading":"failed",error:w,progress:0}),!T)return;let B=n[Math.min(b.attempts-1,n.length-1)]??0;await Nr(B,P,s);}},"run"),A=i(b=>{c.push(b.state.id),S();},"enqueue"),k={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 R=fm(b);if(!R.ok)return R;if(g||d.length>=o)return Se(oe("too_many",false,R.value.filename));let P=a(),V={attachment:R.value,controller:new AbortController,attempts:0,state:Object.freeze({id:P,filename:R.value.filename,previewUri:b.uri,contentType:R.value.contentType,sizeBytes:R.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(P,V),d.push(P),x(),A(V),rr(V.state)},retry(b){let R=u.get(b);R===void 0||g||R.state.status!=="failed"||(R.controller=new AbortController,R.attempts=0,y(R,{status:"uploading",error:null,progress:0,s3Key:null}),A(R));},remove(b){let R=u.get(b);if(R===void 0)return;R.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),x();},clear(){for(let b of [...d])k.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 k}i(ia,"createAttachmentQueue");function Rm(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Rm,"clamp");var sa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function nr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(sa,t)?sa[t]:null}i(nr,"canonicalPetSpecies");var aa=50,Sm=128,io=120,la=120,Pm=2e3,ua=120,Tm=80,pa=new Set(["male","female","unknown"]),fa=new Set(["day","month","year"]),ma=new Set(["low","medium","high","athletic"]),ya=new Set(["indoor","outdoor","both"]),ga=new Set(["mild","moderate","severe"]),km=/^(\d{4})-(\d{2})-(\d{2})$/,ha=[["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"]],ba=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...ha,...ba].map(([e])=>e));function xm(e){let t=km.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(xm,"isRealDate");var ir=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),_m=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),jr=i((e,t)=>typeof t=="string"&&xm(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Ae=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Ee(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=rt(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),wm={sex:ir(pa),spayedNeutered:_m,birthDate:jr,birthDatePrecision:ir(fa),activityLevel:ir(ma),indoorOutdoor:ir(ya),foodBrand:Ae(ua),foodType:Ae(ua),microchipId:Ae(Tm)},so=["ref","ref",false,Ae(Sm,{required:true,trimmed:true})],ao=["notes","notes",false,Ae(Pm,{trimmed:true})],da=[so,["name","name",true,Ae(io,{required:true,trimmed:true})],["dose","dose",false,Ae(la,{trimmed:true})],["frequency","frequency",false,Ae(la,{trimmed:true})],["startDate","start_date",false,jr],["endDate","end_date",false,jr],ao],Im={allergies:[so,["allergen","allergen",true,Ae(io,{required:true,trimmed:true})],["severity","severity",false,ir(ga)],ao],medications:da,supplements:da,conditions:[so,["conditionName","condition_name",true,Ae(io,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,jr],ao]};function Am(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 Im[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(Am,"itemToWire");function Om(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>aa)return {error:`${e} has ${t.length} items; the server accepts at most ${aa}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=Am(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(Om,"listToWire");function va(e,t){let r=e,n={};for(let[a,l]of ha){let u=r[a];if(u!==void 0){if(u!==null){let d=wm[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 ba){let u=r[a];if(u===void 0)continue;let d=Om(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&nr(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(va,"petHealthToWire");var te=i(e=>typeof e=="string"?e:null,"str"),or=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),Fm=i(e=>typeof e=="boolean"?e:null,"bool");function zr(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(zr,"itemsFromWire");function ca(e){let t=te(e.name);return t===null||t.length===0?null:Object.freeze({ref:te(e.ref),name:t,dose:te(e.dose),frequency:te(e.frequency),startDate:te(e.start_date),endDate:te(e.end_date),notes:te(e.notes)})}i(ca,"medicationFromWire");function Ca(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:or(pa,e.sex),spayedNeutered:Fm(e.spayed_neutered),birthDate:te(e.birth_date),birthDatePrecision:or(fa,e.birth_date_precision),activityLevel:or(ma,e.activity_level),indoorOutdoor:or(ya,e.indoor_outdoor),foodBrand:te(e.food_brand),foodType:te(e.food_type),microchipId:te(e.microchip_id),allergies:zr(e.allergies,r=>{let n=te(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),allergen:n,severity:or(ga,r.severity),notes:te(r.notes)})}),medications:zr(e.medications,ca),supplements:zr(e.supplements,ca),conditions:zr(e.conditions,r=>{let n=te(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),conditionName:n,diagnosedDate:te(r.diagnosed_date),notes:te(r.notes)})})})}i(Ca,"petHealthFromWire");var Sa=100,Pa=50,Ta=100,ka=50,xa=500,Mm=128,Lm=6e4;function Fe(e){return L("validationFailed",{retryable:false,wireMessage:e})}i(Fe,"invalid");function nt(e,t,r){if(typeof t!="string")return Fe(`${e} must be a string`);let n=rt(t);return n<=r?null:Fe(`${e} is ${n} characters; the server accepts at most ${r}`)}i(nt,"checkString");function Wr(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Fe(`${e} must be a finite number between 0 and ${r}`)}i(Wr,"outOfRange");function Ea(e,t){if(typeof e!="string")return Fe("pet_ref must be a string");if(e.trim().length===0)return Fe("pet_ref must not be blank");if(Ee(e))return Fe("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Fe("profile must be an object");let r=[nt("pet_ref",e,Mm)];return t?.name!==void 0&&r.push(nt("name",t.name,Sa)),t?.species!==void 0&&r.push(nt("species",t.species,Pa)),t?.breed!==void 0&&r.push(nt("breed",t.breed,Ta)),t?.ageYears!==void 0&&r.push(Wr("age_years",t.ageYears,ka)),t?.weightKg!==void 0&&r.push(Wr("weight_kg",t.weightKg,xa)),r.find(n=>n!==null)??null}i(Ea,"validate");function _a(e,t){let r=va(e,t);return "error"in r?{error:Fe(r.error)}:r}i(_a,"healthToWire");function Dm(e){if(typeof e!="object"||e===null)return {error:Fe("patch must be an object")};let t=e,r=[["name","name",s=>nt("name",s,Sa)],["species","species",s=>nt("species",s,Pa)],["breed","breed",s=>nt("breed",s,Ta)],["ageYears","age_years",s=>Wr("age_years",s,ka)],["weightKg","weight_kg",s=>Wr("weight_kg",s,xa)]],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=_a(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Fe("patch must change at least one field")}:{body:n})}i(Dm,"patchToWire");function Nm(e){if(e==null)return {body:{}};let t=_a(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(Nm,"toWire");var Oe=i(e=>typeof e=="string"?e:null,"str"),Gr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ra(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Oe(r.pet_ref)??t,name:Oe(r.name),species:Oe(r.species),breed:Oe(r.breed),ageYears:Gr(r.age_years),weightKg:Gr(r.weight_kg)})}i(Ra,"fromWire");function wa(e){if(typeof e!="object"||e===null)return null;let t=e,r=Oe(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Oe(t.pet_id),petRef:r,name:Oe(t.name),species:Oe(t.species),breed:Oe(t.breed),ageYears:Gr(t.age_years),weightKg:Gr(t.weight_kg),updatedAt:Oe(t.updated_at)})}i(wa,"widgetPetFromWire");function Um(e){let t=wa(e);return t===null?null:Object.freeze({...t,...Ca(e)})}i(Um,"widgetPetProfileFromWire");function Vm(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=wa(r);return n===null?[]:[n]}))}i(Vm,"petListFromWire");function qe(e){return Bm(Re({auth:e}),Re({auth:e,unaryTimeoutMs:Lm}))}i(qe,"createPetsRepository");function Bm(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Ea(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(Vm(s.value)):v(s.error)},async registerPet(o,s,a){let l=Ea(o,s);if(l!==null)return v(l);let u=Nm(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(Ra(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=Dm(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(Ra(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=Um(l.value);return u===null?v(L("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(Bm,"createPetsRepositoryOver");var uo=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 Hm(e){return uo[e]}i(Hm,"requires");function Ia(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(uo))for(let a of uo[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Ia,"deniedDecisionsFor");function Aa(e,t,r){let n=Hm(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 lo({name:e,enabled:false,isPending:true,limits:{}});let s=zm(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?lo({name:e,enabled:true,isPending:false,limits:s}):lo({name:e,enabled:false,isPending:false,limits:s,disabled:jm(n,o)})}i(Aa,"decideCapability");function zm(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(zm,"mergeLimits");function jm(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:wt("accessDenied"),level:"user_entitlement",recoverable:false})}i(jm,"disabledFor");function lo(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(lo,"freezeDecision");function ye(e){let t=ue(e);return t===null?null:Gm(t)}i(ye,"parseColor");function ue(e){if(typeof e=="number")return Oa(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return co(t.slice(1));if(t.toLowerCase().startsWith("0x"))return co(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Wm(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=co(t);if(r!==null)return r}return /^\d+$/.test(t)?Oa(Number.parseInt(t,10)):null}i(ue,"toRgba");function co(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:po(t[0]),g:po(t[1]),b:po(t[2]),a:1};if(t.length===6)return {r:ot(t,0),g:ot(t,2),b:ot(t,4),a:1};if(t.length===8){let r=ot(t,0);return {r:ot(t,2),g:ot(t,4),b:ot(t,6),a:r/255}}return null}i(co,"fromHex");function Wm(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=fo(Number(n[0])),s=fo(Number(n[1])),a=fo(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(Wm,"fromRgbFunc");function Oa(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(Oa,"argbIntToRgba");function ot(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ot,"byte");function po(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(po,"dup");function fo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(fo,"clampByte");function Gm(e){if(e.a>=1)return st(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Gm,"normalizeRgba");function st(e,t,r){return `#${mo(e)}${mo(t)}${mo(r)}`.toUpperCase()}i(st,"rgbToHex");function mo(e){return e.toString(16).padStart(2,"0")}i(mo,"hex2");var Km="#111111",Ot="#FFFFFF",Kr="#000000";function Ma(e){let t=ue(e);if(t===null)return Ot;let r=it(t),n=it({r:17,g:17,b:17}),o=it({r:255,g:255,b:255});return ho(r,o)>=ho(r,n)?Ot:Km}i(Ma,"readableOn");function sr(e,t){let r=Ma(e);return de(r,e)>=t?r:de(Ot,e)>=de(Kr,e)?Ot:Kr}i(sr,"legibleOn");function ar(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,de(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ot)>=t(Kr)?Ot:Kr}i(ar,"poleForGrounds");function it(e){let t=yo(e.r/255),r=yo(e.g/255),n=yo(e.b/255);return .2126*t+.7152*r+.0722*n}i(it,"relativeLuminance");function yo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(yo,"linearize");function ho(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(ho,"luminanceContrast");function de(e,t){let r=ue(e),n=ue(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:La(r,o);return ho(it(s),it(o))}i(de,"contrastRatio");function La(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(La,"composite");function at(e,t){let r=ue(e),n=ue(t);if(r===null||n===null)return null;let o=r.a>=1?r:La(r,{...n});return st(o.r,o.g,o.b)}i(at,"flattenOnto");var Fa=.05;function lt(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>de(d,c)>=n),"reads");if(ue(e)===null)return r;if(s(e))return e;let a=at(e,o),l=a===null?null:ue(a),u=ue(r);if(l===null||u===null)return r;for(let d=1;d<1/Fa;d+=1){let c=d*Fa,p=i((m,g)=>Math.round(m+(g-m)*c),"mix"),f=st(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(lt,"pushToContrast");function Da(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(Da,"rgbToHsl");function bo(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:go(c+l),g:go(p+l),b:go(f+l)}}i(bo,"hslToRgb");function go(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(go,"channel");function Be(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))Be(e[t]);}return e}i(Be,"deepFreeze");var $r=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ua={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Va={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Na={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},qm={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},$m={regular:"400",medium:"500",bold:"700"},Ym={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},vo=0,ut="System",Me="monospace",Xm=["content","heading","control","compact","badge"];function Qm(e){let t={};for(let r of Xm)t[r]=e;return t}i(Qm,"authoredTierSizes");function Ba(){return {family:ut,mono:Me,fontUrl:null,families:{regular:ut,medium:ut,bold:ut,mono:Me,monoMedium:Me,monoBold:Me},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Na,tierSizes:Qm(Na),lineHeight:qm,weight:$m,letterSpacing:Ym,scale:1,maxScale:vo,scaleCaps:$r}}i(Ba,"baseType");var Ha={},dt=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 za={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:qr(dt.standard),emphasized:qr(dt.emphasized),exit:qr(dt.exit)},reducedMotion:false},Zm={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)"},ct=Be({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Zm,space:Ua,radius:Va,type:Ba(),motion:za,slots:Ha}),Jm={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)"},Yr=Be({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Jm,space:Ua,radius:Va,type:Ba(),motion:za,slots:Ha});var ey="#23272C",ja=4.5,ty=.6,Co=.9,ry=.02,ny="#FFFFFF",oy="#111111";function iy(e){return de(e,ey)>=ja&&Math.max(de(e,ny),de(e,oy))>=ja}i(iy,"readsOnDark");function Ka(e){let t=ue(e);if(t===null)return null;let{h:r,s:n,l:o}=Da(t.r,t.g,t.b),s=Math.min(Math.max(o,ty),Co);for(let l=0;;l+=1){let u=s+l*ry;if(u>Co)break;let d=bo({h:r,s:n,l:u}),c=st(d.r,d.g,d.b);if(iy(c))return c}let a=bo({h:r,s:n,l:Co});return st(a.r,a.g,a.b)}i(Ka,"deriveDarkVariant");var sy=7,Wa=.05,ay="#000000",ly="#FFFFFF";function uy(e,t,r,n){let o=at(e,t);if(o===null)return r;if(de(o,t)>=n)return o;let s=ue(o),a=ue(r);if(s===null||a===null)return r;for(let l=1;l<1/Wa;l+=1){let u=l*Wa,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=st(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(de(c,t)>=n)return c}return r}i(uy,"pushContrast");function dy(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=Ga(n);for(let s of r){let a=Ga(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(dy,"hardestGround");function Ga(e){let t=ue(e);return t===null?0:it(t)}i(Ga,"luminanceOf");function $e(e,t){return at(e,t)??ye(e)??t}i($e,"solid");function qa(e){let t=e.color,r=e.brightness==="dark",n=r?ly:ay,o=dy(t,r),s=i(l=>uy(l,o,n,sy),"text"),a={...t,brandSoft:$e(t.brandSoft,t.surface),brandSofter:$e(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:$e(t.badgeBgPositive,t.surface),badgeBgCaution:$e(t.badgeBgCaution,t.surface),badgeBgCritical:$e(t.badgeBgCritical,t.surface),badgeBgNeutral:$e(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:$e(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:$e(t.checkupCardConcernBg,t.surface)};return Be({...e,highContrast:true,color:a})}i(qa,"deriveHighContrast");var pt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),cy=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Pe=4.5,py=Object.freeze({});function fy(e){return pt.includes(e)}i(fy,"isSlotName");function my(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(my,"parseRadius");function $a(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(!fy(n)||o===null||typeof o!="object")continue;let s=yy(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i($a,"parseThemeSlots");function Xr(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Xr,"pick");function yy(e){let t={},r=ye(Xr(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(Xr(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=my(Xr(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ye(Xr(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(yy,"parseSlot");function Ya(e,t){return t===null||Object.keys(t).length===0?e??py:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(Ya,"mergeThemeSlots");var gy=3;function hy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>at(e,r)??r)}i(hy,"seatsOf");function by(e,t){let r=ar(e);return e.every(n=>de(r,n)>=t)}i(by,"someInkReads");function vy(e,t){let r=t[0];return r===void 0?null:at(e,r)}i(vy,"collapseUnsatisfiableFill");function Cy(e){let t=sr(e[0],Pe);return e.every(r=>de(t,r)>=Pe)?t:ar(e)}i(Cy,"inkFor");function Xa(e,t){let r=false,n={};for(let o of pt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=hy(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!by(u,Pe)){let p=vy(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=>de(p,f)<Pe))&&(d.textColor=Cy(u),c=true);else if(p!==void 0){let f=lt(p,u,ar(u),Pe);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=lt(s.borderColor,u,ar(u),gy);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(Xa,"guardSlotContrast");var Ja=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"]),lr="slots.",el=Object.freeze([1,2]);function Qr(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(Qr,"isEmptyBranding");function tl(e){let t=e?.schemaVersion??null;return t===null||el.includes(t)}i(tl,"isKnownBrandingSchema");function rl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(rl,"lockedFieldsOf");function Ey(e){return e==="hide_powered_by"||Ja.includes(e)?true:e.startsWith(lr)&&pt.includes(e.slice(lr.length))}i(Ey,"isThemeLockName");function He(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:ft(q(t,"display_name","displayName")),logoUrl:ft(q(t,"logo_url","logoUrl")),primaryColor:ye(q(t,"primary_color","primaryColor")),accentColor:ye(q(t,"accent_color","accentColor")),brightness:Ty(q(t,"brightness","color_scheme","colorScheme")),fontFamily:ft(q(t,"font_family","fontFamily")),fontUrl:ft(q(t,"font_url","fontUrl")),fonts:Qa(q(t,"fonts")),fontUrls:Qa(q(t,"font_urls","fontUrls")),placeholder:ft(q(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ry(q(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye(q(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye(q(t,"accent_color_dark","accentColorDark")),surfaceStyle:Za(q(t,"surface_style","surfaceStyle"),Sy),radiusScale:Za(q(t,"radius_scale","radiusScale"),Py),logoUrlDark:ft(q(t,"logo_url_dark","logoUrlDark")),slots:$a(q(t,"slots")),accessibilityMaxFontScale:xy(q(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:wy(q(t,"locked_fields","lockedFields")),schemaVersion:_y(q(t,"schema_version","schemaVersion"))};return Qr(r)?null:Object.freeze(r)}i(He,"parseClientBranding");function Ry(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(Ry,"parseBool");function q(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(q,"pick");function ft(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(ft,"parseNonEmptyString");var ur=["regular","medium","bold","mono","monoMedium","monoBold"];function Qa(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of ur){let o=ft(q(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Qa,"parseFaceMap");var Sy=["white","cream","subtle"],Py=["sharp","default","round"];function Za(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(Za,"parseEnum");function Ty(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ty,"parseBrightness");function nl(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(nl,"parseNumber");var ky=1,ol=3.1;function xy(e){let t=nl(e);return t===null?null:t<=0?0:Math.min(ol,Math.max(ky,t))}i(xy,"parseMaxFontScale");function _y(e){if(e==null)return null;let t=nl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(_y,"parseSchemaVersion");function Eo(e){let t=e.trim();return t.startsWith(lr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Eo,"toWireName");function wy(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Eo(r);Ey(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(wy,"parseLockedFields");function Ro(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Ro,"hardenHttpsUrl");function il(e,t){if(t===null||Qr(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Yr:ct:e,n=r.brightness==="dark"?Yr:ct,o=r.brightness==="dark",s=o?t.primaryColorDark??sl(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??sl(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&My(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ue(c):null,f=i(x=>Math.round(x+(255-x)*.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?Ly(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,...Fy(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:Ny(t.radiusScale??null,r.radius,n),type:{...r.type,...Oy(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:Ya(r.slots,t.slots??null)};return Be(g)}i(il,"withServerBranding");var Iy={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Ay=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function So(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(So,"isMonoFace");function Oy(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of ur){let u=Iy[l].map(p=>r[p]).find(p=>p!==void 0),d=So(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 Ay)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(Oy,"mergeFaces");function sl(e){return e===null?null:Ka(e)}i(sl,"darkVariantOf");function Fy(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(Fy,"surfaceOf");function al(e,t){return e==null?false:ye(e)===ye(t)}i(al,"sameColor");function My(e,t,r,n){return al(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&al(e.primaryColor,ct.color.primary)}i(My,"isCompiledPrimary");function Ly(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(Ly,"compiledBrandFamily");var Dy={sharp:.5,default:1,round:1.5};function Ny(e,t,r){if(e===null)return t;let n=Dy[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(Ny,"radiusOf");var Uy="Everfur",Vy=.5;function Po(e){let t=e?.branding??null,r=tl(t)?t:null,n=Wy(e?.clientOverride??null,rl(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=il((s==="auto"?o:s)==="dark"?Yr:ct,ll(r)),d=il(u,ll(n));return tg(d,e)}i(Po,"resolveTheme");function By(e,t,r){return Po({...r,branding:He(t),clientOverride:He(e)})}i(By,"previewTheme");function Hy(e){return e==="placeholder"?"chat_placeholder":Eo(e)}i(Hy,"wireNameOf");var zy={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function jy(e,t){return t.has(Hy(e))?true:(zy[e]??[]).some(r=>t.has(r))}i(jy,"isLocked");function Wy(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(jy(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 pt){let d=o[u];d!==void 0&&(t.has(`${lr}${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 Qr(s)?null:s}i(Wy,"withoutFields");function ll(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(ll,"withoutBrightness");function Gy(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(Gy,"scaledSizes");function Ky(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Vy,e)}i(Ky,"effectiveScale");var ul=["content","heading","control","compact","badge"];function qy(e){if(!(e>0))return $r;let t={};for(let r of ul){let n=$r[r];t[r]=n===0?0:Math.min(n,e);}return t}i(qy,"tierCaps");function $y(e,t){return t>0?Math.min(e,t):e}i($y,"capped");function Yy(e,t,r,n){let o={};for(let s of ul)o[s]=n?Gy(e,$y(t,r[s])):e;return o}i(Yy,"sizesByTier");function Xy(e){return e==="dark"?"#FFFFFF":"#000000"}i(Xy,"inkPole");function Qy(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Qy,"textGrounds");function dl(e){return [e.chatGround,e.surface,e.surfaceCream]}i(dl,"linkGrounds");function Zy(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:dl(e)}}i(Zy,"slotGrounds");function Jy(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Jy,"registration");function eg(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 ur)!(o[a]===ut||o[a]===Me)&&r!==void 0&&Jy(r,o[a])===false&&(o[a]=So(a)?Me:ut,s[a]=false),n!==null&&So(a)&&o[a]===Me&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(eg,"platformFaces");function tg(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?Uy:e.meta.displayName,s=Ro(e.meta.logoUrl),a={};for(let A of ur){let k=e.type.fontUrls[A];k!==void 0&&(a[A]=Ro(k));}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:vo,p=Ky(t?.textScale),f=qy(c),m=Yy(e.type.size,p,f,t?.scaleTypeSizes===true),g=e.color,x=Xy(e.brightness),y=Qy(g),S={...g,primary:r,accent:n,onPrimary:sr(r,Pe),onAccent:sr(n,Pe),brandInk:lt(g.brandInk,y,x,Pe),linkInk:lt(e.slots.link?.textColor??n,dl(g),x,Pe),text:{...g.text,secondary:lt(g.text.secondary,y,x,Pe)}},_={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:S,space:e.space,radius:e.radius,type:{...e.type,...eg(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:Xa(e.slots,Zy(S))};return t?.highContrast===true?qa(Be(_)):Be(_)}i(tg,"finalize");var cl="/widget/v1/entitlements",rg=304,ng=Object.freeze({kind:"notModified"});async function fl(e,t={},r=Re({auth:e})){let n=await r.send("entitlements.fetch",ig(t));return n.ok?sg(n.value):n.error.httpStatus===rg?ng:{kind:"failed",error:n.error}}i(fl,"fetchEntitlements");var og=64;function ig(e){let t={};return To(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=og?{method:"GET",path:cl,headers:t,query:{region:e.region}}:{method:"GET",path:cl,headers:t}}i(ig,"buildRequest");function sg(e){if(e===null||typeof e!="object"||!To(e.revision))return pl();let t=typeof e.region=="string"?e.region:"",r=To(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:lg(e.capabilities),branding:ag(e)})}i(sg,"parseUpdated");function ag(e){let t=He(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=He(r.branding);return n!==null?n:He(r)}return null}i(ag,"parseBranding");function lg(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))ug(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(lg,"mapCapabilities");function ug(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(ug,"isEnabled");function pl(){return {kind:"failed",error:L("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(pl,"malformed");function To(e){return typeof e=="number"&&Number.isFinite(e)}i(To,"isFiniteNumber");var dg=30;function ml(e){let t=e.scheduler??cg,r=e.resolve??fl,n=Math.max(1,e.floorSeconds??dg),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(S=>{l||!a||(c=Math.max(n,S),u=t.set(()=>{u=null,y();},c*1e3));},"schedule"),g=null,x=i(async()=>{if(l)return null;let S=p;e.onFetch?.();let _=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},A;try{A=await r(e.authFor(),_);}catch(k){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:pg(k)}),!l&&S===p&&(e.onSettled?.(),m(s())),null}if(l||S!==p)return null;switch(A.kind){case "updated":d=A.revision,e.update(A.decisions,A.branding??null),m(A.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:A.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),A},"tick"),y=i(()=>{let S=x().finally(()=>{g===S&&(g=null);});return g=S,S},"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(ml,"createEntitlementPoller");var cg={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function pg(e){return e instanceof Error?e.message:"poll failed"}i(pg,"describe");var yl="everfur.notifications.device";var fg=3e3,gl=Object.freeze([yl]);function hl(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();},fg);u.then(p,p);})}i(hl,"startBeforeLogoutHooks");function bl(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(bl,"graceAuth");async function vl(e,t){if(gl.length===0)return;let r=await Promise.allSettled(gl.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 mg(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(mg,"compiledDefaultDecisions");function ko(e=mg){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(ko,"createEntitlementStore");function xo(e){return L("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(xo,"notConfiguredError");function Cl(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 cs(r,t===void 0?void 0:{platform:t})}i(Cl,"tryResolveClient");function El(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(El,"guardTelemetry");function Rl(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(Rl,"reportConfigFailure");function _o(e){return Object.freeze({request(){return Promise.resolve(v(xo(e)))},stream(t,r){let n=ce({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(_o,"refusingTransport");function Sl(){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(Sl,"createInMemoryKv");var Pl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function xl(e,t){return new Io(e,t)}i(xl,"createEverfurRuntime");var yg=6e4,Ao=class Ao{constructor(t,r){this.sessionId=Nn();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 Z("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?El(n.telemetry):Fr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Vn(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=_o(s);else if(n.transport!==void 0)l=n.transport;else {let c=Cl(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=hs({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=_o(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Rl(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Xi,this.upload=n.upload??Ls,this.uploadTransport=n.uploadTransport??ro,this.imageCache=n.imageCache??Pl,this.kv=n.storage??Sl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?ko():ko(()=>Ia("sdk_config",wt("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",wo(c),()=>this.buildChatController(c),Tl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${wo(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=os(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-yg,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=Js({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=ra(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=Nn(),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 hl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>bl({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:xo(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(L("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(L("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",wo(r),()=>this.buildChatController(r),Tl,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(Ao,"EverfurRuntimeImpl");var Io=Ao;function wo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(wo,"chatScopeKey");function Tl(e){e.dispose();}i(Tl,"disposeChat");function kl(e){return L("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"),wl=globalThis,Zr=wl[_l]??(wl[_l]=createContext(null));Zr.displayName??="EverfurContext";function Y(){let e=useContext(Zr);if(e===null)throw new Z("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Y,"useEverfurContext");function Il(){return Y().handle}i(Il,"useEverfur");var Al=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Ol=globalThis,dr=Ol[Al]??(Ol[Al]=createContext(ct));dr.displayName??="EverfurThemeContext";function F(){return useContext(dr)}i(F,"useEverfurTheme");function Jr(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?Rg(e.clientTheme):"",f=useMemo(()=>e.clientTheme?He(e.clientTheme):null,[p]),m=n.branding??null,g=useMemo(()=>Po({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(dr.Provider,{value:g},e.children)}i(Jr,"EverfurThemeProviderCore");function Rg(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(Rg,"stableKey");function Nl(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),g=useRef(void 0),x=r?.userRef??null;g.current!==x&&(g.current!==void 0&&(m.current=null),g.current=x);let y=m.current!==null?m.current.user:r??null,S=useRef(null),_=useRef(void 0),A=n??null;_.current!==A&&(_.current!==void 0&&(S.current=null),_.current=A);let k=S.current!==null?S.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:xl({config:l.withDefaults?l.withDefaults(t):t,user:y,activePet:k,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,R=useRef(null);useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||R.current!==T&&(R.current=T,f());}),useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let P=y?.userRef??null;useLayoutEffect(()=>{b.setUser(y);},[b,P]),useLayoutEffect(()=>{b.setActivePet(k);},[b,k]),useEffect(()=>()=>b.dispose(),[b]),useEffect(()=>{s==="onMount"&&b.prepare(k===null?{}:{petRef:k});},[b,s,P,k]);let V=useMemo(()=>({setUser:i(T=>{m.current={user:T},b.setUser(T),f();},"setUser"),setActivePet:i(T=>{S.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,B)=>b.registerPet(T,B),"registerPet"),updatePet:i((T,B)=>b.updatePet(T,B),"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]),I=useMemo(()=>({runtime:b,handle:V,userRef:P,activePet:k,scopeEpoch:b.scopeEpoch}),[b,V,P,k,p]),w=createElement(Jr,{clientTheme:o??null,seams:l.theme,children:a});return createElement(Zr.Provider,{value:I},l.wrap?l.wrap(w):w)}i(Nl,"EverfurProviderCore");var Tg=2;function kg(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Tg)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(kg,"readEventSourceResponseHeader");function Ul(){let e=Pg;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=>kg(n,o),"getResponseHeader")})}}i(Ul,"createRnEventSourceFactory");function Ig(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(Ig,"useRnColorScheme");function Ag(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Ag,"isThenable");function Og(){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(Og,"useRnReducedMotion");function Hl(){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(Hl,"readFontScale");function Fg(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(Fg,"subscribeFontScale");function Mg(){return useSyncExternalStore(Fg,Hl,Hl)}i(Mg,"useRnTextScale");function Gl(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(Gl,"platformOS");function Lg(){return Gl()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(Lg,"contrastSignal");function Dg(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=Lg(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);Ag(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(Dg,"useRnHighContrast");function Ng(){return Gl()==="ios"?"Menlo":Me}i(Ng,"rnPlatformMonoFamily");function Ug(){return globalThis.__DEV__!==false}i(Ug,"isDevelopment");var zl=new Set;function Vg(e){if(!Ug()||zl.has(e))return;zl.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(Vg,"warnUnregisteredFace");function Bg(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||Vg(e),o}i(Bg,"rnIsFontRegistered");var tn=Object.freeze({useColorScheme:Ig,useReducedMotion:Og,useTextScale:Mg,useHighContrast:Dg,scaleTypeSizes:false,platformMonoFamily:Ng,isFontRegistered:Bg});function zg(e){return createElement(SafeAreaProvider,null,e)}i(zg,"wrapInSafeArea");var jg=Object.freeze({platform:"react-native",eventSourceFactory:Ul(),wrap:zg,theme:tn});function Wg(e){return createElement(Nl,{...e,seams:jg})}i(Wg,"EverfurProvider");function Ft(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Aa(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Ft,"useCapability");function Xg(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Xg,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=F(),n=Xg(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Mt=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Qg=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[Qg[t]]}}i(E,"face");var Fo=class Fo 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(Fo,"HostRenderBoundary");var Oo=Fo;function Jg({render:e}){return e()}i(Jg,"RenderHost");function gt({render:e,fallback:t,resetKey:r}){return createElement(Oo,{fallback:t,resetKey:r,children:createElement(Jg,{render:e})})}i(gt,"HostRender");var eh=48;function th(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(th,"selectView");function Do(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Ft(t),l=useMemo(()=>th(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(gt,{render:o,fallback:jsx(Xl,{capability:t,style:s})}):jsx(Xl,{capability:t,style:s});case "disabled":return n?jsx(gt,{render:()=>n(a),fallback:jsx(Ql,{decision:a,style:s}),resetKey:a}):jsx(Ql,{decision:a,style:s});default:return Ke(l)}}i(Do,"CapabilityGate");function Xl({capability:e,style:t}){let r=F(),n=useMemo(()=>Zl(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(Xl,"PendingSkeleton");function Ql({decision:e,style:t}){let r=F(),n=useMemo(()=>Zl(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(Ql,"OffState");function Zl(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:eh,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(Zl,"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 $(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i($,"fillCopy");var No=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"})]),Jl=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function rh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(rh,"sentimentToFeedbackType");function eu(e,t){if(e==="down"&&t!==null){let r=No.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return rh(e)}i(eu,"feedbackTypeFor");var sh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function cr(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 I=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=I,d({scope:l,controller:I}),()=>{p.current=null,d(w=>w?.controller===I?null:w),t.registry.releaseChat(I);}},[t,r,s,a,o,l]);let f=useCallback(I=>c?c.subscribe(I):ah,[c]),m=useCallback(()=>c?c.getSnapshot():sh,[c]),g=useSyncExternalStore(f,m,m),x=useCallback((I,w)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Vo(c,c.send(I,w?.imageS3Keys===void 0?{}:{imageS3Keys:w.imageS3Keys}),()=>p.current===c):Promise.resolve(Bo()),[c]),y=useCallback(I=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Vo(c,c.askEverfur(I),()=>p.current===c):Promise.resolve(Bo()),[c]),S=useCallback(()=>c&&p.current===c?Vo(c,c.retryLast(),()=>p.current===c):Promise.resolve(Bo()),[c]),_=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),A=useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[k,b]=useState({controller:null,byMessage:{}}),R=k.controller===c?k.byMessage:lh,P=useCallback(async(I,w,T,B)=>{if(!c||p.current!==c)return v(L("accessDenied"));let K=String(I),W=k.controller===c?k.byMessage[K]:void 0;if(W===w&&T==null)return b(me=>{let G={...me.controller===c?me.byMessage:{}};return delete G[K],{controller:c,byMessage:G}}),M(Object.freeze({feedbackId:""}));b(me=>({controller:c,byMessage:{...me.controller===c?me.byMessage:{},[K]:w}}));let ae=await c.submitFeedback(I,eu(w,T??null),B??null);return p.current!==c?v(L("accessDenied")):(ae.ok||b(me=>{let G={...me.controller===c?me.byMessage:{}};return W===void 0?delete G[K]:G[K]=W,{controller:c,byMessage:G}}),ae)},[c,k]),V=useMemo(()=>{let I=i(async w=>{if(!c||p.current!==c)return v(L("accessDenied"));let T=await w(c);return p.current===c?T:v(L("accessDenied"))},"run");return {listConversations:i(w=>I(T=>T.listConversations({...s?{petRef:s}:{},...w})),"listConversations"),getMessages:i((w,T)=>I(B=>B.getMessages(w,T)),"getMessages"),resumeConversation:i(w=>I(T=>T.resumeConversation(w)),"resumeConversation"),loadOlderMessages:i(()=>I(w=>w.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>I(w=>w.markRead()),"markRead"),refreshActiveThread:i(()=>I(w=>w.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((w,T)=>I(B=>B.answerCheckin(w,T)),"answerCheckin"),openCheckin:i(w=>I(T=>T.openCheckin(w)),"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:A,sentimentByMessage:R,feedback:P,send:x,askEverfur:y,retryLast:S,stop:_}),[g,s,x,y,S,_,V,A,R,P])}i(cr,"useEverfurChat");var ah=i(()=>{},"NOOP_UNSUBSCRIBE"),lh=Object.freeze({});async function Vo(e,t,r){for await(let o of t);if(!r())return v(L("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):M(uh(n.messages))}i(Vo,"driveToResult");function uh(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(uh,"lastAssistantResponseId");function Bo(){return v(L("internalError",{retryable:true}))}i(Bo,"notReadyError");function nu(e){switch(e.code){case "too_large":return $(h.attachmentTooLarge,{max:oo(Br),filename:e.filename,size:oo(e.sizeBytes??0)});case "too_many":return $(h.attachmentTooMany,{max:Hr});case "unsupported_type":return $(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return $(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(nu,"attachmentErrorMessage");function ou(e,t){return $(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(ou,"attachControlLabel");var fh=Object.freeze({attachments:Object.freeze([])});function rn(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??Hr,s=useMemo(()=>{if(e.queue)return e.queue;let{services:y}=t.registry;return ia({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,()=>fh),[l,u]=useState(null),d=useCallback(y=>{let _=(Array.isArray(y)?y:[y]).map(k=>s.add(k)),A=_.find(k=>!k.ok);return A!==void 0&&!A.ok&&u(A.error),_},[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"),x=a.attachments.some(y=>y.status==="failed");return useMemo(()=>({available:s.available,attachments:a.attachments,maxPerMessage:o,uploading:g,failed:x,blocked:g||x,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,x,l,d,c,p,f,m])}i(rn,"useChatAttachments");var gh="pet_not_registered";function au(e){return e!=null&&e.reasonCode===gh}i(au,"isPetNotRegistered");var hh=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function lu(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:zo(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 x=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(y=>{x===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?hh: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(lu,"useChatPetRegistration");function zo(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(zo).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)}:${zo(n)}`).join(",")}}`}i(zo,"stableKey");var jo=Object.freeze({});function du(e){let[t,r]=useState(jo),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===jo?u:jo);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(du,"useSentImages");var Sh=500;function Wo(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(Wo,"sanitizeSeedPrompt");function pu(e,t,r){let n=Wo(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(pu,"useInitialAsk");function Ph(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(Ph,"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"}:Ph(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(fu,"decideChatRefresh");function Go(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Go,"reportHostFailure");function Th(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Th,"isThenable");function X(e,...t){if(typeof e=="function")try{let r=e(...t);return Th(r)&&Promise.resolve(r).then(void 0,Go),r}catch(r){Go(r);return}}i(X,"callHost");var mu=new WeakMap;function yu(e){if(typeof e!="function")return;let t=mu.get(e);if(t!==void 0)return t;let r=i((...n)=>{X(e,...n);},"guarded");return mu.set(e,r),r}i(yu,"guardHost");function Lt(e,...t){let r;try{r=e(...t);}catch(n){return Go(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Lt,"callHostAsync");function hu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:X(()=>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=X(()=>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)X(d);}},[e]);}i(hu,"useChatLifecycle");function xh(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(xh,"targetKey");function vu(e,t){let r=xh(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 Ru(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(Ru,"useChatDraft");function Su(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 Lt(()=>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??""}`||X(()=>e.write(t,r));},[e,t,r,a]);}i(Su,"usePersistedDraft");var J=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 on(e){let t=e?.replace(/\s+/g," ").trim();return t||J.untitled}i(on,"conversationTitle");function Tu(e){return `${e.unreadCount!==null&&e.unreadCount>0?J.unreadPrefix:""}${J.openConversation} ${on(e.title)}`}i(Tu,"openConversationLabel");function Pu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Pu,"normalizeForSearch");function Fh(e,t){let r=Pu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Pu(on(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(Fh,"filterConversations");function $o(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i($o,"fresh");function ku(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>$o(s)),d=l.scope===s?l:$o(s);useEffect(()=>(a.current+=1,r(false),o(""),u($o(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async A=>{let k=++a.current,b=A!==void 0;u(P=>({...P,scope:s,loading:!b,loadingMore:b,error:null}));let R=await e.listConversations(A?{cursor:A}:void 0);if(k===a.current){if(!R.ok){u(P=>({...P,loading:false,loadingMore:false,error:R.error.displayMessage}));return}u(P=>{let V=A&&P.scope===s?P.rows:[],I=new Set(V.map(w=>w.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...V,...R.value.conversations.filter(w=>!I.has(w.id))],cursor:R.value.nextCursor===A?null:R.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async A=>{let k=++a.current;u(R=>({...R,loading:true,error:null}));let b=await e.resumeConversation(A);k===a.current&&(u(R=>({...R,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),g=i(async()=>{let A=a.current,k=await e.loadOlderMessages();A===a.current&&!k.ok&&u(b=>({...b,error:k.error.displayMessage}));},"earlier"),x=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"),S=useMemo(()=>Fh(d.rows,n),[d.rows,n]),_=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:g,newConversation:x,loadMore:y,query:n,setQuery:o,searching:_,filtered:S,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(ku,"useHistoryPanel");var sn="#111111",an="#FFFFFF",Dh=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:sn,pillColor:an,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:sn,pillColor:an,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:sn,pillColor:an,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:sn,pillColor:an,showsVetAction:false})});function Nh(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Nh,"urgencySignature");function Uh(e){return $(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Uh,"generalUrgencyReason");function wu(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:Uh(t)}:null}return null}i(wu,"latestUrgencySource");function Iu(e){let t=e===null?null:Nh(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:Dh[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:$(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Iu,"useUrgencySurface");function Au(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Au,"selectView");function Vh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Vh,"needsNewConversation");function Ou(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Vh(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(Ou,"turnNotice");function Fu(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Fu,"awaitingAssistant");function Mu(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(Mu,"buildChatOpts");var fr=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 Nu(e){let t=F(),r=useMemo(()=>zh(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${fr.title}. ${fr.body}`,children:[jsx(C,{style:r.title,children:fr.title}),jsx(C,{style:r.body,children:fr.body})]})}i(Nu,"ClinicalDisclaimer");function zh(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(zh,"makeStyles");var ie={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function re(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(re,"box");function pe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(pe,"stroke");function Uu({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:[re(e),{gap:e*.22}],...ie,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(Uu,"MenuGlyph");function Vu({size:e,color:t,strokeWidth:r,rotate:n}){let o=pe(e,r),s=e*.78;return jsxs(View,{style:[re(e),{transform:[{rotate:n}]}],...ie,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(Vu,"Cross");function Bu(e){return jsx(Vu,{...e,rotate:"0deg"})}i(Bu,"PlusGlyph");function ht(e){return jsx(Vu,{...e,rotate:"45deg"})}i(ht,"CloseGlyph");function Xe({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsx(View,{style:re(e),...ie,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(Xe,"CheckGlyph");function Hu({size:e,color:t,strokeWidth:r,direction:n}){let o=pe(e,r),s=e*.46;return jsx(View,{style:re(e),...ie,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(Hu,"ChevronGlyph");function zu({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:[re(e),{flexDirection:"row",gap:1}],...ie,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(zu,"BookGlyph");function ju({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.5;return jsxs(View,{style:re(e),...ie,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(ju,"ArrowUpRightGlyph");function Wu({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:re(e),...ie,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(Wu,"CopyGlyph");function ln({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=pe(e,r),a=n?t:"transparent";return jsxs(View,{style:[re(e),{transform:[{rotate:o}]}],...ie,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(ln,"ThumbGlyph");function Gu({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:[re(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...ie,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(Gu,"InfoGlyph");function Ku({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.34;return jsxs(View,{style:re(e),...ie,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(Ku,"UploadGlyph");function qu({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:[re(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...ie,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(qu,"PhotoGlyph");function $u({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:re(e),...ie,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($u,"CameraGlyph");function Yu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.66;return jsxs(View,{style:re(e),...ie,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(Yu,"SearchGlyph");function Xu({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxs(View,{style:re(e),...ie,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(Xu,"EditGlyph");function Qu({size:e,color:t,strokeWidth:r}){let n=pe(e,r),o=e*.62;return jsxs(View,{style:re(e),...ie,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(Qu,"MapPinGlyph");function Zu({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:re(e),testID:r,...ie,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(Zu,"SendGlyph");function Ju({size:e,color:t,testID:r}){return jsx(View,{style:re(e),testID:r,...ie,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(Ju,"StopGlyph");function un({size:e,strokeWidth:t,color:r,children:n}){return jsx(View,{style:[re(e),{borderRadius:e/2,borderWidth:t??StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(un,"Ring");var mr=Object.freeze({standard:dt.standard,emphasized:dt.emphasized,exit:dt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var ed=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}),Gh=Object.freeze({...ed,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 td(e){return e.motion.reducedMotion?Gh:ed}i(td,"chatMotion");function dn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(dn,"followUpDelayMs");function rd(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(rd,"nextRevealLength");function Q(){let e=F();return td(e)}i(Q,"useChatMotion");var Qh=8;function od(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(od,"bezierComponent");function Zh(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Zh,"bezierSlope");function cn(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<Qh;l+=1){let u=Zh(a,t,n);if(u===0)break;a-=(od(a,t,n)-s)/u;}return od(Math.min(1,Math.max(0,a)),r,o)}}i(cn,"bezierEasing");var Yo=cn(mr.standard),Jh=cn(mr.outQuad);function Jo(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(Jo,"useAnimatedValue");function bt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=Jo(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:Jh,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(bt,"useFadeIn");function ei({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=Jo(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:Yo,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:Yo,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(ei,"FadePresence");function H({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,...s}){let a=Q(),l=Jo(1),u=useCallback(d=>{a.pressMs<=0||a.pressScale===1||Animated.timing(l,{toValue:d,duration:a.pressMs,easing:Yo,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 ad(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=>rd(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(ad,"useRevealedText");var id=false;function eb(e){e.layoutMs<=0||(id||(id=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(eb,"animateLayout");function yr(e,t){let r=useRef(e);r.current!==e&&(r.current=e,eb(t));}i(yr,"useAnimateLayoutOn");var ti=36,ab=22,lb=12,ub=12,db=16,cb="#000",pb="rgba(0,0,0,0.45)";function ld({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:pn.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:pn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[pn.closeWrap,{top:o.top+ub}],children:jsx(H,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:lb,style:pn.closeButton,onPress:r,children:jsx(ht,{size:ab,color:n.color.surface,strokeWidth:2})})})]})}i(ld,"AttachmentImageLightbox");var pn=StyleSheet.create({backdrop:{flex:1,backgroundColor:cb,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:db},closeButton:{width:ti,height:ti,borderRadius:ti/2,backgroundColor:pb,alignItems:"center",justifyContent:"center"}});var fn=12,hb=80,ri=44,ud=22,bb=.14,vb=18,Cb=8,dd=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function cd({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>Eb(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:dd[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(qu,{size:ud,color:o.color.brandInk,strokeWidth:1.5}):jsx($u,{size:ud,color:o.color.brandInk,strokeWidth:1.5})}),jsx(C,{tier:"control",style:s.tileLabel,children:dd[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(cd,"AttachmentPickerPopover");function Eb(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:bb,shadowRadius:vb,shadowOffset:{width:0,height:Cb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:hb,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:ri,height:ri,borderRadius:ri/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:-fn/2,width:fn,height:fn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:fn+4,height:2,backgroundColor:t.surfaceCream}})}i(Eb,"makeStyles");var pd=56,fd=12,Pb=14,Tb=10,kb="rgba(16,70,46,0.45)",xb="rgba(7,193,104,0.55)",_b="rgba(185,28,28,0.55)",wb=200,Ib=300,Ed=20,oi=22,Ab=12,Ob="rgba(0,0,0,0.78)",md=220,yd=100,gd="rgba(255,255,255,0.15)";function Rd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=useMemo(()=>Pd(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(Fb,{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:nu(t)}):null]})}i(Rd,"AttachmentStrip");function Fb({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?$(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(Mb,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:$(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(ht,{size:Ed,color:s.color.surface,strokeWidth:2})})}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:$(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(ht,{size:Ab,color:s.color.surface,strokeWidth:1.5})})]})}i(Fb,"PreviewCard");function Mb({styles:e,onDone:t}){let r=F(),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:wb,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:Ib,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(Xe,{size:Ed,color:r.color.surface,strokeWidth:2})})}i(Mb,"SuccessFlash");function Sd({images:e,onPreview:t}){let r=F(),n=useMemo(()=>Pd(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:$(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(Sd,"SentImages");function Pd(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:pd,height:pd,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:fd,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:kb},successOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:xb},failedOverlay:{...StyleSheet.absoluteFillObject,borderRadius:fd,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:_b},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:oi,height:oi,borderRadius:oi/2,backgroundColor:Ob,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:md,height:md,borderRadius:Pb,backgroundColor:gd},gridImage:{width:yd,height:yd,borderRadius:Tb,backgroundColor:gd}})}i(Pd,"makeStyles");var Lb="file",Db="chat attachment upload: the file handle has no uri",Nb="chat attachment upload failed";function Ub(e){return {uri:e.uri,name:no(e.name),type:e.mimeType}}i(Ub,"filePartOf");function Td(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Db));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Nb)),"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(Lb,Ub(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(Td,"createRnChatAttachmentTransport");function mn(){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(mn,"useEverfurPets");function kd(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(kd,"headerPetOf");function fe(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(fe,"slotBox");function li(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(li,"ownGroundSlot");function Te(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Te,"slotText");var xd=Object.freeze({visitButton:"Talk to a vet"});var _d=null;function wd(){return _d!==null}i(wd,"hasEverfurTelevetFlow");function Id(e){return false;}i(Id,"presentEverfurTelevetFlow");var ui=Object.freeze(["visit","join","summary","messages"]);function di(e){return typeof e=="string"&&ui.includes(e)}i(di,"isVetVisitIntent");var jb="/widget/v1/televet/handoffs",Wb="/widget/v1/televet/availability",Gb="/widget/v1/televet/chat-entry",Kb=/^[a-z0-9][a-z0-9_-]{0,39}$/,qb=/^[A-Za-z0-9_-]{22}$/;var Ad=32,Od=128,Fd=64;function pi(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(pi,"vetVisitErrorReasonOf");function Md(e){return v(L("validationFailed",{retryable:false,wireMessage:e}))}i(Md,"invalid");function ci(e){return v(L("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(ci,"unusable");function $b(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Kb.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>Fd)return {ok:false,message:`visitRef must be 1..${Fd} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!di(a))return {ok:false,message:`intent must be one of ${ui.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i($b,"handoffBody");function Yb(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!di(r)?null:Object.freeze({visitRef:t,intent:r})}i(Yb,"parseVisitEcho");function Dd(e){let t=e.funnel??Re({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(Ld(r,"televet.visit.handoff_failed",{reason:pi(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>Od)return n(L("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Od} characters`}));a=o;}let l=$b(a,s);if(!l.ok){let y=Md(l.message);return y.ok?y:n(y.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:jb,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Xb(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!qb.test(f))){let y=ci("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?Yb(d.value?.visit):null;if(m&&g===null){let y=ci("the handoff response did not confirm the visit it opens");return y.ok?y:n(y.error)}let x=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...g!==null?{visit:g}:{}});return x===null?n(L("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Ld(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(x))},async checkAvailability(o){if(typeof o!="string"||o.length>Ad)return Md(`state must be at most ${Ad} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Wb,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?ci("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:Gb},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(Dd,"createVetVisitController");function Xb(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||!ev(t)?null:Object.freeze({url:t,expiresAt:r})}i(Xb,"parseHandoff");var Qb=new Set(["localhost","127.0.0.1","[::1]"]),Zb=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Jb=/[\s\u0000-\u001f\u007f]/;function ev(e){if(Jb.test(e))return false;let t=Zb.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"&&Qb.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(ev,"isOpenableVisitUrl");function Ld(e,t,r){if(e)try{e.track(t,r);}catch{}}i(Ld,"safeTrack");var Ud=Object.freeze({status:"idle",error:null,errorReason:null});function rv(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(rv,"usePreflight");var nv=Object.freeze({status:"opening",error:null,errorReason:null});function Bd(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Y(),s=Ft("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 Dd({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=rv(p,a,{usState:l,chat:u,scope:f}),g=a&&(m===null||m.open)&&(!u||d!==null),x=t.returnTo??null,[y,S]=useState(Ud),_=useRef(null),A=useRef({runtime:r,userRef:n,scopeEpoch:o});A.current={runtime:r,userRef:n,scopeEpoch:o};let k=useRef(c);k.current=c;let b=useRef(g);b.current=g;let R=useCallback((I,w)=>{if(_.current)return _.current;let T=i((G,tt)=>(S({status:G==="cancelled"?"idle":"error",error:tt,errorReason:G==="cancelled"?null:G}),Object.freeze({opened:false,reason:G,error:tt})),"fail");if(!b.current)return Promise.resolve(T("unavailable",null));let B=e.prepare();if(!B.ok)return Promise.resolve(T(B.reason,null));let K=A.current,W=k.current;S(nv);let me=(async()=>{let G,tt={...x!==null?{returnTo:x}:{},...u?{entry:"chat"}:{},...w!==null?{visitRef:w.visitRef}:{},...w!==null&&w.intent!==null&&w.intent!==void 0?{intent:w.intent}:{}},Tr=Object.keys(tt).length===0?void 0:tt,jt=I===void 0?d:I;try{G=await(Tr===void 0?W.createHandoff(jt):W.createHandoff(jt,Tr));}catch{return e.abandon(B.value),T("unknown",null)}let kt=A.current;if(kt.runtime!==K.runtime||kt.userRef!==K.userRef||kt.scopeEpoch!==K.scopeEpoch)return e.abandon(B.value),T("cancelled",null);if(!G.ok)return e.abandon(B.value),T(pi(G.error),G.error);let xt=await e.finish(B.value,G.value);return xt!==null?T(xt,null):(S(Ud),Object.freeze(G.value.flowId===void 0?{opened:true}:{opened:true,flowId:G.value.flowId}))})().finally(()=>{_.current===me&&(_.current=null);});return _.current=me,me},[e,d,x,u]),P=useCallback(I=>R(I,null),[R]),V=useCallback((I,w)=>R(void 0,{visitRef:I,intent:w??null}),[R]);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 sv=i(e=>Linking.openURL(e),"defaultOpenUrl");function yn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??sv;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(yn,"useVetVisit");var Hd=44,cv=.6;function Ut(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:g,prefer:x}=e,y=yn({...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}:{}}),S=F(),_=useMemo(()=>pv(S),[S]),A=useRef(false);if(!y.available)return null;let k=y.status==="opening",b=r??xd.visitButton,R=f!=null,P=x==="redirect"||R,V=!P&&g!==void 0;return jsx(Pressable,{onPress:i(()=>{if(!(k||A.current)){if(V){X(g);return}(A.current=true,(f==null?y.open():y.openVisit(f,m??null)).then(T=>{T.opened?X(o,T.flowId??null):T.reason!=="cancelled"&&X(s,T.reason,T.error);}).finally(()=>{A.current=false;}));}},"onPress"),accessibilityRole:"button",accessibilityLabel:b,accessibilityState:{busy:k,disabled:k},style:[_.button,k?_.busy:null,a],children:jsx(C,{style:[_.label,l],children:b})})}i(Ut,"VetVisitButton");function pv(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:Hd,minWidth:Hd,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...fe(s.vetVisitButton)},busy:{opacity:cv},label:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...Te(s.vetVisitButton)}})}i(pv,"makeStyles");function mi(e){return nr(e)==="cat"?"cat":"dog"}i(mi,"speciesOf");function yi(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(yi,"petAgeYears");function Wd(e){let t=yi(e.ageYears),r=mi(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Wd,"formatPetMeta");var jd=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 fv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return jd[t%jd.length]}i(fv,"pickInitialsPalette");function gi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(gi,"getInitial");function Gd(e){return {...fv(e.petRef),initial:gi(e.name)}}i(Gd,"petInitials");function hv(e){return Math.max(12,Math.round(e*.42))}i(hv,"letterSize");function vr({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>bv(n),[n]),s=t-r*2,a=e===null?null:Gd(e),l=hv(s);return jsx(un,{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?gi(null):a.initial})})})}i(vr,"PetDisc");function bv(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(bv,"makeStyles");var bi=48,Yd=2,Sv=320,Pv="80%",Tv="rgba(17,17,17,0.45)",kv=18,Kd=22,xv=12,qd=.4,_v=44;function vi(e){return e?.name?.trim()||h.yourPet}i(vi,"petDisplayName");function Xd({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>wv(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=vi(u),p=Wd(u);return jsxs(H,{accessibilityRole:"button",accessibilityLabel:$(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(vr,{pet:u,size:bi,ringStroke:Yd}),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(Xe,{size:kv,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(Xd,"PetSwitcherSheet");function wv(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:Tv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Kd,borderTopRightRadius:Kd,gap:14,maxHeight:Pv},title:{...E(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:Sv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:_v,paddingHorizontal:8},addDisc:{width:bi,height:bi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Yd,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:qd},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:xv,backgroundColor:t.brandSoft},closeText:{...E(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:qd}})}i(wv,"makeStyles");var Ov=44,gn=36,Fv=22,Ei=9,Mv=1.5,Qd=6,Ct=35,hn=1.75,Ri=12.4,Lv=.5,Dv=8,Nv=28,Uv=160;function Pi(e,t){return kd(e,t)}i(Pi,"headerPet");function Jd({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=useMemo(()=>Bv(l),[l]),[d,c]=useState(false),p=Pi(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,g=vi(p),x=i(S=>{c(false),e.setActivePet(S),X(o,S);},"select"),y=s===void 0?null:()=>{c(false),X(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(Uu,{size:Fv,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(Vv,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(Ut,{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:$(h.switchActivePet,{name:g}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(vr,{pet:p,size:Ct,ringStroke:hn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(Bu,{size:Dv,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(un,{size:Ct,strokeWidth:hn,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(vr,{pet:p,size:Ct,ringStroke:hn})})}),jsx(Xd,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:x,onAddPet:y,onClose:()=>c(false)})]})}i(Jd,"ChatHeader");function Vv({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(Vv,"BrandLogo");function Bv(e){let t=e.color,r=Ct-hn*2;return StyleSheet.create({vetEntry:{minHeight:Ov,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:gn/2},iconButton:{width:gn,height:gn,borderRadius:gn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Qd,right:Qd,width:Ei,height:Ei,borderRadius:Ei,backgroundColor:t.danger,borderWidth:Mv,borderColor:t.surface},center:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:Nv,width:Uv},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Ct/2},avatarWrap:{width:Ct,height:Ct,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Ri,height:Ri,borderRadius:Ri/2,borderWidth:Lv,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(Bv,"makeStyles");var tc=44,Gv="rgba(17,17,17,0.55)",rc=26,Kv=36,nc=4,Ti=20,ki=38,qv=18,$v=12;function oc({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>Yv(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"),x=i(async()=>{if(d)return;c(true),f(false);let S=l.trim();await t(s,S.length>0?S:null)?m():(c(false),f(true));},"submit");if(!e)return null;let y=[...l].length>It;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(ln,{size:qv,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:No.map(S=>{let _=s===S.key;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:S.label,accessibilityState:{selected:_},style:[o.option,_?o.optionSelected:null],onPress:()=>a(A=>A===S.key?null:S.key),children:[jsx(C,{style:[o.optionLabel,_?o.optionLabelSelected:null],children:S.label}),jsx(View,{style:[o.radio,_?o.radioSelected:null],children:_?jsx(Xe,{size:$v,color:n.color.surface,strokeWidth:2}):null})]},S.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(Mt,{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}/${It}`}):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:()=>{x();},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(oc,"FeedbackReasons");function Yv(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:Gv},sheet:{backgroundColor:t.surface,borderTopLeftRadius:rc,borderTopRightRadius:rc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:Kv,height:nc,borderRadius:nc/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:ki,height:ki,borderRadius:ki/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:Ti,height:Ti,borderRadius:Ti/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:tc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...fe(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Te(o.primaryButton)},skip:{minHeight:tc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(Yv,"makeStyles");var uC=.88,dC=420,cC=58,pC="rgba(17,17,17,0.28)",fC=.08,mC=.1,yC=.08,gC=.18,hC=.78,bC=.7,xi=36,vC=10,CC=14,EC=12,RC=16,SC=14,_i=8,PC=1.5,TC=.5,kC=cn(mr.standard);function xC(e){return Math.min(Math.round(e*uC),dC)}i(xC,"drawerPanelWidth");function sc({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(_C,{chat:e,history:t,onHidden:o}):null}i(sc,"HistoryDrawer");function _C({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>IC(n),[n]),s=Q(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=xC(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 S=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:kC,useNativeDriver:true});return S.start(({finished:_})=>{_&&!d&&r();}),()=>S.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,g=t.rows.length===0,x=g&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:J.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(C,{style:o.emptyBody,children:J.loading})]}):g&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:J.loadFailed}),jsx(C,{style:o.emptyBody,children:t.error}),jsx(H,{accessibilityRole:"button",accessibilityLabel:J.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(C,{tier:"control",style:o.retryText,children:J.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?J.empty:J.noMatch}),jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?J.emptyBody:J.noMatchBody})]}),y=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(C,{style:o.loadMoreLabel,children:J.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:J.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(Yu,{size:SC,color:n.color.text.muted,strokeWidth:1.5}),jsx(Mt,{value:t.query,onChangeText:S=>t.setQuery(S.replace(/^\s+/,"")),style:o.searchInput,placeholder:J.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:J.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(H,{accessibilityRole:"button",accessibilityLabel:J.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(Xu,{size:RC,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:J.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:S=>S.id,renderItem:({item:S})=>jsx(wC,{row:S,active:S.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(S.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:x,ListFooterComponent:y,onEndReached:t.loadMore,onEndReachedThreshold:TC})]})})]})})}i(_C,"DrawerModal");function wC({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(H,{accessibilityRole:"button",accessibilityLabel:Tu(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:on(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(wC,"Row");function En(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(En,"inkWash");function IC(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:pC},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:En(n,mC)},searchInput:{...E(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:xi,height:xi,borderRadius:xi/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:vC},itemActive:{backgroundColor:En(n,fC)},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:_i,height:_i,borderRadius:_i/2,backgroundColor:t.danger,borderWidth:PC,borderColor:n},errorCard:{borderRadius:EC,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...E(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:CC,padding:14,gap:6,backgroundColor:En(n,yC),borderWidth:.5,borderColor:En(n,gC)},emptyTitle:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...E(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:hC},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...fe(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:bC}})}i(IC,"makeStyles");function ac(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(ac,"chatVetVisitOptions");var MC=16,LC=.75,wi=12,lc=15,DC=18,Rn=22,NC=14,UC=8,VC=20,BC=10,HC=13;function dc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>zC(s),[s]),l=Q(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(ei,{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(gt,{render:()=>r(u.level),fallback:jsx(uc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(uc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(H,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:UC,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(ht,{size:NC,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(ei,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:BC,onPress:e.expand,children:jsx(Gu,{size:VC,color:s.color.text.muted,strokeWidth:2})})})]})}i(dc,"UrgencyBanner");function uc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=yn(ac(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{X(r,e.level);}:null;if(u===null)return null;let d=li(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(Qu,{size:HC,color:d,strokeWidth:1.5}),jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(uc,"VetAction");function zC(e){let t=li(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:MC,borderWidth:LC,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...E(e,"monoBold"),fontSize:wi,lineHeight:lc},reason:{...E(e,"regular"),fontSize:wi,lineHeight:DC,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:{...fe(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...E(e,"monoBold"),fontSize:wi,lineHeight:lc},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(zC,"makeStyles");function cc(){let e=mn(),{handle:t}=Y(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(cc,"useChatPets");var hc=300,bc=3e3,pc=120,Rt=44,qC=120,$C="86%",fc=15,mc=22,Pn=.5,YC=.04,XC=8,QC=2,ZC=1,JC=.6,eE=22,tE=48,yc=1.25,rE=14,nE=18,oE=6,iE=14,sE=.04,aE=12,lE=2,uE=2,gc=36,dE=20,Vt=36,Bt=(Rt-Vt)/2,vc=24,Cc=22,cE=.4,Tn=30,Ec=20,pE=.4,fE=480,mE="12%";function Ce(){let e=F(),t=useMemo(()=>yE(e),[e]);return {theme:e,styles:t}}i(Ce,"useChatTheme");function yE(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:pc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:pc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:mE,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:fE,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:Rt,minWidth:Rt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...fe(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:Rt,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:$C},bubbleUser:{padding:fc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:Pn,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:YC,shadowRadius:XC,shadowOffset:{width:0,height:QC},elevation:ZC,...fe(s.userBubble,Pn)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...fe(s.assistantBubble,Pn)}:{padding:fc,borderRadius:n.xl,...fe(s.assistantBubble,Pn)},bubblePending:{opacity:JC},bubbleTextUser:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:mc,...Te(s.userBubble)},bubbleTextAssistant:{...E(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:mc,...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:Rt,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:tE,justifyContent:"center",paddingLeft:rE,paddingRight:nE,paddingVertical:oE,backgroundColor:t.composerFill,borderWidth:yc,borderColor:t.composerBorder,borderRadius:eE,shadowColor:t.shadow,shadowOpacity:sE,shadowRadius:aE,shadowOffset:{width:0,height:lE},elevation:uE,...fe(s.composerInput,yc)},composerRow:{flexDirection:"row",alignItems:"center",gap:iE,minHeight:gc},attachControl:{width:Tn,height:Tn,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:pE},input:{flex:1,minHeight:gc,maxHeight:qC,paddingHorizontal:0,paddingVertical:0,...E(e,"regular"),fontSize:o.size.body,lineHeight:dE,color:t.text.primary,...Te(s.composerInput)},sendControl:{minHeight:Vt,minWidth:Vt,alignItems:"center",justifyContent:"center"},sendDisc:{width:Vt,height:Vt,borderRadius:Vt/2,alignItems:"center",justifyContent:"center",...fe(s.sendButton)},sendControlDisabled:{opacity:cE},poweredBy:{...E(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(yE,"makeStyles");var Je=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),Rc=Object.freeze(Lr.map(e=>Object.freeze({answer:e,label:Je.answers[e]})));function Sc(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:!Gs(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(Sc,"useCheckinCard");var xc=44,bE=.6;function _c({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s}){let a=F(),l=useMemo(()=>vE(a),[a]),u=Sc(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable;return jsxs(View,{style:l.card,accessibilityLabel:Je.eyebrow,children:[jsx(C,{tier:"compact",style:l.eyebrow,children:Je.eyebrow}),jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsx(View,{style:[l.row,u.pending?l.rowPending:null],children:Rc.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:Je.logged}):null,u.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Je.findVet,style:l.findVet,children:jsx(C,{tier:"control",style:l.findVetLabel,children:Je.findVet})}):n?jsx(Ut,{entry:"chat",petRef:n,label:Je.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(_c,"CheckinCard");function vE(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:bE},pill:{flex:1,minHeight:xc,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:xc,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(vE,"makeStyles");var EE=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),wc="#C8BEB4";function RE(e){return e?EE[e.toUpperCase()]??wc:wc}i(RE,"tierColor");function SE(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(SE,"tierLabel");function Ne(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ne,"text");function PE(e){let t=Ne(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(PE,"httpsUrl");function TE(e,t){let r=Ne(e.source_name)??Ne(e.sourceName),n=Ne(e.section),o=Ne(e.authority_tier)??Ne(e.authorityTier),s=SE(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:PE(e.url),excerpt:Ne(e.excerpt),tierColor:RE(o),key:`${a}-${l??"none"}-${t}`})}i(TE,"toCitationCard");function Ic(e){return e===void 0||e.length===0?kE:Object.freeze(e.map((t,r)=>TE(t,r)))}i(Ic,"toCitationCards");var kE=Object.freeze([]);function Oi(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(Oi,"sourcesLabel");function Ac(e,t){return `${t?h.hideSources:h.showSources} ${Oi(e)}`}i(Ac,"sourcesToggleLabel");function Oc(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Oc,"citationA11yLabel");var OE=244,Mc=8,Lc=13,FE=14,ME=.3,LE=-0.24,DE=22,NE=10,UE=15;function Dc({citations:e}){let t=F(),r=useMemo(()=>HE(t),[t]),n=useMemo(()=>Ic(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:Ac(a,o),accessibilityState:{expanded:o},containerStyle:r.toggleSlot,style:r.togglePill,onPress:()=>s(l=>!l),children:[jsx(zu,{size:Lc,color:t.color.brandInk,strokeWidth:1.5}),jsx(C,{tier:"compact",style:r.toggleLabel,children:Oi(a)}),jsx(Hu,{size:Lc,color:t.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?jsx(VE,{cards:n,styles:r}):null]})}i(Dc,"CitationCards");function VE({cards:e,styles:t}){let r=Q(),n=bt(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(BE,{card:o,styles:t},o.key))})})}i(VE,"Deck");function BE({card:e,styles:t}){let r=F(),n=Oc(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(ju,{size:FE,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(BE,"Card");function HE(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:ME,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:OE,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:Mc,height:Mc,borderRadius:n.pill},cardTitle:{...E(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:DE,color:t.text.primary,letterSpacing:LE},cardTitleLink:{color:t.linkInk},cardMeta:{...E(e,"monoMedium"),fontSize:o.nano,lineHeight:NE,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...E(e,"regular"),fontSize:o.tiny,lineHeight:UE,color:t.text.muted}})}i(HE,"makeStyles");function Nc(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(Nc,"formatMessageTime");var Rr=15,qE=15,$E=6,YE=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function zc({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>XE(s),[s]),l=Q(),u=e.role==="user",d=useMemo(()=>Nc(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 x=i(()=>{t!==void 0&&(Lt(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:qE,onPress:x,style:a.iconHit,children:f?jsx(Xe,{size:Rr,color:s.color.success,strokeWidth:2}):jsx(Wu,{size:Rr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Jl.map(({sentiment:y,label:S})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:S,accessibilityState:{selected:r===y},hitSlop:$E,onPress:()=>n?.(y),style:a.iconHit,children:jsx(ln,{size:Rr,color:s.color.sentiment[y],active:r===y,rotate:YE[y],strokeWidth:1.5})},y)):null]}),o?jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(zc,"MessageFooter");function XE(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:Rr,height:Rr,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(XE,"makeStyles");var jc="#000000",QE="#83E0B4",ZE=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:QE,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})]),JE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function eR(e){return e==null?e:e.replace(JE,"").trim()}i(eR,"formatBreedForPrompt");var tR=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 rR(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return tR.has(t)}i(rR,"isUninformativeBreed");function nR(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(nR,"unspecifiedBreedLabel");function oR(e,t){return rR(e)?nR(t):String(e).replace(/\s+/gu," ").trim()}i(oR,"resolveBreedLabel");function Wc(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return $(h.emptyTitle,{petName:t})}i(Wc,"emptyStateTitle");function Gc(e){let t=mi(e?.species),r=t==="cat"?"my cat":"my dog",n=e?.name?.trim()||null,o=n||r,s=oR(eR(e?.breed),t)||null,a=yi(e?.ageYears),l=a===null?null:String(a);return Object.freeze(ZE.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=$(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(Gc,"resolveQuickPrompts");var sR=36,$c=4,aR=340;function Yc({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>uR(s),[s]),l=useMemo(()=>Gc(e),[e]),u=Wc(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(lR,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Yc,"QuickPrompts");function lR({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=Q(),d=bt(u.followUpInMs,{delayMs:dn(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:$c,style:[l.chip,c],onPress:()=>{X(s,r);},children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(Ut,{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:$c,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(lR,"Chip");function uR(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:aR},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:sR,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...E(e,"bold"),fontSize:12,lineHeight:14,color:jc,textAlign:"center"}})}i(uR,"makeStyles");var Mi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Xc(e){return e.includes("*")||e.includes("`")}i(Xc,"hasInlineMarkup");function Qc(e){let t=[],r=0;Mi.lastIndex=0;for(let n=Mi.exec(e);n!==null;n=Mi.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(Qc,"tokenizeInlineMarkdown");function Zc(e,t){return Xc(e)?Qc(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(Zc,"renderInlineMarkdown");var tp=6,op=520,yR=Math.round(op*.18),rp=.44,gR=.5,np=[0,.5,1],hR=[0,1,2];function ip(){let e=F(),t=useMemo(()=>vR(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:hR.map(n=>r?jsx(bR,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(ip,"TypingIndicator");function bR({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*yR),Animated.loop(Animated.timing(r,{toValue:1,duration:op,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:np,outputRange:[rp,1,rp]}),o=r.interpolate({inputRange:np,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(bR,"AnimatedDot");function vR(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:tp,height:tp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:gR}})}i(vR,"makeStyles");function up(e,t,r){switch(e){case "loading":return r.renderPending?jsx(gt,{render:r.renderPending,fallback:jsx(sp,{})}):jsx(sp,{});case "empty":return jsx(PR,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(kR,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(xR,{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 Ke(e)}}i(up,"renderView");function sp(){let{theme:e,styles:t}=Ce(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),hc);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(sp,"LoadingState");function PR({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(Yc,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(dp,{prompts:r,onSelectPrompt:n})]})}i(PR,"EmptyState");function dp({prompts:e,onSelectPrompt:t}){let{styles:r}=Ce();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(TR,{prompt:n,index:o,onSelectPrompt:t},n))]})}i(dp,"FollowUps");function TR({prompt:e,index:t,onSelectPrompt:r}){let{styles:n}=Ce(),o=Q(),s=bt(o.followUpInMs,{delayMs:dn(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(TR,"FollowUpRow");function kR({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ce(),o=au(e)?yu(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(kR,"ErrorState");function xR({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:x,onFindVet:y,vet:S}){let{styles:_}=Ce(),A=Q();yr(e.length,A);let k=Fu(e,n),b=e[e.length-1];return jsxs(ScrollView,{style:_.list,contentContainerStyle:_.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(R=>R.checkin?jsx(_c,{message:R,checkin:R.checkin,onAnswer:o,petRef:x,onFindVet:y,vet:S},R.id):jsx(IR,{message:R,revealing:n&&R===b&&R.role==="assistant",onCopy:s,sentiment:R.responseId===void 0?null:a[String(R.responseId)]??null,onSentiment:l,thanks:u!==null&&R.responseId!==void 0&&String(R.responseId)===u,images:d[R.id]??wR,onPreview:c},R.id)),f?jsx(C,{tier:"compact",style:_.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,k?jsx(ip,{}):null,p!==null?jsx(_R,{notice:p,onRetry:m,onStartNew:g}):null,n?null:jsx(dp,{prompts:t,onSelectPrompt:r})]})}i(xR,"PopulatedState");function _R({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:Bt,style:n.turnNoticeAction,children:jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(_R,"TurnNoticeCard");var wR=Object.freeze([]);function IR({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l}){let{styles:u}=Ce(),d=Q(),c=bt(d.messageInMs),p=ad(e.text,t,d),f=e.role==="user",m=f?h.senderUser:h.senderAssistant,g=useCallback(y=>o(e,y),[o,e]),x=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(Sd,{images:a,onPreview:y=>l({uri:y.uri,label:y.filename})}):null,jsx(C,{style:f?u.bubbleTextUser:u.bubbleTextAssistant,children:f?e.text:Zc(p,{bold:u.bubbleBold,italic:u.bubbleItalic,code:u.bubbleCode})})]})}),!f&&!t?jsx(Dc,{citations:e.citations}):null,x?jsx(zc,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:g,thanks:s}):null]})}i(IR,"MessageRow");var LR=Object.freeze(["photo"]),DR=1;function pp(e){let{style:t,renderPending:r}=e;return jsx(Do,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(NR,{...e})})}i(pp,"EverfurChat");function NR({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:x,draftStore:y,vetReturnTo:S,vetUsState:_}){let{theme:A,styles:k}=Ce(),b=Q(),R=useMemo(()=>Mu(e,t),[e,t]),P=cr(R),V=Au(P),I=cc(),w=ku(P),T=useSafeAreaInsets(),B=Ou(P),K=useMemo(()=>l===void 0?void 0:()=>{X(l,"emergency");},[l]),W=useMemo(()=>S===void 0&&_===void 0?void 0:{returnTo:S,usState:_},[S,_]),ae=Pi(I.pets,P.petRef),me=useMemo(()=>wu(P.messages,ae?.name??null),[P.messages,ae?.name]),G=Iu(me);yr(G.showBanner,b),vu(P.openCheckin,f),pu(P.askEverfur,P.isBootstrapping,m);let tt=useMemo(()=>Wo(g),[g]);hu(x,{conversationId:P.conversationId===null?null:String(P.conversationId),isTurnInFlight:P.isStreaming,refresh:P.refreshActiveThread});let Tr=(P.hasUnreadThreads??false)||w.rows.some(_e=>_e.unreadCount!==null&&_e.unreadCount>0)||(P.unreadCount??0)>0,jt=du(P.messages),[kt,xt]=useState(null),mp=useCallback(()=>xt(null),[]),[Wt,An]=useState(null),[yp,Ni]=useState(null),_t=useRef(null);useEffect(()=>()=>{_t.current&&clearTimeout(_t.current);},[]);let Ui=useCallback(_e=>{Ni(String(_e)),_t.current&&clearTimeout(_t.current),_t.current=setTimeout(()=>{Ni(null),_t.current=null;},bc);},[]),gp=useCallback((_e,kr)=>{let Gt=_e.responseId;if(Gt===void 0)return;let Cp=P.sentimentByMessage[String(Gt)];P.feedback(Gt,kr),kr==="down"&&Cp!=="down"&&An(Gt);},[P]),hp=useCallback(async(_e,kr)=>Wt===null||!(await P.feedback(Wt,"down",_e??"other",kr)).ok?false:(An(null),Ui(Wt),true),[P,Wt,Ui]),bp=useCallback(()=>An(null),[]),vp=useCallback(_e=>{P.send(_e);},[P.send]),Vi={send:P.send,stop:P.stop,isStreaming:P.isStreaming,conversationId:P.conversationId,seed:tt,draftStore:y,onStage:jt.stage,onPreview:xt};return jsxs(KeyboardAvoidingView,{style:[k.container,{paddingTop:T.top},r],behavior:Platform.OS==="ios"?"padding":void 0,children:[jsx(Jd,{pets:I,petRef:P.petRef,historyUnread:Tr,onOpenHistory:w.show,onPetChange:s,onAddPet:p,vet:W}),c!==void 0?jsx(UR,{petRef:e??null,pet:c,onRegistered:I.refresh}):null,jsx(dc,{surface:G,petRef:P.petRef,renderVetAction:u,onFindVet:l,vet:W}),jsx(View,{style:k.body,children:up(V,P,{notice:B,vet:W,onCheckinFindVet:K,onSelectPrompt:vp,renderPending:n,shownPet:ae,onVetPrep:a,onCopy:o,onSentiment:gp,thanksFor:yp,imagesByMessage:jt.byMessage,onPreview:xt,onAddPet:p})}),d!==void 0?jsx(VR,{...Vi,attachments:d}):jsx(fp,{...Vi,attachments:null}),jsx(Nu,{}),A.meta.hidePoweredBy?null:jsx(C,{tier:"compact",style:k.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(sc,{chat:P,history:w}),jsx(oc,{visible:Wt!==null,onSubmit:hp,onSkip:bp}),jsx(ld,{uri:kt?.uri??null,label:kt?.label??"",onClose:mp})]})}i(NR,"ChatBody");function UR({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ce(),o=lu(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:Bt,children:jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(UR,"PetSetupNotice");function VR({attachments:e,...t}){let r=useMemo(()=>Td(),[]),n=rn({maxPerMessage:e.maxPerMessage??DR,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??LR,pick:e.pick}),[n,e.sources,e.pick]);return jsx(fp,{...t,attachments:o})}i(VR,"ComposerWithAttachments");function fp({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=Q(),[f,m]=Ru(e,n,s);Su(a,n===null?null:String(n),f,m);let[g,x]=useState(false),[y,S]=useState(false);useEffect(()=>{S(false);},[n]);let _=d.meta.placeholder??h.placeholder,A=o?.state.uploading??false,k=o?.state.failed??false,b=A||k,R=o?.state.attachments??BR;yr(R.length,p);let P=useCallback(()=>{if(f.trim().length===0||b||[...f].length>At)return;let W=o?.state.s3Keys??HR;o!==null&&W.length>0?(l(o.state.attachments.filter(ae=>ae.status==="uploaded").map(ae=>({uri:ae.previewUri,filename:ae.filename}))),e(f,{imageS3Keys:W}),o.state.clear()):e(f),m(""),S(false);},[f,e,b,o,l]),V=useCallback(()=>{t();},[t]),I=useCallback(W=>{x(false),o!==null&&(S(false),o.state.dismissRejected(),Lt(o.pick,W).then(ae=>{if(!ae.ok){S(true);return}ae.value!==null&&o.state.add(ae.value);}));},[o]),T=useMemo(()=>[...f].length>At,[f])||b,B=o!==null&&R.length>=o.state.maxPerMessage,K=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&g?jsx(cd,{sources:o.sources,full:B,onPick:I,onClose:()=>x(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Rd,{attachments:R,rejected:y?zR:o.state.rejected,uploadFailed:k,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:W=>u({uri:W.previewUri,label:W.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ou(R.length,o.state.maxPerMessage),accessibilityState:{disabled:B,expanded:g},disabled:B,hitSlop:(Rt-Tn)/2,style:[c.attachControl,B?c.attachControlDisabled:null],onPress:()=>x(W=>!W),children:jsx(Ku,{size:Ec,color:B?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Mt,{style:c.input,value:f,onChangeText:m,placeholder:_,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:_,onSubmitEditing:P,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:V,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:Bt,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(Ju,{size:Cc,color:K,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:P,disabled:T,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:T,busy:A},hitSlop:Bt,style:[c.sendControl,T?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(Zu,{size:vc,color:K,testID:"everfur-send-glyph"})})})]})]})]})}i(fp,"Composer");var BR=Object.freeze([]),HR=Object.freeze([]),zR=Object.freeze({code:"unknown",retryable:true,filename:""});function qR(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(qR,"useEverfurPetProfile");function YR(e){return createElement(Jr,{clientTheme:e.clientTheme??null,seams:tn,children:e.children})}i(YR,"EverfurThemeProvider");export{Do as CapabilityGate,pp as EverfurChat,Z as EverfurConfigError,Wg as EverfurProvider,YR as EverfurThemeProvider,xr as EverfurThrownError,cy as THEME_SLOT_KEYS,pt as THEME_SLOT_NAMES,nr as canonicalPetSpecies,Fn as categoryFor,_p as conversationId,jp as createRnRecordsUploadTransport,E as face,Sp as isErr,Rp as isOk,Mn as isRetryableCode,kp as petRef,By as previewTheme,Pp as unwrap,Ft as useCapability,rn as useChatAttachments,Il as useEverfur,cr as useEverfurChat,qR as useEverfurPetProfile,mn as useEverfurPets,F as useEverfurTheme,wt as userFacingError,xp as userRef};