@everfur/sdk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +182 -0
  2. package/README.md +9 -8
  3. package/dist/{Chat-BZZ-Py5l.d.ts → Chat-BOX-03ho.d.ts} +17 -3
  4. package/dist/{Chat-Dq4fffIO.d.cts → Chat-TA-aTcVF.d.cts} +17 -3
  5. package/dist/{DepthViews-CkYri51q.d.ts → DepthViews-CgjX2AJ5.d.ts} +1 -1
  6. package/dist/{DepthViews-CL75jyRA.d.cts → DepthViews-Cviea-ri.d.cts} +1 -1
  7. package/dist/{DepthViews-BG3E25MD.d.ts → DepthViews-D2dRqWRq.d.ts} +1 -1
  8. package/dist/{DepthViews-B_hIypI6.d.cts → DepthViews-DSFyaSeL.d.cts} +1 -1
  9. package/dist/{ErrorPolicyPort-CwbfmxzJ.d.ts → ErrorPolicyPort-D22LUVrK.d.ts} +1 -1
  10. package/dist/{ErrorPolicyPort-CNf4uQZP.d.cts → ErrorPolicyPort-D6CybiqJ.d.cts} +1 -1
  11. package/dist/{EverfurResult-DN9pL2Ab.d.cts → EverfurError-DmELDpXp.d.cts} +1 -67
  12. package/dist/{EverfurResult-DN9pL2Ab.d.ts → EverfurError-DmELDpXp.d.ts} +1 -67
  13. package/dist/EverfurResult-SGvHKsCB.d.ts +69 -0
  14. package/dist/EverfurResult-ZtH-YV1h.d.cts +69 -0
  15. package/dist/animations/index.d.cts +6 -5
  16. package/dist/animations/index.d.ts +6 -5
  17. package/dist/{attachments-BrUWQYNK.d.ts → attachments-C_vtFu2f.d.ts} +7 -6
  18. package/dist/{attachments-D_SECjr1.d.cts → attachments-DHvnITuE.d.cts} +7 -6
  19. package/dist/{attachments-DpldrvIW.d.ts → attachments-oD5U2fXI.d.ts} +3 -3
  20. package/dist/{attachments-BorG422I.d.cts → attachments-pIdGOQfm.d.cts} +3 -3
  21. package/dist/{bookingCopy-CqtDYvCR.d.ts → bookingCopy-CJir9mjb.d.ts} +417 -14
  22. package/dist/{bookingCopy-SREvkG19.d.cts → bookingCopy-DfuA13dh.d.cts} +417 -14
  23. package/dist/branding-Xb_wL8N1.d.cts +212 -0
  24. package/dist/branding-xpQ056sM.d.ts +212 -0
  25. package/dist/callCopy-rDH9JTFo.d.cts +45 -0
  26. package/dist/callCopy-rDH9JTFo.d.ts +45 -0
  27. package/dist/callRoom-7wrE3RP2.d.ts +62 -0
  28. package/dist/callRoom-B_EqaUzx.d.cts +62 -0
  29. package/dist/{casesRepository-DwtZVsbj.d.cts → casesRepository-B-Eg8ZJ3.d.cts} +14 -2
  30. package/dist/{casesRepository-v6QczS9N.d.ts → casesRepository-DHgIYKN9.d.ts} +14 -2
  31. package/dist/chat/index.cjs +1 -1
  32. package/dist/chat/index.d.cts +12 -11
  33. package/dist/chat/index.d.ts +12 -11
  34. package/dist/chat/index.js +1 -1
  35. package/dist/client/index.cjs +5 -5
  36. package/dist/client/index.d.cts +14 -12
  37. package/dist/client/index.d.ts +14 -12
  38. package/dist/client/index.js +5 -5
  39. package/dist/{config--Wu1Umhd.d.cts → config-ClI7QxB0.d.ts} +3 -2
  40. package/dist/{config-C7eb_IMD.d.ts → config-DAFbf721.d.cts} +3 -2
  41. package/dist/consent/index.d.cts +9 -8
  42. package/dist/consent/index.d.ts +9 -8
  43. package/dist/{context-CL3lyuy1.d.cts → context-B-dUM1Qf.d.cts} +9 -8
  44. package/dist/{context-CahAEha8.d.ts → context-CZbgF_OH.d.ts} +9 -8
  45. package/dist/{copy-DdVFDL01.d.ts → copy-CeRH3NXy.d.ts} +5 -4
  46. package/dist/{copy-UeUJVk8X.d.cts → copy-CneuYdrO.d.cts} +5 -4
  47. package/dist/core/index.cjs +9 -9
  48. package/dist/core/index.d.cts +19 -17
  49. package/dist/core/index.d.ts +19 -17
  50. package/dist/core/index.js +9 -9
  51. package/dist/{depth-D5HwcvKC.d.cts → depth-B3NFKlF9.d.cts} +6 -5
  52. package/dist/{depth-DvPwPuT_.d.ts → depth-DO3Ko_qs.d.ts} +6 -5
  53. package/dist/{entitlementRepository-B7egEdW6.d.ts → entitlementRepository-74kW5mK0.d.ts} +4 -4
  54. package/dist/{entitlementRepository-BpJ7tiwl.d.cts → entitlementRepository-m6zLUmiB.d.cts} +4 -4
  55. package/dist/{identity-C2-08BZW.d.cts → identity-C7uxGwfT.d.cts} +2 -2
  56. package/dist/{identity-CEi9GRFZ.d.ts → identity-CLAUq-K4.d.ts} +2 -2
  57. package/dist/index.cjs +6 -6
  58. package/dist/index.d.cts +19 -17
  59. package/dist/index.d.ts +19 -17
  60. package/dist/index.js +6 -6
  61. package/dist/{models-D2EUxPZY.d.cts → models-Bn2z0NNo.d.cts} +1 -1
  62. package/dist/{models-B-Uh2LTf.d.ts → models-DSqA5Ahs.d.ts} +1 -1
  63. package/dist/notifications/index.d.cts +5 -4
  64. package/dist/notifications/index.d.ts +5 -4
  65. package/dist/{pets-JVCXgRgR.d.cts → pets-BoB5B7kp.d.cts} +2 -2
  66. package/dist/{pets-DJv2sj2H.d.ts → pets-w4M9d-Dn.d.ts} +2 -2
  67. package/dist/{petsRepository-Bk6GDwLs.d.ts → petsRepository-BjKJ8UsN.d.ts} +2 -2
  68. package/dist/{petsRepository-B_gKbAzJ.d.cts → petsRepository-DZZoEG3r.d.cts} +2 -2
  69. package/dist/photo/index.d.cts +3 -2
  70. package/dist/photo/index.d.ts +3 -2
  71. package/dist/{ports-D7YW8qz9.d.ts → ports-BO3bzTJg.d.ts} +13 -6
  72. package/dist/{ports-BY2ph0_y.d.cts → ports-C2EVK416.d.cts} +13 -6
  73. package/dist/records/depth/index.d.cts +11 -10
  74. package/dist/records/depth/index.d.ts +11 -10
  75. package/dist/records/index.cjs +3 -3
  76. package/dist/records/index.d.cts +25 -14
  77. package/dist/records/index.d.ts +25 -14
  78. package/dist/records/index.js +3 -3
  79. package/dist/{requestFunnel-DFMGcluw.d.ts → requestFunnel-D7ipek3e.d.ts} +5 -4
  80. package/dist/{requestFunnel-BjDpqqvm.d.cts → requestFunnel-Djjwgoe9.d.cts} +5 -4
  81. package/dist/{runtimeTypes-w5KqBMcs.d.ts → runtimeTypes-CTL3yToK.d.ts} +7 -7
  82. package/dist/{runtimeTypes-gZEJu-da.d.cts → runtimeTypes-D2C9uD85.d.cts} +7 -7
  83. package/dist/server/events/index.cjs +1 -1
  84. package/dist/server/events/index.d.cts +4 -3
  85. package/dist/server/events/index.d.ts +4 -3
  86. package/dist/server/events/index.js +1 -1
  87. package/dist/server/index.cjs +1 -1
  88. package/dist/server/index.d.cts +5 -4
  89. package/dist/server/index.d.ts +5 -4
  90. package/dist/server/index.js +1 -1
  91. package/dist/televet/booking/index.cjs +1 -1
  92. package/dist/televet/booking/index.d.cts +303 -31
  93. package/dist/televet/booking/index.d.ts +303 -31
  94. package/dist/televet/booking/index.js +1 -1
  95. package/dist/televet/call/index.cjs +1 -1
  96. package/dist/televet/call/index.d.cts +25 -5
  97. package/dist/televet/call/index.d.ts +25 -5
  98. package/dist/televet/call/index.js +1 -1
  99. package/dist/televet/index.cjs +1 -1
  100. package/dist/televet/index.d.cts +41 -71
  101. package/dist/televet/index.d.ts +41 -71
  102. package/dist/televet/index.js +1 -1
  103. package/dist/televetGlobal-CEk0_cW9.d.cts +34 -0
  104. package/dist/televetGlobal-Cs9Wbqsy.d.ts +34 -0
  105. package/dist/testing/index.cjs +4 -4
  106. package/dist/testing/index.d.cts +3 -2
  107. package/dist/testing/index.d.ts +3 -2
  108. package/dist/testing/index.js +4 -4
  109. package/dist/testing/rn/index.cjs +1 -1
  110. package/dist/testing/rn/index.d.cts +13 -11
  111. package/dist/testing/rn/index.d.ts +13 -11
  112. package/dist/testing/rn/index.js +1 -1
  113. package/dist/testing/web/index.d.cts +14 -13
  114. package/dist/testing/web/index.d.ts +14 -13
  115. package/dist/{timelineRows-C15jxFFH.d.ts → timelineRows-7yFNK_rU.d.ts} +1 -1
  116. package/dist/{timelineRows-odO8g9r2.d.cts → timelineRows-CzR1T2DR.d.cts} +1 -1
  117. package/dist/{branding-CsRdeNwK.d.cts → tokens-CIngRkvt.d.cts} +7 -211
  118. package/dist/{branding-CsRdeNwK.d.ts → tokens-CIngRkvt.d.ts} +7 -211
  119. package/dist/{typeStyle-DmoyacDG.d.ts → typeStyle-DHJzDaUo.d.cts} +2 -1
  120. package/dist/{typeStyle-CKqVYD6L.d.cts → typeStyle-YPS_MXeI.d.ts} +2 -1
  121. package/dist/{useRecordsDepth-C6rjEaLn.d.cts → useRecordsDepth-Bnw36jPr.d.cts} +24 -5
  122. package/dist/{useRecordsDepth-crhBllQK.d.ts → useRecordsDepth-DFF7Faxx.d.ts} +24 -5
  123. package/dist/{useVetVisit-CjmMa896.d.ts → useVetVisit-BsjoDO-n.d.ts} +21 -6
  124. package/dist/{useVetVisit-Bc84hWUU.d.cts → useVetVisit-Ds8f1peV.d.cts} +21 -6
  125. package/dist/video/index.d.cts +3 -2
  126. package/dist/video/index.d.ts +3 -2
  127. package/dist/{view-Bxwxp4xD.d.ts → view-BqcOYFTr.d.ts} +5 -4
  128. package/dist/{view-DyitEO0m.d.cts → view-CaJs8WFH.d.cts} +5 -4
  129. package/dist/web/consent/index.d.cts +9 -8
  130. package/dist/web/consent/index.d.ts +9 -8
  131. package/dist/web/index.cjs +10 -10
  132. package/dist/web/index.d.cts +42 -19
  133. package/dist/web/index.d.ts +42 -19
  134. package/dist/web/index.js +10 -10
  135. package/dist/web/notifications/index.d.cts +7 -6
  136. package/dist/web/notifications/index.d.ts +7 -6
  137. package/dist/web/records/depth/index.cjs +2 -2
  138. package/dist/web/records/depth/index.d.cts +11 -10
  139. package/dist/web/records/depth/index.d.ts +11 -10
  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 +53 -35
  143. package/dist/web/records/index.d.ts +53 -35
  144. package/dist/web/records/index.js +3 -3
  145. package/dist/web/televet/booking/index.cjs +2 -1
  146. package/dist/web/televet/booking/index.d.cts +453 -32
  147. package/dist/web/televet/booking/index.d.ts +453 -32
  148. package/dist/web/televet/booking/index.js +2 -1
  149. package/dist/web/televet/call/index.cjs +1 -1
  150. package/dist/web/televet/call/index.d.cts +3 -1
  151. package/dist/web/televet/call/index.d.ts +3 -1
  152. package/dist/web/televet/call/index.js +1 -1
  153. package/dist/web/televet/index.cjs +1 -1
  154. package/dist/web/televet/index.d.cts +40 -74
  155. package/dist/web/televet/index.d.ts +40 -74
  156. package/dist/web/televet/index.js +1 -1
  157. package/package.json +3 -2
  158. package/dist/callCopy-DoQKG3-L.d.cts +0 -40
  159. package/dist/callCopy-DoQKG3-L.d.ts +0 -40
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- 'use strict';var react=require('react'),reactNativeSafeAreaContext=require('react-native-safe-area-context'),zod=require('zod'),Pg=require('react-native-sse'),reactNative=require('react-native'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Pg__default=/*#__PURE__*/_interopDefault(Pg);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=`
1
+ 'use strict';var react=require('react'),reactNativeSafeAreaContext=require('react-native-safe-area-context'),zod=require('zod'),sh=require('react-native-sse'),reactNative=require('react-native'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var sh__default=/*#__PURE__*/_interopDefault(sh);var nf=Object.defineProperty;var i=(e,t)=>nf(e,"name",{value:t,configurable:true});function Re(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Re,"hasLoneSurrogate");function it(e){return [...e].length}i(it,"serverLength");function M(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(M,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function of(e){return e.ok}i(of,"isOk");function sf(e){return !e.ok}i(sf,"isErr");var Or=class Or extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Or.prototype);}};i(Or,"EverfurThrownError");var Ar=Or;function af(e){if(e.ok)return e.value;throw new Ar(e.error)}i(af,"unwrap");var Fr=class Fr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fr.prototype);}};i(Fr,"EverfurConfigError");var Q=Fr;var ns=128,os=128,is=/[\u0000-\u001F\u007F]/,lf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uf(e){let t=e,r=it(t);if(r===0||r>os)throw new Q("invalid-argument",`petRef must be 1..${os} characters`);if(is.test(t))throw new Q("invalid-argument","petRef must be printable (no control characters)");return t}i(uf,"petRef");function df(e){let t=e,r=it(t);if(r===0||r>ns)throw new Q("invalid-argument",`userRef must be 1..${ns} characters`);if(t.includes("@"))throw new Q("invalid-argument","userRef must not contain '@'");if(is.test(t))throw new Q("invalid-argument","userRef must be printable (no control characters)");return t}i(df,"userRef");function cf(e){if(!lf.test(e))throw new Q("invalid-argument","conversationId must be a UUID");return e}i(cf,"conversationId");var Vn=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Vn.map(e=>e.wireCode));var pf=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),as=Object.freeze(Vn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:pf[e.wireCode]}))),ff=new Map(as.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),mf=Object.freeze(["http_envelope",...[...new Set(as.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Mr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...mf]){let o=ff.get(n+r);if(o)return o}}i(Mr,"contractErrorFor");function yf(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(yf,"contractDocUrl");function ls(e){return null}i(ls,"publishedDocUrl");var gf=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Hn(e){return gf[e]}i(Hn,"categoryFor");function Ae(e){let t=Mr(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Ae,"fromWire");function us(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(us,"fromHttpStatus");var hf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function He(e){return hf.has(e)}i(He,"isAutoRetryable");var bf=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Bn(e){return He(e)||bf.has(e)}i(Bn,"isRetryableCode");function Lr(e,t=false){return t||He(e)}i(Lr,"shouldRetry");var vf=500,zn=8e3,Yt=4;function Dr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(vf*2**r,zn);return Math.floor(t()*n)}i(Dr,"backoffDelayMs");function ds(e){return e==="conversationNotFound"}i(ds,"canRecreateOnNotFound");var Cf=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function It(e){return Cf[e]}i(It,"userFacingError");function cs(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(cs,"defineHidden");var Ef=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Mr(t?.wireCode,t?.wireEnvelope),n={code:e,category:Hn(e),retryable:t?.retryable??Bn(e),displayMessage:It(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ef.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&cs(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&cs(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Rf="file",Sf="document.pdf",Tf="records upload: the file handle has no uri",Pf="records upload failed";function kf(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Tf));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Pf)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(Rf,{uri:r.uri,name:Sf,type:"application/pdf"});let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(kf,"createRnRecordsUploadTransport");var Nr=Object.freeze({track(){},trackExpectedFailure(){}});var ps=Object.freeze({shouldRetry(e,t){return He(e)&&t<Yt},maxAttempts(){return Yt}});var fs=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Xe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Xe,"assertNever");function ms(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ms,"acceptedFrame");function ys(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(ys,"heartbeatFrame");function gs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(gs,"deltaFrame");function hs(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(hs,"doneFrame");function pe(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(pe,"errorFrame");function bs(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(bs,"analysisStartedFrame");function vs(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(vs,"analysisCompleteFrame");function Cs(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Cs,"unknownFrame");function Es(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new Q("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:wf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new Q("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Es,"createIdentityProvider");function wf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(wf,"expiryMs");function Wn(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(Wn,"newSessionId");function If(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(If,"authHeaders");function Xt(e,t){return {...e,headers:{...Af(e.headers),...If(t)}}}i(Xt,"withAuthHeaders");function Af(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(Af,"stripAuthHeaders");async function Rs(e,t){if(t.mode==="anonymous")return t.transport.request(Xt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(jn())}let n=await t.transport.request(Xt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return v(jn())}let s=await t.transport.request(Xt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(jn(s.error.httpStatus)):s}i(Rs,"authedSend");function jn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(jn,"authRejectedError");var Ss=`
2
2
 
3
- `,Yp=1048576,Xp=zod.z.record(zod.z.string(),zod.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(`
3
+ `,Of=1048576,Ff=zod.z.record(zod.z.string(),zod.z.unknown()),Mf=["emergency","schedule_soon","home_care"];async function*Ur(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",a=0,l=false;for await(let u of e){for(s+=o.decode(u,{stream:true});;){let d=s.indexOf(Ss,a);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+Ss.length),a=0;let p=Ts(c,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Of){yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let u=Ts(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ur,"parseSse");function Ts(e,t){let r=null,n=[];for(let a of e.split(`
4
4
  `)){let l=a.replace(/\s+$/,"");l.length===0||l.startsWith(":")||(l.startsWith("id:")?r=l.slice(3).trim():l.startsWith("data:")&&n.push(l.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
5
- `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=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}
5
+ `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Ff.safeParse(o);return s.success?Lf(s.data,r,t):null}i(Ts,"parseBlock");function Lf(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return pe({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return hs({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:Uf(e.follow_up_questions),citations:Ps(e.citations),citationStatus:le(e.citation_status),urgencyLevel:ks(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:Nf(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return ms(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return ys(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=le(e.delta)??le(e.token)??"";return gs(s,t,r)}return o==="analysis_started"?bs(le(e.request_id),t,r):o==="analysis_complete"?vs({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:Df(e.confidence),detections:Ps(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):Cs(e,t,r)}i(Lf,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function Df(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Df,"asNumber");function ks(e){return typeof e=="string"&&Mf.includes(e)?e:null}i(ks,"asUrgency");function Nf(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||ks(t)!==null}i(Nf,"urgencySlotProvided");function Uf(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Uf,"asStringList");function Vf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Vf,"isPlainObject");function Ps(e){return Array.isArray(e)?e.filter(Vf):[]}i(Ps,"asMapList");var Hf="0.5.0",Bf="react-native",zf="2026-09-19",xs="EVERFUR_API_BASE_URL";function Qt(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(Qt,"configFailure");function Kn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Kn,"checkPublishableKey");function _s(e,t){let r=Kn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=jf(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||zf;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Hf,platform:t?.platform??Bf,debug:e.debug===true})})}i(_s,"tryResolveClientConfig");function jf(e){let t=e?.trim(),r=t&&t.length>0?t:Qf(xs);return r?Yf(r):Qt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${xs}. The SDK never ships a hardcoded host.`)}i(jf,"tryResolveApiBaseUrl");function ws(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(ws,"buildBaseHeaders");var Wf=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Gf(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Gf,"hostOf");function Kf(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Kf,"isPrintableHost");function qf(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Kf(t)}i(qf,"canEchoOrigin");function $f(e,t){return `${e}://${t}`}i($f,"safeOrigin");function Yf(e){let t=e.trim(),r=Wf.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Qt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Gf(r[2]);if(o.length===0)return Qt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=qf(t,o)?`: ${$f(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Xf(o)))return n==="http"?Qt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):Qt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let a=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:a})}i(Yf,"normalizeBaseUrl");function Xf(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Xf,"isLoopbackHost");function Qf(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Qf,"readEnv");var Zf=3e4,Fs="x-request-id";async function*Is(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Is,"fetchByteSource");function Jf(e){let t=new TextEncoder,r=tm(),n=false,o=i(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
6
6
  `);let c=u.data??"";for(let p of c.split(`
7
7
  `))d+=`data: ${p}
8
8
  `;d+=`
9
- `,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=vs(d),p=Ue(we(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
9
+ `,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=Ds(d),p=He(Ae(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
10
10
 
11
- `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),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]=react.createContext(null));Zr.displayName??="EverfurContext";function Y(){let e=react.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]=react.createContext(ct));dr.displayName??="EverfurThemeContext";function F(){return react.useContext(dr)}i(F,"useEverfurTheme");function Jr(e){let{runtime:t}=Y(),r=t.entitlements,n=react.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=react.useMemo(()=>e.clientTheme?He(e.clientTheme):null,[p]),m=n.branding??null,g=react.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),react.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=react.useRef(null),c=react.useRef(null),[p,f]=react.useReducer(T=>T+1,0),m=react.useRef(null),g=react.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=react.useRef(null),_=react.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=react.useRef(null);react.useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||R.current!==T&&(R.current=T,f());}),react.useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let P=y?.userRef??null;react.useLayoutEffect(()=>{b.setUser(y);},[b,P]),react.useLayoutEffect(()=>{b.setActivePet(k);},[b,k]),react.useEffect(()=>()=>b.dispose(),[b]),react.useEffect(()=>{s==="onMount"&&b.prepare(k===null?{}:{petRef:k});},[b,s,P,k]);let V=react.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=react.useMemo(()=>({runtime:b,handle:V,userRef:P,activePet:k,scopeEpoch:b.scopeEpoch}),[b,V,P,k,p]),w=react.createElement(Jr,{clientTheme:o??null,seams:l.theme,children:a});return react.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__default.default;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=reactNative.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]=react.useState(false);return react.useEffect(()=>{let r=true,n=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(reactNative.AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(Og,"useRnReducedMotion");function Hl(){let e=reactNative.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(reactNative.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(Hl,"readFontScale");function Fg(e){let t=reactNative.Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(reactNative.Dimensions,"change",e);return ()=>r?.remove?.()}i(Fg,"subscribeFontScale");function Mg(){return react.useSyncExternalStore(Fg,Hl,Hl)}i(Mg,"useRnTextScale");function Gl(){try{let e=reactNative.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]=react.useState(false);return react.useEffect(()=>{let r=true,{query:n,event:o}=Lg(),a=reactNative.AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(reactNative.AccessibilityInfo);Ag(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=reactNative.AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(reactNative.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 react.createElement(reactNativeSafeAreaContext.SafeAreaProvider,null,e)}i(zg,"wrapInSafeArea");var jg=Object.freeze({platform:"react-native",eventSourceFactory:Ul(),wrap:zg,theme:tn});function Wg(e){return react.createElement(Nl,{...e,seams:jg})}i(Wg,"EverfurProvider");function Ft(e){let{runtime:t}=Y(),r=t.entitlements,n=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return react.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 react.createElement(reactNative.Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Mt=react.forwardRef(i(function(t,r){return react.createElement(reactNative.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 react.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 react.createElement(Oo,{fallback:t,resetKey:r,children:react.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=react.useMemo(()=>th(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsxRuntime.jsx(gt,{render:o,fallback:jsxRuntime.jsx(Xl,{capability:t,style:s})}):jsxRuntime.jsx(Xl,{capability:t,style:s});case "disabled":return n?jsxRuntime.jsx(gt,{render:()=>n(a),fallback:jsxRuntime.jsx(Ql,{decision:a,style:s}),resetKey:a}):jsxRuntime.jsx(Ql,{decision:a,style:s});default:return Ke(l)}}i(Do,"CapabilityGate");function Xl({capability:e,style:t}){let r=F(),n=react.useMemo(()=>Zl(r),[r]);return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsxRuntime.jsx(reactNative.View,{style:n.skeletonBar})})}i(Xl,"PendingSkeleton");function Ql({decision:e,style:t}){let r=F(),n=react.useMemo(()=>Zl(r),[r]),o=e.disabled?.reason??"";return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsxRuntime.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 reactNative.StyleSheet.create({offstate:{minHeight:eh,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:reactNative.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=react.useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[u,d]=react.useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=react.useRef(null);react.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=react.useCallback(I=>c?c.subscribe(I):ah,[c]),m=react.useCallback(()=>c?c.getSnapshot():sh,[c]),g=react.useSyncExternalStore(f,m,m),x=react.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=react.useCallback(I=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Vo(c,c.askEverfur(I),()=>p.current===c):Promise.resolve(Bo()),[c]),S=react.useCallback(()=>c&&p.current===c?Vo(c,c.retryLast(),()=>p.current===c):Promise.resolve(Bo()),[c]),_=react.useCallback(()=>{c&&p.current===c&&c.stop();},[c]),A=react.useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[k,b]=react.useState({controller:null,byMessage:{}}),R=k.controller===c?k.byMessage:lh,P=react.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=react.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 react.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=react.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]);react.useEffect(()=>()=>{s!==e.queue&&s.dispose();},[s,e.queue]);let a=react.useSyncExternalStore(s.subscribe,s.getSnapshot,()=>fh),[l,u]=react.useState(null),d=react.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=react.useCallback(y=>s.retry(y),[s]),p=react.useCallback(y=>s.remove(y),[s]),f=react.useCallback(()=>s.clear(),[s]),m=react.useCallback(()=>u(null),[u]),g=a.attachments.some(y=>y.status==="uploading"),x=a.attachments.some(y=>y.status==="failed");return react.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=react.useCallback(()=>qe(n.registry.services.authFor(o)),[n,o,s]),l=react.useMemo(()=>t===void 0?null:zo(t),[t]),[u,d]=react.useState({key:null,status:"idle",error:null,registered:null}),c=react.useRef(0),p=react.useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=react.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]);react.useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let g=react.useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return react.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]=react.useState(jo),n=react.useRef(null),o=react.useRef([]);o.current=e.map(a=>a.id),react.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=react.useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return react.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=react.useRef(e);o.current=e;let s=react.useRef(null);react.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=react.useRef(t);r.current=t;let n=react.useRef(null),o=react.useRef(null),s=e?.isOffline===void 0?false:X(()=>e.isOffline?.()===!0)===true,a=react.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(()=>{});}},react.useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),react.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=react.useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=react.useRef(null);react.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]=react.useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);react.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=react.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=react.useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=react.useRef(null),[a,l]=react.useState(null);react.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]),react.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]=react.useState(false),[n,o]=react.useState(""),s=e.listConversations,a=react.useRef(0),[l,u]=react.useState(()=>$o(s)),d=l.scope===s?l:$o(s);react.useEffect(()=>(a.current+=1,r(false),o(""),u($o(s)),()=>{a.current+=1;}),[s]);let c=react.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=react.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]=react.useState(null),[o,s]=react.useState(false);react.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=react.useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=react.useCallback(()=>s(true),[]);return react.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=react.useMemo(()=>zh(t),[t]);return jsxRuntime.jsxs(reactNative.View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${fr.title}. ${fr.body}`,children:[jsxRuntime.jsx(C,{style:r.title,children:fr.title}),jsxRuntime.jsx(C,{style:r.body,children:fr.body})]})}i(Nu,"ClinicalDisclaimer");function zh(e){let{color:t,space:r,type:n}=e;return reactNative.StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{gap:e*.22}],...ie,children:[jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{transform:[{rotate:n}]}],...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(Vu,"Cross");function Bu(e){return jsxRuntime.jsx(Vu,{...e,rotate:"0deg"})}i(Bu,"PlusGlyph");function ht(e){return jsxRuntime.jsx(Vu,{...e,rotate:"45deg"})}i(ht,"CloseGlyph");function Xe({size:e,color:t,strokeWidth:r}){let n=pe(e,r);return jsxRuntime.jsx(reactNative.View,{style:re(e),...ie,children:jsxRuntime.jsx(reactNative.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 jsxRuntime.jsx(reactNative.View,{style:re(e),...ie,children:jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{flexDirection:"row",gap:1}],...ie,children:[jsxRuntime.jsx(reactNative.View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:[s,{top:0,left:0}]}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{transform:[{rotate:o}]}],...ie,children:[jsxRuntime.jsx(reactNative.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}}),jsxRuntime.jsx(reactNative.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"}]}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:[re(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.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}}),jsxRuntime.jsx(reactNative.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:jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.View,{style:re(e),...ie,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsxRuntime.jsx(reactNative.View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsxRuntime.jsx(reactNative.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 jsxRuntime.jsx(reactNative.View,{style:re(e),testID:r,...ie,children:jsxRuntime.jsx(reactNative.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 jsxRuntime.jsx(reactNative.View,{style:re(e),testID:r,...ie,children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(Ju,"StopGlyph");function un({size:e,strokeWidth:t,color:r,children:n}){return jsxRuntime.jsx(reactNative.View,{style:[re(e),{borderRadius:e/2,borderWidth:t??reactNative.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=react.useRef(null);return t.current===null&&(t.current=new reactNative.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 react.useEffect(()=>{if(e<=0)return;let s=reactNative.Animated.timing(o,{toValue:1,duration:e,easing:Jh,useNativeDriver:true}),a=n>0?reactNative.Animated.sequence([reactNative.Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),react.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]=react.useState(e),l=Jo(e&&t<=0?1:0);return react.useEffect(()=>{if(e){a(true);let d=reactNative.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=reactNative.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:jsxRuntime.jsx(reactNative.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=react.useCallback(d=>{a.pressMs<=0||a.pressScale===1||reactNative.Animated.timing(l,{toValue:d,duration:a.pressMs,easing:Yo,useNativeDriver:true}).start();},[l,a.pressMs,a.pressScale]);return jsxRuntime.jsx(reactNative.Pressable,{...s,style:t,onPressIn:d=>{u(a.pressScale),n?.(d);},onPressOut:d=>{u(1),o?.(d);},children:jsxRuntime.jsx(reactNative.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]=react.useState(0),a=react.useRef(e);return a.current=e,react.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,reactNative.Platform.OS==="android"&&typeof reactNative.UIManager.setLayoutAnimationEnabledExperimental=="function"&&reactNative.UIManager.setLayoutAnimationEnabledExperimental(true)),reactNative.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=react.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=reactNativeSafeAreaContext.useSafeAreaInsets();return e===null?null:jsxRuntime.jsxs(reactNative.Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:h.closePreview,style:pn.backdrop,onPress:r,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:e},style:pn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[pn.closeWrap,{top:o.top+ub}],children:jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:lb,style:pn.closeButton,onPress:r,children:jsxRuntime.jsx(ht,{size:ab,color:n.color.surface,strokeWidth:2})})})]})}i(ld,"AttachmentImageLightbox");var pn=reactNative.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=react.useMemo(()=>Eb(o),[o]);return jsxRuntime.jsxs(reactNative.View,{style:s.anchor,pointerEvents:"box-none",children:[jsxRuntime.jsx(reactNative.Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxRuntime.jsxs(reactNative.View,{style:s.bubble,children:[jsxRuntime.jsx(reactNative.View,{style:s.tilesRow,children:e.map(a=>jsxRuntime.jsxs(H,{accessibilityRole:"button",accessibilityLabel:dd[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsxRuntime.jsx(reactNative.View,{style:s.tileIconWrap,children:a==="photo"?jsxRuntime.jsx(qu,{size:ud,color:o.color.brandInk,strokeWidth:1.5}):jsxRuntime.jsx($u,{size:ud,color:o.color.brandInk,strokeWidth:1.5})}),jsxRuntime.jsx(C,{tier:"control",style:s.tileLabel,children:dd[a]})]},a))}),jsxRuntime.jsx(reactNative.View,{style:s.tail}),jsxRuntime.jsx(reactNative.View,{style:s.tailFill})]})]})}i(cd,"AttachmentPickerPopover");function Eb(e){let t=e.color,r=e.radius;return reactNative.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=react.useMemo(()=>Pd(a),[a]);return e.length===0&&t===null?null:jsxRuntime.jsxs(reactNative.View,{style:l.strip,children:[e.length>0?jsxRuntime.jsx(reactNative.View,{style:l.cards,children:e.map(u=>jsxRuntime.jsx(Fb,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsxRuntime.jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsxRuntime.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=react.useRef(e.status),[c,p]=react.useState(false);return react.useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxRuntime.jsxs(reactNative.View,{style:t.card,children:[jsxRuntime.jsx(reactNative.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:jsxRuntime.jsxs(reactNative.View,{style:t.thumb,children:[jsxRuntime.jsx(reactNative.Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsxRuntime.jsx(reactNative.View,{style:t.uploadingOverlay,children:jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsxRuntime.jsx(Mb,{styles:t,onDone:()=>p(false)}):null]})}),l?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:$(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsxRuntime.jsx(reactNative.View,{style:t.failedInner,children:jsxRuntime.jsx(ht,{size:Ed,color:s.color.surface,strokeWidth:2})})}):null,jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:$(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsxRuntime.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=react.useRef(null);o.current===null&&(o.current=new reactNative.Animated.Value(0));let s=o.current;return react.useEffect(()=>{let a=reactNative.Animated.sequence([reactNative.Animated.timing(s,{toValue:1,duration:wb,useNativeDriver:true}),reactNative.Animated.delay(n.uploadFlashMs),reactNative.Animated.timing(s,{toValue:0,duration:Ib,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsxRuntime.jsx(reactNative.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsxRuntime.jsx(Xe,{size:Ed,color:r.color.surface,strokeWidth:2})})}i(Mb,"SuccessFlash");function Sd({images:e,onPreview:t}){let r=F(),n=react.useMemo(()=>Pd(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsxRuntime.jsx(reactNative.View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:$(h.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsxRuntime.jsx(reactNative.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 reactNative.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:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...reactNative.StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:kb},successOverlay:{...reactNative.StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:xb},failedOverlay:{...reactNative.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=react.useMemo(()=>qe(e.registry.services.authFor(t)),[e,t,n]),[s,a]=react.useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},u=react.useRef(0),d=react.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]);react.useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=react.useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return react.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]=react.useState(null);if(react.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=react.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=react.useRef(c);p.current=c;let f=react.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]=react.useState(Ud),_=react.useRef(null),A=react.useRef({runtime:r,userRef:n,scopeEpoch:o});A.current={runtime:r,userRef:n,scopeEpoch:o};let k=react.useRef(c);k.current=c;let b=react.useRef(g);b.current=g;let R=react.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=react.useCallback(I=>R(I,null),[R]),V=react.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=>reactNative.Linking.openURL(e),"defaultOpenUrl");function yn(e={}){let{openUrl:t,...r}=e,n=react.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(),_=react.useMemo(()=>pv(S),[S]),A=react.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 jsxRuntime.jsx(reactNative.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:jsxRuntime.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 reactNative.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=react.useMemo(()=>bv(n),[n]),s=t-r*2,a=e===null?null:Gd(e),l=hv(s);return jsxRuntime.jsx(un,{size:t,strokeWidth:r,color:n.color.success,children:jsxRuntime.jsx(reactNative.View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsxRuntime.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 reactNative.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=react.useMemo(()=>wv(a),[a]);return e?jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxRuntime.jsxs(reactNative.View,{style:l.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:reactNative.StyleSheet.absoluteFill,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsxRuntime.jsx(reactNative.View,{style:l.backdrop})}),jsxRuntime.jsxs(reactNative.View,{style:l.panel,accessibilityViewIsModal:true,children:[jsxRuntime.jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsxRuntime.jsx(reactNative.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 jsxRuntime.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:[jsxRuntime.jsx(vr,{pet:u,size:bi,ringStroke:Yd}),jsxRuntime.jsxs(reactNative.View,{style:l.copy,children:[jsxRuntime.jsx(C,{style:l.name,numberOfLines:1,children:c}),jsxRuntime.jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsxRuntime.jsx(Xe,{size:kv,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxRuntime.jsxs(H,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsxRuntime.jsx(reactNative.View,{style:l.addDisc,children:jsxRuntime.jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsxRuntime.jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsxRuntime.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 reactNative.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=react.useMemo(()=>Bv(l),[l]),[d,c]=react.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 jsxRuntime.jsxs(reactNative.View,{style:u.row,children:[jsxRuntime.jsxs(H,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsxRuntime.jsx(Uu,{size:Fv,color:l.color.text.primary,strokeWidth:2}),r?jsxRuntime.jsx(reactNative.View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsxRuntime.jsx(reactNative.View,{style:u.center,pointerEvents:"box-none",children:jsxRuntime.jsx(Vv,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsxRuntime.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}),jsxRuntime.jsx(reactNative.View,{style:u.right,children:f?jsxRuntime.jsxs(H,{accessibilityRole:"button",accessibilityLabel:$(h.switchActivePet,{name:g}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsxRuntime.jsx(vr,{pet:p,size:Ct,ringStroke:hn}),jsxRuntime.jsx(reactNative.View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsxRuntime.jsx(Bu,{size:Dv,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsxRuntime.jsx(un,{size:Ct,strokeWidth:hn,color:l.color.success,children:jsxRuntime.jsx(reactNative.View,{style:u.placeholderDisc})})}):jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:g,children:jsxRuntime.jsx(vr,{pet:p,size:Ct,ringStroke:hn})})}),jsxRuntime.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]=react.useState(null);return e===null||n===e?null:jsxRuntime.jsx(reactNative.View,{style:r.logoBar,children:jsxRuntime.jsx(reactNative.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 reactNative.StyleSheet.create({vetEntry:{minHeight:Ov,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:reactNative.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:{...reactNative.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=react.useMemo(()=>Yv(n),[n]),[s,a]=react.useState(null),[l,u]=react.useState(""),[d,c]=react.useState(false),[p,f]=react.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 jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:g,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:reactNative.Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:o.scrim,onPress:g,accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y}),jsxRuntime.jsxs(reactNative.View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsxRuntime.jsx(reactNative.View,{style:o.handle}),jsxRuntime.jsxs(reactNative.View,{style:o.header,children:[jsxRuntime.jsx(reactNative.View,{style:o.iconBadge,children:jsxRuntime.jsx(ln,{size:qv,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxRuntime.jsxs(reactNative.View,{style:o.headerText,children:[jsxRuntime.jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsxRuntime.jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsxRuntime.jsx(reactNative.View,{style:o.options,children:No.map(S=>{let _=s===S.key;return jsxRuntime.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:[jsxRuntime.jsx(C,{style:[o.optionLabel,_?o.optionLabelSelected:null],children:S.label}),jsxRuntime.jsx(reactNative.View,{style:[o.radio,_?o.radioSelected:null],children:_?jsxRuntime.jsx(Xe,{size:$v,color:n.color.surface,strokeWidth:2}):null})]},S.key)})}),jsxRuntime.jsxs(reactNative.View,{style:o.inputWrap,children:[jsxRuntime.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?jsxRuntime.jsx(C,{tier:"compact",style:[o.counter,y?o.counterOver:null],children:`${[...l].length}/${It}`}):null]}),p?jsxRuntime.jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxRuntime.jsxs(reactNative.View,{style:o.actions,children:[jsxRuntime.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:jsxRuntime.jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:g,style:o.skip,children:jsxRuntime.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 reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...reactNative.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:reactNative.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:reactNative.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]=react.useState(t.open),o=react.useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsxRuntime.jsx(_C,{chat:e,history:t,onHidden:o}):null}i(sc,"HistoryDrawer");function _C({chat:e,history:t,onHidden:r}){let n=F(),o=react.useMemo(()=>IC(n),[n]),s=Q(),a=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:l}=reactNative.useWindowDimensions(),u=xC(l),d=t.open,c=react.useRef(null);c.current===null&&(c.current=new reactNative.Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;react.useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let S=reactNative.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?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,accessibilityLabel:J.loading,accessibilityState:{busy:true},children:[jsxRuntime.jsx(reactNative.ActivityIndicator,{color:n.color.onPrimary}),jsxRuntime.jsx(C,{style:o.emptyBody,children:J.loading})]}):g&&t.error!==null?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:J.loadFailed}),jsxRuntime.jsx(C,{style:o.emptyBody,children:t.error}),jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:J.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsxRuntime.jsx(C,{tier:"control",style:o.retryText,children:J.retry})})]}):jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?J.empty:J.noMatch}),jsxRuntime.jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?J.emptyBody:J.noMatchBody})]}),y=!t.searching&&t.loadingMore?jsxRuntime.jsx(reactNative.View,{style:o.loadMoreFooter,children:jsxRuntime.jsx(C,{style:o.loadMoreLabel,children:J.loadingMore})}):null;return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxRuntime.jsxs(reactNative.View,{style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:reactNative.StyleSheet.absoluteFill,onPress:t.close,accessibilityRole:"button",accessibilityLabel:J.closeA11y,children:jsxRuntime.jsx(reactNative.Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsxRuntime.jsx(reactNative.Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(cC,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:reactNative.Platform.OS==="ios"?"padding":"height",children:[jsxRuntime.jsxs(reactNative.View,{style:o.searchRow,children:[jsxRuntime.jsxs(reactNative.View,{style:o.searchPill,children:[jsxRuntime.jsx(Yu,{size:SC,color:n.color.text.muted,strokeWidth:1.5}),jsxRuntime.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"})]}),jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:J.newConversation,style:o.newButton,onPress:t.newConversation,children:jsxRuntime.jsx(Xu,{size:RC,color:n.color.text.primary,strokeWidth:1.5})})]}),jsxRuntime.jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:J.heading}),t.error!==null&&!g?jsxRuntime.jsx(reactNative.View,{style:o.errorCard,children:jsxRuntime.jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsxRuntime.jsx(reactNative.FlatList,{data:m,keyExtractor:S=>S.id,renderItem:({item:S})=>jsxRuntime.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 jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:Tu(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:jsxRuntime.jsxs(reactNative.View,{style:n.itemRow,children:[jsxRuntime.jsx(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:on(e.title)}),s?jsxRuntime.jsx(reactNative.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 reactNative.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=react.useMemo(()=>zC(s),[s]),l=Q(),u=e.tier,d=e.source;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(ei,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxRuntime.jsxs(reactNative.View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsxRuntime.jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsxRuntime.jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsxRuntime.jsx(gt,{render:()=>r(u.level),fallback:jsxRuntime.jsx(uc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsxRuntime.jsx(uc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:UC,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsxRuntime.jsx(ht,{size:NC,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsxRuntime.jsx(ei,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:BC,onPress:e.expand,children:jsxRuntime.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 jsxRuntime.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:[jsxRuntime.jsx(Qu,{size:HC,color:d,strokeWidth:1.5}),jsxRuntime.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 reactNative.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=react.useCallback(n=>t.setActivePet(n),[t]);return react.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=react.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 reactNative.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:reactNative.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:reactNative.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:reactNative.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]=react.useState(null),[o,s]=react.useState(null),[a,l]=react.useState(null),u=react.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=react.useMemo(()=>vE(a),[a]),u=Sc(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable;return jsxRuntime.jsxs(reactNative.View,{style:l.card,accessibilityLabel:Je.eyebrow,children:[jsxRuntime.jsx(C,{tier:"compact",style:l.eyebrow,children:Je.eyebrow}),jsxRuntime.jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsxRuntime.jsx(reactNative.View,{style:[l.row,u.pending?l.rowPending:null],children:Rc.map(({answer:p,label:f})=>{let m=(u.pending??u.answer)===p;return jsxRuntime.jsx(reactNative.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:jsxRuntime.jsx(C,{tier:"control",style:[l.pillLabel,m?l.pillLabelSelected:null],children:f})},p)})}):null,u.answer!==null?jsxRuntime.jsx(C,{style:l.logged,children:Je.logged}):null,u.escalated?o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Je.findVet,style:l.findVet,children:jsxRuntime.jsx(C,{tier:"control",style:l.findVetLabel,children:Je.findVet})}):n?jsxRuntime.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?jsxRuntime.jsx(C,{style:l.resolution,children:t.resolutionText}):null,u.error?jsxRuntime.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 reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.surface,borderWidth:reactNative.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=react.useMemo(()=>HE(t),[t]),n=react.useMemo(()=>Ic(e),[e]),[o,s]=react.useState(false);if(n.length===0)return null;let a=n.length;return jsxRuntime.jsxs(reactNative.View,{style:r.block,children:[jsxRuntime.jsxs(H,{accessibilityRole:"button",accessibilityLabel:Ac(a,o),accessibilityState:{expanded:o},containerStyle:r.toggleSlot,style:r.togglePill,onPress:()=>s(l=>!l),children:[jsxRuntime.jsx(zu,{size:Lc,color:t.color.brandInk,strokeWidth:1.5}),jsxRuntime.jsx(C,{tier:"compact",style:r.toggleLabel,children:Oi(a)}),jsxRuntime.jsx(Hu,{size:Lc,color:t.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?jsxRuntime.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 jsxRuntime.jsx(reactNative.Animated.View,{style:n,children:jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(o=>jsxRuntime.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=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:t.cardHeader,children:[jsxRuntime.jsx(reactNative.View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsxRuntime.jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsxRuntime.jsx(ju,{size:FE,color:r.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsxRuntime.jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsxRuntime.jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null){let a=e.url;return jsxRuntime.jsx(H,{accessibilityRole:"link",accessibilityLabel:n,style:t.card,onPress:()=>{reactNative.Linking.openURL(a);},children:s})}return jsxRuntime.jsx(reactNative.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 reactNative.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=react.useMemo(()=>XE(s),[s]),l=Q(),u=e.role==="user",d=react.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]=react.useState(false),g=react.useRef(null);react.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:jsxRuntime.jsxs(reactNative.View,{style:a.wrap,children:[jsxRuntime.jsxs(reactNative.View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsxRuntime.jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:qE,onPress:x,style:a.iconHit,children:f?jsxRuntime.jsx(Xe,{size:Rr,color:s.color.success,strokeWidth:2}):jsxRuntime.jsx(Wu,{size:Rr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Jl.map(({sentiment:y,label:S})=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:S,accessibilityState:{selected:r===y},hitSlop:$E,onPress:()=>n?.(y),style:a.iconHit,children:jsxRuntime.jsx(ln,{size:Rr,color:s.color.sentiment[y],active:r===y,rotate:YE[y],strokeWidth:1.5})},y)):null]}),o?jsxRuntime.jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(zc,"MessageFooter");function XE(e){let t=e.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...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=react.useMemo(()=>uR(s),[s]),l=react.useMemo(()=>Gc(e),[e]),u=Wc(e);return jsxRuntime.jsxs(reactNative.View,{style:a.block,children:[jsxRuntime.jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsxRuntime.jsx(reactNative.View,{style:a.list,children:l.map((d,c)=>jsxRuntime.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?jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:$c,style:[l.chip,c],onPress:()=>{X(s,r);},children:jsxRuntime.jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.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})}):jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:$c,style:[l.chip,c],onPress:()=>o(e.label),children:jsxRuntime.jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(lR,"Chip");function uR(e){let t=e.color;return reactNative.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 jsxRuntime.jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsxRuntime.jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsxRuntime.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=react.useMemo(()=>vR(e),[e]),r=!e.motion.reducedMotion;return jsxRuntime.jsx(reactNative.View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:hR.map(n=>r?jsxRuntime.jsx(bR,{index:n,style:t.dot},n):jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotStatic]},n))})}i(ip,"TypingIndicator");function bR({index:e,style:t}){let r=react.useRef(new reactNative.Animated.Value(0)).current;react.useEffect(()=>{let s=reactNative.Animated.sequence([reactNative.Animated.delay(e*yR),reactNative.Animated.loop(reactNative.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 jsxRuntime.jsx(reactNative.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 reactNative.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:reactNative.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?jsxRuntime.jsx(gt,{render:r.renderPending,fallback:jsxRuntime.jsx(sp,{})}):jsxRuntime.jsx(sp,{});case "empty":return jsxRuntime.jsx(PR,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsxRuntime.jsx(kR,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsxRuntime.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]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>n(true),hc);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx(reactNative.View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsxRuntime.jsx(reactNative.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 jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsxRuntime.jsx(Yc,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsxRuntime.jsx(dp,{prompts:r,onSelectPrompt:n})]})}i(PR,"EmptyState");function dp({prompts:e,onSelectPrompt:t}){let{styles:r}=Ce();return e.length===0?null:jsxRuntime.jsxs(reactNative.View,{style:r.followUps,children:[jsxRuntime.jsx(C,{tier:"compact",style:r.followUpsLabel,accessibilityRole:"header",children:h.followUps}),e.map((n,o)=>jsxRuntime.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 jsxRuntime.jsx(reactNative.Animated.View,{style:s,children:jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,style:[n.followUpRow,t>0?n.followUpDivider:null],children:jsxRuntime.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 jsxRuntime.jsxs(reactNative.View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsxRuntime.jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsxRuntime.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 jsxRuntime.jsxs(reactNative.ScrollView,{style:_.list,contentContainerStyle:_.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(R=>R.checkin?jsxRuntime.jsx(_c,{message:R,checkin:R.checkin,onAnswer:o,petRef:x,onFindVet:y,vet:S},R.id):jsxRuntime.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?jsxRuntime.jsx(C,{tier:"compact",style:_.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,k?jsxRuntime.jsx(ip,{}):null,p!==null?jsxRuntime.jsx(_R,{notice:p,onRetry:m,onStartNew:g}):null,n?null:jsxRuntime.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 jsxRuntime.jsxs(reactNative.View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsxRuntime.jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsxRuntime.jsx(reactNative.Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Bt,style:n.turnNoticeAction,children:jsxRuntime.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=react.useCallback(y=>o(e,y),[o,e]),x=e.pending!==true;return jsxRuntime.jsxs(reactNative.Animated.View,{style:[u.rowBlock,f?u.rowBlockUser:u.rowBlockAssistant,c],children:[jsxRuntime.jsx(reactNative.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:jsxRuntime.jsxs(reactNative.View,{style:[u.bubble,f?u.bubbleUser:u.bubbleAssistant,e.pending?u.bubblePending:null],children:[f&&a.length>0?jsxRuntime.jsx(Sd,{images:a,onPreview:y=>l({uri:y.uri,label:y.filename})}):null,jsxRuntime.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?jsxRuntime.jsx(Dc,{citations:e.citations}):null,x?jsxRuntime.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 jsxRuntime.jsx(Do,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsxRuntime.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=react.useMemo(()=>Mu(e,t),[e,t]),P=cr(R),V=Au(P),I=cc(),w=ku(P),T=reactNativeSafeAreaContext.useSafeAreaInsets(),B=Ou(P),K=react.useMemo(()=>l===void 0?void 0:()=>{X(l,"emergency");},[l]),W=react.useMemo(()=>S===void 0&&_===void 0?void 0:{returnTo:S,usState:_},[S,_]),ae=Pi(I.pets,P.petRef),me=react.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=react.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]=react.useState(null),mp=react.useCallback(()=>xt(null),[]),[Wt,An]=react.useState(null),[yp,Ni]=react.useState(null),_t=react.useRef(null);react.useEffect(()=>()=>{_t.current&&clearTimeout(_t.current);},[]);let Ui=react.useCallback(_e=>{Ni(String(_e)),_t.current&&clearTimeout(_t.current),_t.current=setTimeout(()=>{Ni(null),_t.current=null;},bc);},[]),gp=react.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=react.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=react.useCallback(()=>An(null),[]),vp=react.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 jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:[k.container,{paddingTop:T.top},r],behavior:reactNative.Platform.OS==="ios"?"padding":void 0,children:[jsxRuntime.jsx(Jd,{pets:I,petRef:P.petRef,historyUnread:Tr,onOpenHistory:w.show,onPetChange:s,onAddPet:p,vet:W}),c!==void 0?jsxRuntime.jsx(UR,{petRef:e??null,pet:c,onRegistered:I.refresh}):null,jsxRuntime.jsx(dc,{surface:G,petRef:P.petRef,renderVetAction:u,onFindVet:l,vet:W}),jsxRuntime.jsx(reactNative.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?jsxRuntime.jsx(VR,{...Vi,attachments:d}):jsxRuntime.jsx(fp,{...Vi,attachments:null}),jsxRuntime.jsx(Nu,{}),A.meta.hidePoweredBy?null:jsxRuntime.jsx(C,{tier:"compact",style:k.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsxRuntime.jsx(sc,{chat:P,history:w}),jsxRuntime.jsx(oc,{visible:Wt!==null,onSubmit:hp,onSkip:bp}),jsxRuntime.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:jsxRuntime.jsxs(reactNative.View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsxRuntime.jsx(reactNative.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:Bt,children:jsxRuntime.jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(UR,"PetSetupNotice");function VR({attachments:e,...t}){let r=react.useMemo(()=>Td(),[]),n=rn({maxPerMessage:e.maxPerMessage??DR,transport:r}),o=react.useMemo(()=>({state:n,sources:e.sources??LR,pick:e.pick}),[n,e.sources,e.pick]);return jsxRuntime.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]=react.useState(false),[y,S]=react.useState(false);react.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=react.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=react.useCallback(()=>{t();},[t]),I=react.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=react.useMemo(()=>[...f].length>At,[f])||b,B=o!==null&&R.length>=o.state.maxPerMessage,K=d.slots.sendButton?.textColor??d.color.brandInk;return jsxRuntime.jsxs(reactNative.View,{style:c.composerOuter,children:[o!==null&&g?jsxRuntime.jsx(cd,{sources:o.sources,full:B,onPick:I,onClose:()=>x(false)}):null,jsxRuntime.jsxs(reactNative.View,{style:c.composer,children:[o!==null?jsxRuntime.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,jsxRuntime.jsxs(reactNative.View,{style:c.composerRow,children:[o!==null?jsxRuntime.jsx(reactNative.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:jsxRuntime.jsx(Ku,{size:Ec,color:B?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsxRuntime.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?jsxRuntime.jsx(reactNative.Pressable,{onPress:V,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:Bt,style:c.sendControl,children:jsxRuntime.jsx(reactNative.View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsxRuntime.jsx(Ju,{size:Cc,color:K,testID:"everfur-stop-glyph"})})}):jsxRuntime.jsx(reactNative.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:jsxRuntime.jsx(reactNative.View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsxRuntime.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=react.useMemo(()=>qe(t.registry.services.authFor(r)),[t,r,n]),s=react.useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=react.useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=react.useRef(0),c=react.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 react.useEffect(()=>(c(),()=>{d.current+=1;}),[c]),react.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 react.createElement(Jr,{clientTheme:e.clientTheme??null,seams:tn,children:e.children})}i(YR,"EverfurThemeProvider");exports.CapabilityGate=Do;exports.EverfurChat=pp;exports.EverfurConfigError=Z;exports.EverfurProvider=Wg;exports.EverfurThemeProvider=YR;exports.EverfurThrownError=xr;exports.THEME_SLOT_KEYS=cy;exports.THEME_SLOT_NAMES=pt;exports.canonicalPetSpecies=nr;exports.categoryFor=Fn;exports.conversationId=_p;exports.createRnRecordsUploadTransport=jp;exports.face=E;exports.isErr=Sp;exports.isOk=Rp;exports.isRetryableCode=Mn;exports.petRef=kp;exports.previewTheme=By;exports.unwrap=Pp;exports.useCapability=Ft;exports.useChatAttachments=rn;exports.useEverfur=Il;exports.useEverfurChat=cr;exports.useEverfurPetProfile=qR;exports.useEverfurPets=mn;exports.useEverfurTheme=F;exports.userFacingError=wt;exports.userRef=xp;
11
+ `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),em(r.source,l)}i(Jf,"eventSourceByteSource");async function*em(e,t){try{yield*e;}finally{t();}}i(em,"sourceWithCleanup");function tm(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(tm,"createByteQueue");async function rm(e,t){let r=t.fetchImpl??Ns(),n=Us(t.config.apiBaseUrl,e.path,e.query),o=Vs(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=lm(Zf),a=um(s.signal,e.signal),l;try{l=await r(n,Hs({...e,signal:a},o));}catch(d){return v(qn(d))}finally{s.cancel();}let u=await Bs(l);return l.ok?M(u):v(im(l.status,u,Ls(l)))}i(rm,"requestJson");function Ms(e){return {request:i(t=>rm(t,e),"request"),stream:i((t,r)=>nm(am(t,r),e),"stream")}}i(Ms,"createHttpTransport");async function*nm(e,t){let r=Us(t.config.apiBaseUrl,e.path,e.query),n=Vs(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,om(e,n));yield*Ur(Jf(l),()=>sm(l));return}let o=t.fetchImpl??Ns(),s;try{s=await o(r,Hs(e,n));}catch(l){yield As("",true,Gs(l));return}let a=Ls(s);if(!s.ok){let l=await Bs(s),u=zs(l)??Ds(s.status),d=Ws(l)||He(Ae(u));yield As(u,d,js(l),a);return}if(s.body){yield*Ur(Is(s.body),a);return}yield*Ur(Is(null),a);}i(nm,"streamFrames");function om(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(om,"buildEventSourceInit");function im(e,t,r){let n=zs(t),o=n?Ae(n):us(e),s=js(t);return D(o,{httpStatus:e,...Ws(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Os(t)?{reasonCode:Os(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(im,"errorFromResponse");function qn(e){return D("internalError",{retryable:true,wireMessage:Gs(e)})}i(qn,"networkError");function Ls(e){let t=e.headers.get(Fs);return typeof t=="string"&&t.length>0?t:null}i(Ls,"requestIdOf");function sm(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Fs);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(sm,"eventSourceRequestId");function Ds(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Ds,"statusToWireCode");function As(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(As,"syntheticErrorFrame");function Ns(){let e=globalThis.fetch;if(typeof e!="function")throw new Q("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Ns,"getGlobalFetch");function Us(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(Us,"buildUrl");function Vs(e,t,r,n){let o={...ws(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Vs,"mergeHeaders");function Hs(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Hs,"buildInit");function am(e,t){return e.signal?e:{...e,signal:t}}i(am,"withSignal");function lm(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(lm,"timeoutSignal");function um(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(um,"mergeAbortSignals");async function Bs(e){try{return await e.json()}catch{return null}}i(Bs,"safeJson");function Os(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Os,"extractReasonCode");function zs(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(zs,"extractWireCode");function js(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(js,"extractWireMessage");function Ws(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Ws,"extractRetryable");function Gs(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Gs,"describeCause");var dm=3e4,cm=zn*2,pm="idempotency-key",fm=new Set(["POST","PUT","PATCH","DELETE"]),mm=Object.freeze({onEvent(){}}),ym=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function gm(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(gm,"seededIdempotencyKey");function ke(e){let t=e.observer??mm,r=e.timers??ym,n=e.rng??Math.random,o=e.sleep??((f,m)=>wm(f,r,m)),s=e.maxAttempts??Yt,a=e.unaryTimeoutMs??dm,l=e.newIdempotencyKey??bm(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let k=y?.maxAttempts,g=Math.max(1,k??s),R=y?.idempotent??fm.has(m.method),w=y?.idempotencyKey===void 0?null:gm(y.idempotencyKey),_=R?w??l():null,x=hm(m,_),b=0;for(;;){let P=i(j=>Object.freeze({call:f,method:m.method,path:m.path,attempt:b,..._?{idempotencyKey:_}:{},...j}),"stamp");u(P({phase:"attempt"}));let L=xm(a,r),I=_m(L.signal,m.signal),S;try{S=await Rs({...x,signal:I.signal},e.auth);}catch(j){S=v(qn(j));}finally{I.dispose(),L.cancel();}if(S.ok)return u(P({phase:"settled",ok:true,reason:"ok"})),S;let O=S.error,T=Cm(O,b,{maxAttempts:g,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...k!==void 0?{perCallMaxAttempts:k}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:O.code,reason:T.reason,...O.httpStatus!==void 0?{httpStatus:O.httpStatus}:{},...O.requestId!==void 0?{requestId:O.requestId}:{}};if(!T.retry)return u(P({phase:"settled",...V})),v(O);if(u(P({phase:"retry",...V,delayMs:T.delayMs})),await o(T.delayMs,m.signal),m.signal?.aborted===true)return u(P({phase:"settled",...V,reason:"aborted"})),v(O);b+=1;}}i(d,"send");async function c(f){return Xt(f,await km(e.auth))}i(c,"authorize");async function*p(f,m,y){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,y);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(ke,"createRequestFunnel");function hm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==pm&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(hm,"assembleHeaders");function bm(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(bm,"defaultIdempotencyKeyFactory");var vm=10;function Cm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Em(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!He(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(vm,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=Rm(e,r.now);return u!==null?u>cm?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Dr(t,r.rng)}}i(Cm,"decideRetry");function Em(e){let t=e.code==="unknown"?Ae(Pm(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Em,"throttleKind");function Rm(e,t){let r=Sm(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(Rm,"retryOverrideMs");function Sm(e){for(let t of qs(e)){let r=t.resets_at,n=Tm(r);if(n!==null)return n}return null}i(Sm,"findResetsAt");function qs(e){if(!Ks(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Ks(n)&&t.push(n);}return t}i(qs,"candidateScopes");function Tm(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Tm,"parseInstantMs");function Pm(e){for(let t of qs(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Pm,"rawWireCode");function Ks(e){return typeof e=="object"&&e!==null}i(Ks,"isRecord");async function km(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(km,"resolveDeviceAuth");function xm(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(xm,"boundedSignal");function _m(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(_m,"mergeSignals");function wm(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(wm,"delayAbortable");var Vr=Object.freeze(["better","same","worse"]),Yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $s(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i($s,"invalid");function $n(){return v(D("internalError",{retryable:false}))}i($n,"malformed");function Ys(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Re(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Ys,"petPath");var Be=i(e=>typeof e=="string"?e:null,"str"),Xs=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function Qs(e){if(typeof e!="object"||e===null)return null;let t=e,r=Be(t.case_id),n=Be(t.status);if(r===null||n===null)return null;let o=Be(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Be(t.body_location),lastResponse:o!==null&&Vr.includes(o)?o:null,checkInDueAt:Be(t.check_in_due_at),openedAt:Be(t.opened_at),resolvedAt:Be(t.resolved_at),resolutionText:Be(t.resolution_text),checkinAskCount:Xs(t.checkin_ask_count),checkinAnswerCount:Xs(t.checkin_answer_count)})}i(Qs,"caseFromWire");function Zs(e){return {async list(t,r){let n=Ys(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return $n();let a=s.map(Qs);return a.every(l=>l!==null)?M(Object.freeze(a)):$n()},async checkin(t,r,n,o){let s=Ys(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!Yn.test(r))return $s("case_id must be a UUID");if(!Vr.includes(n))return $s("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=Qs(l.case);return u===null?$n():M(Object.freeze({case:u,ctaDeepLink:Be(l.cta_deep_link)}))}}}i(Zs,"createCasesRepositoryOver");var Js=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ea=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Br(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(Br,"delayAbortable");function zr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(zr,"mergeSignals");var Xn=class Xn{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?zr(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(Xn,"MediaStore");var Hr=Xn;function Zn(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Zn,"makeUser");function Jn(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(Jn,"makeAssistant");function Jt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(Jt,"stripPending");function ta(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(ta,"appendText");function eo(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(eo,"finalizeAssistant");function ra(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(ra,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function to(e){let t=Ae(e.code);return D(t,{retryable:e.retryable||Lr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(to,"errorFromFrame");function Oe(e){return pe({code:Im(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Oe,"synthErrorFrame");function Im(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Xe(e)}}i(Im,"canonicalWireCode");function na(e){let t=Array.isArray(e)?e:Qn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!Qn(n))continue;let o=Zt(n.category)??Zt(n.title)??"",s=Am(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(na,"parsePromptCategories");function ro(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(ro,"flattenPrompts");function Qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Qn,"isPlainObject");function Zt(e){return typeof e=="string"?e:null}i(Zt,"asStr");function Am(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Qn(r)){let n=Zt(r.text)??Zt(r.prompt)??Zt(r.title);n!==null&&t.push(n);}return t}i(Am,"asPromptTextList");function oa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(oa,"defaultIdFactory");function ia(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(ia,"defaultIdempotencyFactory");var aa={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*la(e,t,r,n){let o=e[Symbol.asyncIterator](),s=sa(t.overallMs,n),a=sa(t.idleMs,n),l=Mm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Fm();return}if(d.tag==="idle"||d.tag==="overall"){yield Om();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(la,"withWatchdog");function Om(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Om,"synthTimeoutFrame");function Fm(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Fm,"synthStreamErrorFrame");function sa(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(sa,"deadline");function Mm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Mm,"abortPromise");var Lm="checkin",Dm=/^\d{4}-\d{2}-\d{2}$/,jr="watching";function ua(e){return e.status!=null&&e.status!==jr}i(ua,"isCheckinSettled");function da(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(da,"isLiveAskAnswered");function no(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Lm||n===void 0||o===void 0||!Yn.test(n)||!Dm.test(o)?null:{caseId:n,dueDay:o}}i(no,"parseCheckinOrigin");function ca(e){return no(e)?.caseId??null}i(ca,"parseCheckinOriginRef");function oo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Re(o))return v(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(oo,"historyQuery");function rr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(rr,"validConversationId");function tr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(tr,"object");function pa(e){return e==null||typeof e=="string"&&e.length>0&&!Re(e)}i(pa,"cursor");function er(){return v(D("internalError",{retryable:false}))}i(er,"malformed");function fa(e){let t=tr(e);if(!t||!Array.isArray(t.conversations)||!pa(t.next_cursor))return er();let r=[];for(let n of t.conversations){let o=tr(n);if(!o||typeof o.conversation_id!="string"||!rr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return er();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return er();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return M(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(fa,"mapConversationPage");function ma(e){let t=tr(e);if(!t||!Array.isArray(t.messages)||!pa(t.next_cursor))return er();let r=[],n=new Set;for(let o of t.messages){let s=tr(o);if(!s||typeof s.message_id!="string"||!rr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return er();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?ca(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Nm(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Um(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return M(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ma,"mapMessagePage");function Nm(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Nm,"normalizeUrgency");function Um(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=tr(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(Um,"historyCitations");var io=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),At=4e3;var Ot=4e3;function ya(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(ya,"validateImageKeys");function ao(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Ot?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ot}`)}:null}i(ao,"validateMessageText");function ga(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(ga,"urgencyTier");async function*nr(e){yield e;}i(nr,"singleFrameStream");async function*ha(){}i(ha,"emptyStream");var Vm=6e4,Hm=18e4,Bm=24,zm=512,jm=false;function ba(e){return new lo(e)}i(ba,"createChatController");var uo=class uo extends Hr{constructor(r){super(ra({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??ke({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Zs(this.funnel),this.telemetry=r.telemetry??Nr,this.errorPolicy=r.errorPolicy??ps,this.timers=r.timers??aa,this.rng=r.rng??Math.random,this.newId=r.newId??oa(),this.makeIdempotencyKey=r.makeIdempotencyKey??ia(),this.budget={idleMs:r.budget?.idleMs??Vm,overallMs:r.budget?.overallMs??Hm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):nr(Oe(u))}let a=ao(r)??ya(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):nr(Oe(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return nr(Oe(U("accessDenied",false)));let o=ao(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),nr(Oe(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):ha()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Zn(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?Jt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(ro(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=oo(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=fa(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?M(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return M(null);let l=await this.resumeConversation(a.id);return l.ok?M(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return M(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),M(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Re(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!io.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${io.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>At)return v(U("validationFailed",false,`notes is over ${At} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return M(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!rr(r))return v(U("validationFailed",false));let o=oo(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?ma(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!rr(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),M(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===jr).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId),f=c.openedAt??p?.openedAt??null,m=s.has(c.caseId),y=p!==void 0&&(!m||da({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?jr:p?.status??"resolved",answer:c.answer??y,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return M(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),M(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return M(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),M(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Oe(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return M(n);let o=this.snapshot.conversationId;return o!==null?M(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):M(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Re(o))return v(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?M(na(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=zr(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Zn(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let g=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;g.ok&&this.snapshot.conversationId===null&&this.adoptConversation(g.value);}if(u&&this.snapshot.conversationId===null){let g=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!g.ok){yield*this.emitTerminal(r,g.error,Oe(g.error));return}this.adoptConversation(g.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let g=U("internalError",!0);yield*this.emitTerminal(r,g,Oe(g));return}this.clearAssistantInProgress(r);let p=new AbortController,f=zr(o.signal,p.signal),m=null;try{let g;try{g=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let w=this.authRejected();yield*this.emitTerminal(r,w,Oe(w));return}if(o.signal.aborted||!this.alive(o.epoch))return;let R=this.funnel.stream("chat.send",g,f);for await(let w of la(R,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(w.kind==="error"&&w.terminal){m=w;break}if(this.applyFrame(w,r),yield w,w.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let g=U("streamIncomplete",!0);yield*this.emitTerminal(r,g,Oe(g));return}let y=Ae(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let g=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!g){let R=this.authRejected();yield*this.emitTerminal(r,R,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let g=this.authRejected();yield*this.emitTerminal(r,g,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,to(m),m);return}if(ds(y)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let k=m.retryable&&Lr(y,!0);if(jm&&k&&s+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,to(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Xe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?Jt(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,Jn(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=zm){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Bm);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?ta(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?eo(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?Jt(d):d),eo(Jn(l,"",this.stamp()),r)];}let a=ro([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=ga(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?Jt(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(uo,"ChatControllerImpl");var lo=uo;async function Ea(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(x=>x.ok?M(o):x):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),k=null;if(m.ok)k=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let x=m.error;c=x,va(x)?(l=true,d=x):(Ca(x)&&(a=true),u=true);}let g=[];y.ok?g=y.value:R(y.error);function R(x){va(x)?(l=true,d===null&&(d=x)):Ca(x)&&(a=true);}i(R,"recordAuthSignals");let w=d!==null?d.displayMessage:null;return Object.freeze({conversationId:k,petRef:n,suggestedPrompts:g,error:w,warning:w===null&&k===null&&u?Wm:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Ea,"bootstrapChat");var Wm="Chat is ready. Your first message will start the conversation.";function va(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(va,"isUnauthorized");function Ca(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ca,"isForbidden");var co=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ra(e){return e!==co}i(Ra,"isUploadTransportAvailable");var Gm=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Wr=10*1024*1024,Gr=5,or=120,Km="/widget/v1/uploads/initiate";function qm(e){return typeof e=="string"&&Gm.includes(e.trim().toLowerCase())}i(qm,"isAttachmentMime");function po(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=or)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,or);let n=t.slice(r);return n.length>=or?t.slice(0,or):`${t.slice(0,r).slice(0,or-n.length)}${n}`}i(po,"sanitizeFilename");function fo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(fo,"formatBytes");var ir=i(e=>Object.freeze({ok:true,value:e}),"ok"),xe=i(e=>Object.freeze({ok:false,error:e}),"err");function oe(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(oe,"failure");function $m(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i($m,"attachmentSize");function Ym(e){let t=po(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!qm(r))return xe(oe("unsupported_type",false,t));let n=$m(e);return n===null?xe(oe("unknown",false,t)):n>Wr?xe(oe("too_large",false,t,{sizeBytes:n})):ir(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Ym,"validateAttachment");function Xm(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),a=r(t.s3_key);if(o===null||s===null||a===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Wr,s3_key:a,purpose:r(t.purpose)})}i(Xm,"parsePolicy");function Qm(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return oe("quota_exceeded",false,t,{cause:e});case "rateLimited":return oe("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return oe("idempotency_conflict",true,t,{cause:e});case "validationFailed":return oe("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return oe("network",true,t,{cause:e});default:return r===429?oe("rate_limited",true,t,{cause:e}):r===503?oe("network",true,t,{cause:e}):r===void 0?oe("network",true,t,{cause:e}):oe("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Qm,"initiateFailure");async function Zm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Km,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return xe(Qm(n.error,t.filename));let o=Xm(n.value);return o===null?xe(oe("server",false,t.filename)):ir(o)}i(Zm,"initiateAttachmentUpload");async function Jm(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return xe(oe("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),ir(void 0)}catch{return o()?xe(oe("cancelled",true,r.filename)):xe(oe("server",true,r.filename))}}i(Jm,"uploadAttachmentBytes");var ey=2,ty=3,ry=Object.freeze([1e3,2e3,4e3]),Sa=0;function ny(){return Sa+=1,`attachment-${Sa}`}i(ny,"defaultNewId");function Ta(e){let t=Math.max(1,e.concurrency??ey),r=Math.max(1,e.maxAttempts??ty),n=e.backoffMs??ry,o=Math.max(1,e.maxPerMessage??Gr),s=e.timers??ea,a=e.newId??ny,l=Ra(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,k=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let P=u.get(b);return P===void 0?[]:[P.state]}))});for(let b of f)b();},"publish"),g=i((b,P)=>{b.state=Object.freeze({...b.state,...P}),k();},"patch"),R=i(()=>{for(;!y&&p.size<t&&c.length>0;){let b=c.shift(),P=u.get(b);P!==void 0&&(p.add(b),w(P).finally(()=>{p.delete(b),R();}));}},"pump"),w=i(async b=>{let{attachment:P}=b;for(;b.attempts<r;){if(y||b.controller.signal.aborted)return;b.attempts+=1;let L=b.controller.signal;g(b,{status:"uploading",error:null,progress:0});let I=await Zm(e.funnel,P,{signal:L});if(y||L.aborted)return;let S;if(!I.ok)S=xe(I.error);else {let j=await Jm(e.transport,I.value,P,{signal:L,onProgress:i(G=>{!L.aborted&&b.state.status==="uploading"&&g(b,{progress:oy(G)});},"onProgress")});if(y||L.aborted)return;S=j.ok?ir(I.value.s3_key):xe(j.error);}if(S.ok){g(b,{status:"uploaded",s3Key:S.value,error:null,progress:1});return}let O=S.error,T=O.retryable&&b.attempts<r;if(g(b,{status:T?"uploading":"failed",error:O,progress:0}),!T)return;let V=n[Math.min(b.attempts-1,n.length-1)]??0;await Br(V,L,s);}},"run"),_=i(b=>{c.push(b.state.id),R();},"enqueue"),x={available:l,subscribe(b){return f.add(b),()=>{f.delete(b);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(b=>b.status==="uploading")},get s3Keys(){return m.attachments.flatMap(b=>b.status==="uploaded"&&b.s3Key!==null?[b.s3Key]:[])},add(b){let P=Ym(b);if(!P.ok)return P;if(y||d.length>=o)return xe(oe("too_many",false,P.value.filename));let L=a(),I={attachment:P.value,controller:new AbortController,attempts:0,state:Object.freeze({id:L,filename:P.value.filename,previewUri:b.uri,contentType:P.value.contentType,sizeBytes:P.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(L,I),d.push(L),k(),_(I),ir(I.state)},retry(b){let P=u.get(b);P===void 0||y||P.state.status!=="failed"||(P.controller=new AbortController,P.attempts=0,g(P,{status:"uploading",error:null,progress:0,s3Key:null}),_(P));},remove(b){let P=u.get(b);if(P===void 0)return;P.controller.abort(),u.delete(b);let L=d.indexOf(b);L>=0&&d.splice(L,1);let I=c.indexOf(b);I>=0&&c.splice(I,1),k();},clear(){for(let b of [...d])x.remove(b);},dispose(){y=true;for(let b of u.values())b.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return x}i(Ta,"createAttachmentQueue");function oy(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(oy,"clamp");var Pa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function sr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Pa,t)?Pa[t]:null}i(sr,"canonicalPetSpecies");var ka=50,iy=128,mo=120,xa=120,sy=2e3,_a=120,ay=80,Aa=new Set(["male","female","unknown"]),Oa=new Set(["day","month","year"]),Fa=new Set(["low","medium","high","athletic"]),Ma=new Set(["indoor","outdoor","both"]),La=new Set(["mild","moderate","severe"]),ly=/^(\d{4})-(\d{2})-(\d{2})$/,Da=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],Na=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Da,...Na].map(([e])=>e));function uy(e){let t=ly.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(uy,"isRealDate");var lr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),dy=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),qr=i((e,t)=>typeof t=="string"&&uy(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Fe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Re(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=it(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),cy={sex:lr(Aa),spayedNeutered:dy,birthDate:qr,birthDatePrecision:lr(Oa),activityLevel:lr(Fa),indoorOutdoor:lr(Ma),foodBrand:Fe(_a),foodType:Fe(_a),microchipId:Fe(ay)},yo=["ref","ref",false,Fe(iy,{required:true,trimmed:true})],go=["notes","notes",false,Fe(sy,{trimmed:true})],wa=[yo,["name","name",true,Fe(mo,{required:true,trimmed:true})],["dose","dose",false,Fe(xa,{trimmed:true})],["frequency","frequency",false,Fe(xa,{trimmed:true})],["startDate","start_date",false,qr],["endDate","end_date",false,qr],go],py={allergies:[yo,["allergen","allergen",true,Fe(mo,{required:true,trimmed:true})],["severity","severity",false,lr(La)],go],medications:wa,supplements:wa,conditions:[yo,["conditionName","condition_name",true,Fe(mo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,qr],go]};function fy(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[u,d,c,p]of py[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};s[d]=f;}let a=s.start_date,l=s.end_date;return typeof a=="string"&&typeof l=="string"&&l<a?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(fy,"itemToWire");function my(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>ka)return {error:`${e} has ${t.length} items; the server accepts at most ${ka}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=fy(e,o,t[o]);if("error"in s)return s;let a=s.item.ref;if(typeof a=="string"){let l=a.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(s.item);}return {items:r}}i(my,"listToWire");function Ua(e,t){let r=e,n={};for(let[a,l]of Da){let u=r[a];if(u!==void 0){if(u!==null){let d=cy[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[a,l]of Na){let u=r[a];if(u===void 0)continue;let d=my(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&sr(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Ua,"petHealthToWire");var ee=i(e=>typeof e=="string"?e:null,"str"),ar=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),yy=i(e=>typeof e=="boolean"?e:null,"bool");function Kr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Kr,"itemsFromWire");function Ia(e){let t=ee(e.name);return t===null||t.length===0?null:Object.freeze({ref:ee(e.ref),name:t,dose:ee(e.dose),frequency:ee(e.frequency),startDate:ee(e.start_date),endDate:ee(e.end_date),notes:ee(e.notes)})}i(Ia,"medicationFromWire");function Va(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ar(Aa,e.sex),spayedNeutered:yy(e.spayed_neutered),birthDate:ee(e.birth_date),birthDatePrecision:ar(Oa,e.birth_date_precision),activityLevel:ar(Fa,e.activity_level),indoorOutdoor:ar(Ma,e.indoor_outdoor),foodBrand:ee(e.food_brand),foodType:ee(e.food_type),microchipId:ee(e.microchip_id),allergies:Kr(e.allergies,r=>{let n=ee(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),allergen:n,severity:ar(La,r.severity),notes:ee(r.notes)})}),medications:Kr(e.medications,Ia),supplements:Kr(e.supplements,Ia),conditions:Kr(e.conditions,r=>{let n=ee(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),conditionName:n,diagnosedDate:ee(r.diagnosed_date),notes:ee(r.notes)})})})}i(Va,"petHealthFromWire");var za=100,ja=50,Wa=100,Ga=50,Ka=500,gy=128,hy=6e4;function Le(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Le,"invalid");function st(e,t,r){if(typeof t!="string")return Le(`${e} must be a string`);let n=it(t);return n<=r?null:Le(`${e} is ${n} characters; the server accepts at most ${r}`)}i(st,"checkString");function $r(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Le(`${e} must be a finite number between 0 and ${r}`)}i($r,"outOfRange");function Ha(e,t){if(typeof e!="string")return Le("pet_ref must be a string");if(e.trim().length===0)return Le("pet_ref must not be blank");if(Re(e))return Le("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Le("profile must be an object");let r=[st("pet_ref",e,gy)];return t?.name!==void 0&&r.push(st("name",t.name,za)),t?.species!==void 0&&r.push(st("species",t.species,ja)),t?.breed!==void 0&&r.push(st("breed",t.breed,Wa)),t?.ageYears!==void 0&&r.push($r("age_years",t.ageYears,Ga)),t?.weightKg!==void 0&&r.push($r("weight_kg",t.weightKg,Ka)),r.find(n=>n!==null)??null}i(Ha,"validate");function qa(e,t){let r=Ua(e,t);return "error"in r?{error:Le(r.error)}:r}i(qa,"healthToWire");function by(e){if(typeof e!="object"||e===null)return {error:Le("patch must be an object")};let t=e,r=[["name","name",s=>st("name",s,za)],["species","species",s=>st("species",s,ja)],["breed","breed",s=>st("breed",s,Wa)],["ageYears","age_years",s=>$r("age_years",s,Ga)],["weightKg","weight_kg",s=>$r("weight_kg",s,Ka)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=qa(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Le("patch must change at least one field")}:{body:n})}i(by,"patchToWire");function vy(e){if(e==null)return {body:{}};let t=qa(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(vy,"toWire");var Me=i(e=>typeof e=="string"?e:null,"str"),Yr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ba(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Me(r.pet_ref)??t,name:Me(r.name),species:Me(r.species),breed:Me(r.breed),ageYears:Yr(r.age_years),weightKg:Yr(r.weight_kg)})}i(Ba,"fromWire");function $a(e){if(typeof e!="object"||e===null)return null;let t=e,r=Me(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Me(t.pet_id),petRef:r,name:Me(t.name),species:Me(t.species),breed:Me(t.breed),ageYears:Yr(t.age_years),weightKg:Yr(t.weight_kg),updatedAt:Me(t.updated_at)})}i($a,"widgetPetFromWire");function Cy(e){let t=$a(e);return t===null?null:Object.freeze({...t,...Va(e)})}i(Cy,"widgetPetProfileFromWire");function Ey(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=$a(r);return n===null?[]:[n]}))}i(Ey,"petListFromWire");function Qe(e){return Ry(ke({auth:e}),ke({auth:e,unaryTimeoutMs:hy}))}i(Qe,"createPetsRepository");function Ry(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Ha(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?M(Ey(s.value)):v(s.error)},async registerPet(o,s,a){let l=Ha(o,s);if(l!==null)return v(l);let u=vy(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?M(Ba(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=by(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?M(Ba(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=Cy(l.value);return u===null?v(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):M(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?M(void 0):v(l.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?M(void 0):v(s.error)}}}i(Ry,"createPetsRepositoryOver");var bo=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Sy(e){return bo[e]}i(Sy,"requires");function Ya(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(bo))for(let a of bo[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Ya,"deniedDecisionsFor");function Xa(e,t,r){let n=Sy(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return ho({name:e,enabled:false,isPending:true,limits:{}});let s=Ty(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?ho({name:e,enabled:true,isPending:false,limits:s}):ho({name:e,enabled:false,isPending:false,limits:s,disabled:Py(n,o)})}i(Xa,"decideCapability");function Ty(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[s,a]of Object.entries(o)){let l=r[s];r[s]=l===void 0?a:Math.min(l,a);}}return r}i(Ty,"mergeLimits");function Py(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:It("accessDenied"),level:"user_entitlement",recoverable:false})}i(Py,"disabledFor");function ho(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(ho,"freezeDecision");function ye(e){let t=ie(e);return t===null?null:xy(t)}i(ye,"parseColor");function ie(e){if(typeof e=="number")return Qa(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return vo(t.slice(1));if(t.toLowerCase().startsWith("0x"))return vo(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return ky(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=vo(t);if(r!==null)return r}return /^\d+$/.test(t)?Qa(Number.parseInt(t,10)):null}i(ie,"toRgba");function vo(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Co(t[0]),g:Co(t[1]),b:Co(t[2]),a:1};if(t.length===6)return {r:at(t,0),g:at(t,2),b:at(t,4),a:1};if(t.length===8){let r=at(t,0);return {r:at(t,2),g:at(t,4),b:at(t,6),a:r/255}}return null}i(vo,"fromHex");function ky(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=Eo(Number(n[0])),s=Eo(Number(n[1])),a=Eo(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(ky,"fromRgbFunc");function Qa(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(Qa,"argbIntToRgba");function at(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(at,"byte");function Co(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Co,"dup");function Eo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Eo,"clampByte");function xy(e){if(e.a>=1)return ut(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(xy,"normalizeRgba");function ut(e,t,r){return `#${Ro(e)}${Ro(t)}${Ro(r)}`.toUpperCase()}i(ut,"rgbToHex");function Ro(e){return e.toString(16).padStart(2,"0")}i(Ro,"hex2");var _y="#111111",Ft="#FFFFFF",Xr="#000000";function Ja(e){let t=ie(e);if(t===null)return Ft;let r=lt(t),n=lt({r:17,g:17,b:17}),o=lt({r:255,g:255,b:255});return Po(r,o)>=Po(r,n)?Ft:_y}i(Ja,"readableOn");function ur(e,t){let r=Ja(e);return ue(r,e)>=t?r:ue(Ft,e)>=ue(Xr,e)?Ft:Xr}i(ur,"legibleOn");function dr(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ft)>=t(Xr)?Ft:Xr}i(dr,"poleForGrounds");function lt(e){let t=So(e.r/255),r=So(e.g/255),n=So(e.b/255);return .2126*t+.7152*r+.0722*n}i(lt,"relativeLuminance");function So(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(So,"linearize");function Po(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Po,"luminanceContrast");function ue(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:el(r,o);return Po(lt(s),lt(o))}i(ue,"contrastRatio");function el(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(el,"composite");function dt(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return null;let o=r.a>=1?r:el(r,{...n});return ut(o.r,o.g,o.b)}i(dt,"flattenOnto");function tl(e,t){let r=ie(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i(tl,"withAlpha");var Za=.05;function Ze(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(ie(e)===null)return r;if(s(e))return e;let a=dt(e,o),l=a===null?null:ie(a),u=ie(r);if(l===null||u===null)return r;for(let d=1;d<1/Za;d+=1){let c=d*Za,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=ut(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(Ze,"pushToContrast");function rl(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(rl,"rgbToHsl");function ko(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:To(c+l),g:To(p+l),b:To(f+l)}}i(ko,"hslToRgb");function To(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(To,"channel");function ze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ze(e[t]);}return e}i(ze,"deepFreeze");var Zr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ol={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},il={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},nl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},wy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Iy={regular:"400",medium:"500",bold:"700"},Ay={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},xo=0,ct="System",De="monospace",Oy=["content","heading","control","compact","badge"];function Fy(e){let t={};for(let r of Oy)t[r]=e;return t}i(Fy,"authoredTierSizes");function sl(){return {family:ct,mono:De,fontUrl:null,families:{regular:ct,medium:ct,bold:ct,mono:De,monoMedium:De,monoBold:De},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:nl,tierSizes:Fy(nl),lineHeight:wy,weight:Iy,letterSpacing:Ay,scale:1,maxScale:xo,scaleCaps:Zr}}i(sl,"baseType");var al={},pt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Qr(e){return `cubic-bezier(${e.join(", ")})`}i(Qr,"cssCubicBezier");var ll={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Qr(pt.standard),emphasized:Qr(pt.emphasized),exit:Qr(pt.exit)},reducedMotion:false},My={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ft=ze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:My,space:ol,radius:il,type:sl(),motion:ll,slots:al}),Ly={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Jr=ze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ly,space:ol,radius:il,type:sl(),motion:ll,slots:al});var Dy="#23272C",ul=4.5,Ny=.6,_o=.9,Uy=.02,Vy="#FFFFFF",Hy="#111111";function By(e){return ue(e,Dy)>=ul&&Math.max(ue(e,Vy),ue(e,Hy))>=ul}i(By,"readsOnDark");function pl(e){let t=ie(e);if(t===null)return null;let{h:r,s:n,l:o}=rl(t.r,t.g,t.b),s=Math.min(Math.max(o,Ny),_o);for(let l=0;;l+=1){let u=s+l*Uy;if(u>_o)break;let d=ko({h:r,s:n,l:u}),c=ut(d.r,d.g,d.b);if(By(c))return c}let a=ko({h:r,s:n,l:_o});return ut(a.r,a.g,a.b)}i(pl,"deriveDarkVariant");var zy=7,dl=.05,jy="#000000",Wy="#FFFFFF";function Gy(e,t,r,n){let o=dt(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let s=ie(o),a=ie(r);if(s===null||a===null)return r;for(let l=1;l<1/dl;l+=1){let u=l*dl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=ut(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(ue(c,t)>=n)return c}return r}i(Gy,"pushContrast");function Ky(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=cl(n);for(let s of r){let a=cl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(Ky,"hardestGround");function cl(e){let t=ie(e);return t===null?0:lt(t)}i(cl,"luminanceOf");function Je(e,t){return dt(e,t)??ye(e)??t}i(Je,"solid");function fl(e){let t=e.color,r=e.brightness==="dark",n=r?Wy:jy,o=Ky(t,r),s=i(l=>Gy(l,o,n,zy),"text"),a={...t,brandSoft:Je(t.brandSoft,t.surface),brandSofter:Je(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:Je(t.badgeBgPositive,t.surface),badgeBgCaution:Je(t.badgeBgCaution,t.surface),badgeBgCritical:Je(t.badgeBgCritical,t.surface),badgeBgNeutral:Je(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Je(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Je(t.checkupCardConcernBg,t.surface)};return ze({...e,highContrast:true,color:a})}i(fl,"deriveHighContrast");var mt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),qy=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),_e=4.5,$y=Object.freeze({});function Yy(e){return mt.includes(e)}i(Yy,"isSlotName");function Xy(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Xy,"parseRadius");function ml(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Yy(n)||o===null||typeof o!="object")continue;let s=Qy(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(ml,"parseThemeSlots");function en(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(en,"pick");function Qy(e){let t={},r=ye(en(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(en(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Xy(en(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ye(en(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Qy,"parseSlot");function yl(e,t){return t===null||Object.keys(t).length===0?e??$y:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(yl,"mergeThemeSlots");var wo=3;function Zy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>dt(e,r)??r)}i(Zy,"seatsOf");function Jy(e,t){let r=dr(e);return e.every(n=>ue(r,n)>=t)}i(Jy,"someInkReads");function eg(e,t){let r=t[0];return r===void 0?null:dt(e,r)}i(eg,"collapseUnsatisfiableFill");function tg(e){let t=ur(e[0],_e);return e.every(r=>ue(t,r)>=_e)?t:dr(e)}i(tg,"inkFor");function gl(e,t){let r=false,n={};for(let o of mt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=Zy(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!Jy(u,_e)){let p=eg(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>ue(p,f)<_e))&&(d.textColor=tg(u),c=true);else if(p!==void 0){let f=Ze(p,u,dr(u),_e);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=Ze(s.borderColor,u,dr(u),wo);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(gl,"guardSlotContrast");var vl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),cr="slots.",Cl=Object.freeze([1,2]);function tn(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(tn,"isEmptyBranding");function El(e){let t=e?.schemaVersion??null;return t===null||Cl.includes(t)}i(El,"isKnownBrandingSchema");function Rl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Rl,"lockedFieldsOf");function rg(e){return e==="hide_powered_by"||vl.includes(e)?true:e.startsWith(cr)&&mt.includes(e.slice(cr.length))}i(rg,"isThemeLockName");function je(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:yt($(t,"display_name","displayName")),logoUrl:yt($(t,"logo_url","logoUrl")),primaryColor:ye($(t,"primary_color","primaryColor")),accentColor:ye($(t,"accent_color","accentColor")),brightness:sg($(t,"brightness","color_scheme","colorScheme")),fontFamily:yt($(t,"font_family","fontFamily")),fontUrl:yt($(t,"font_url","fontUrl")),fonts:hl($(t,"fonts")),fontUrls:hl($(t,"font_urls","fontUrls")),placeholder:yt($(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:ng($(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye($(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye($(t,"accent_color_dark","accentColorDark")),surfaceStyle:bl($(t,"surface_style","surfaceStyle"),og),radiusScale:bl($(t,"radius_scale","radiusScale"),ig),logoUrlDark:yt($(t,"logo_url_dark","logoUrlDark")),slots:ml($(t,"slots")),accessibilityMaxFontScale:lg($(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:dg($(t,"locked_fields","lockedFields")),schemaVersion:ug($(t,"schema_version","schemaVersion"))};return tn(r)?null:Object.freeze(r)}i(je,"parseClientBranding");function ng(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(ng,"parseBool");function $(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i($,"pick");function yt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(yt,"parseNonEmptyString");var pr=["regular","medium","bold","mono","monoMedium","monoBold"];function hl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of pr){let o=yt($(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(hl,"parseFaceMap");var og=["white","cream","subtle"],ig=["sharp","default","round"];function bl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(bl,"parseEnum");function sg(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(sg,"parseBrightness");function Sl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(Sl,"parseNumber");var ag=1,Tl=3.1;function lg(e){let t=Sl(e);return t===null?null:t<=0?0:Math.min(Tl,Math.max(ag,t))}i(lg,"parseMaxFontScale");function ug(e){if(e==null)return null;let t=Sl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(ug,"parseSchemaVersion");function Io(e){let t=e.trim();return t.startsWith(cr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Io,"toWireName");function dg(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Io(r);rg(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(dg,"parseLockedFields");function Ao(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Ao,"hardenHttpsUrl");function Pl(e,t){if(t===null||tn(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Jr:ft:e,n=r.brightness==="dark"?Jr:ft,o=r.brightness==="dark",s=o?t.primaryColorDark??kl(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??kl(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&yg(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ie(c):null,f=i(k=>Math.round(k+(255-k)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?gg(n,r.color.text):{},y={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...mg(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:bg(t.radiusScale??null,r.radius,n),type:{...r.type,...fg(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:yl(r.slots,t.slots??null)};return ze(y)}i(Pl,"withServerBranding");var cg={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},pg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Oo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(Oo,"isMonoFace");function fg(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of pr){let u=cg[l].map(p=>r[p]).find(p=>p!==void 0),d=Oo(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of pg)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(fg,"mergeFaces");function kl(e){return e===null?null:pl(e)}i(kl,"darkVariantOf");function mg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(mg,"surfaceOf");function xl(e,t){return e==null?false:ye(e)===ye(t)}i(xl,"sameColor");function yg(e,t,r,n){return xl(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&xl(e.primaryColor,ft.color.primary)}i(yg,"isCompiledPrimary");function gg(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(gg,"compiledBrandFamily");var hg={sharp:.5,default:1,round:1.5};function bg(e,t,r){if(e===null)return t;let n=hg[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(bg,"radiusOf");var vg="Everfur",Cg=.5;function Fo(e){let t=e?.branding??null,r=El(t)?t:null,n=Pg(e?.clientOverride??null,Rl(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=Pl((s==="auto"?o:s)==="dark"?Jr:ft,_l(r)),d=Pl(u,_l(n));return Ng(d,e)}i(Fo,"resolveTheme");function Eg(e,t,r){return Fo({...r,branding:je(t),clientOverride:je(e)})}i(Eg,"previewTheme");function Rg(e){return e==="placeholder"?"chat_placeholder":Io(e)}i(Rg,"wireNameOf");var Sg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Tg(e,t){return t.has(Rg(e))?true:(Sg[e]??[]).some(r=>t.has(r))}i(Tg,"isLocked");function Pg(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Tg(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of mt){let d=o[u];d!==void 0&&(t.has(`${cr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return tn(s)?null:s}i(Pg,"withoutFields");function _l(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(_l,"withoutBrightness");function kg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(kg,"scaledSizes");function xg(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Cg,e)}i(xg,"effectiveScale");var wl=["content","heading","control","compact","badge"];function _g(e){if(!(e>0))return Zr;let t={};for(let r of wl){let n=Zr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(_g,"tierCaps");function wg(e,t){return t>0?Math.min(e,t):e}i(wg,"capped");function Ig(e,t,r,n){let o={};for(let s of wl)o[s]=n?kg(e,wg(t,r[s])):e;return o}i(Ig,"sizesByTier");function Ag(e){return e==="dark"?"#FFFFFF":"#000000"}i(Ag,"inkPole");function Og(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Og,"textGrounds");function Fg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Fg,"controlGrounds");function Il(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Il,"linkGrounds");function Mg(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Il(e)}}i(Mg,"slotGrounds");function Lg(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Lg,"registration");function Dg(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of pr)!(o[a]===ct||o[a]===De)&&r!==void 0&&Lg(r,o[a])===false&&(o[a]=Oo(a)?De:ct,s[a]=false),n!==null&&Oo(a)&&o[a]===De&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Dg,"platformFaces");function Ng(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?vg:e.meta.displayName,s=Ao(e.meta.logoUrl),a={};for(let _ of pr){let x=e.type.fontUrls[_];x!==void 0&&(a[_]=Ao(x));}let l=a.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:xo,p=xg(t?.textScale),f=_g(c),m=Ig(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,k=Ag(e.brightness),g=Og(y),R={...y,primary:r,accent:n,onPrimary:ur(r,_e),onAccent:ur(n,_e),brandInk:Ze(y.brandInk,g,k,_e),linkInk:Ze(e.slots.link?.textColor??n,Il(y),k,_e),text:{...y.text,secondary:Ze(y.text.secondary,g,k,_e)},brandBorderStrong:Ze(y.brandBorderStrong,Fg(y),k,wo)},w={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:R,space:e.space,radius:e.radius,type:{...e.type,...Dg(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:gl(e.slots,Mg(R))};return t?.highContrast===true?fl(ze(w)):ze(w)}i(Ng,"finalize");var Al="/widget/v1/entitlements",Ug=304,Vg=Object.freeze({kind:"notModified"});async function Fl(e,t={},r=ke({auth:e})){let n=await r.send("entitlements.fetch",Bg(t));return n.ok?zg(n.value):n.error.httpStatus===Ug?Vg:{kind:"failed",error:n.error}}i(Fl,"fetchEntitlements");var Hg=64;function Bg(e){let t={};return Mo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Hg?{method:"GET",path:Al,headers:t,query:{region:e.region}}:{method:"GET",path:Al,headers:t}}i(Bg,"buildRequest");function zg(e){if(e===null||typeof e!="object"||!Mo(e.revision))return Ol();let t=typeof e.region=="string"?e.region:"",r=Mo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Wg(e.capabilities),branding:jg(e)})}i(zg,"parseUpdated");function jg(e){let t=je(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=je(r.branding);return n!==null?n:je(r)}return null}i(jg,"parseBranding");function Wg(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Gg(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Wg,"mapCapabilities");function Gg(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Gg,"isEnabled");function Ol(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Ol,"malformed");function Mo(e){return typeof e=="number"&&Number.isFinite(e)}i(Mo,"isFiniteNumber");var Kg=30;function Ml(e){let t=e.scheduler??qg,r=e.resolve??Fl,n=Math.max(1,e.floorSeconds??Kg),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(R=>{l||!a||(c=Math.max(n,R),u=t.set(()=>{u=null,g();},c*1e3));},"schedule"),y=null,k=i(async()=>{if(l)return null;let R=p;e.onFetch?.();let w=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},_;try{_=await r(e.authFor(),w);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:$g(x)}),!l&&R===p&&(e.onSettled?.(),m(s())),null}if(l||R!==p)return null;switch(_.kind){case "updated":d=_.revision,e.update(_.decisions,_.branding??null),m(_.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:_.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),_},"tick"),g=i(()=>{let R=k().finally(()=>{y===R&&(y=null);});return y=R,R},"run");return {start(){a||l||(a=true,g());},prime(){return l?Promise.resolve(null):y??g()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),g());}}}i(Ml,"createEntitlementPoller");var qg={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function $g(e){return e instanceof Error?e.message:"poll failed"}i($g,"describe");var Ll="everfur.notifications.device";var Yg=3e3,Dl=Object.freeze([Ll]);function Nl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),a=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:a.length});}catch{}},"report"),u=Promise.allSettled(a).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",a.length),p();},Yg);u.then(p,p);})}i(Nl,"startBeforeLogoutHooks");function Ul(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let a={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:a,userRef:t.userRef,sessionId:o}}i(Ul,"graceAuth");async function Vl(e,t){if(Dl.length===0)return;let r=await Promise.allSettled(Dl.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Vl,"sweepPerUserKv");function Xg(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Xg,"compiledDefaultDecisions");function Lo(e=Xg){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Lo,"createEntitlementStore");function Do(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Do,"notConfiguredError");function Hl(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return _s(r,t===void 0?void 0:{platform:t})}i(Hl,"tryResolveClient");function Bl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Bl,"guardTelemetry");function zl(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
+ [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(zl,"reportConfigFailure");function No(e){return Object.freeze({request(){return Promise.resolve(v(Do(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(No,"refusingTransport");function jl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(jl,"createInMemoryKv");var Wl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function ql(e,t){return new Vo(e,t)}i(ql,"createEverfurRuntime");var Qg=6e4,Ho=class Ho{constructor(t,r){this.sessionId=Wn();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new Q("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Bl(n.telemetry):Nr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Kn(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=No(s);else if(n.transport!==void 0)l=n.transport;else {let c=Hl(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=Ms({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=No(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&zl(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??fs,this.upload=n.upload??Js,this.uploadTransport=n.uploadTransport??co,this.imageCache=n.imageCache??Wl,this.kv=n.storage??jl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Lo():Lo(()=>Ya("sdk_config",It("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Uo(c),()=>this.buildChatController(c),Gl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Uo(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Es(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Qg,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Ml({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=ba({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Ea(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=Wn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Vl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Nl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Ul({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v(Kl(t)):r(Qe(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Kl("prepare"):n===null?null:Do(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?M(void 0):s.currentToken().then(()=>M(void 0),()=>v(D("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):M(void 0):v(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Uo(r),()=>this.buildChatController(r),Gl,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):M(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Ho,"EverfurRuntimeImpl");var Vo=Ho;function Uo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Uo,"chatScopeKey");function Gl(e){e.dispose();}i(Gl,"disposeChat");function Kl(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Kl,"disposedError");var $l=Symbol.for("@everfur/sdk#EverfurContext@v1"),Yl=globalThis,rn=Yl[$l]??(Yl[$l]=react.createContext(null));rn.displayName??="EverfurContext";function Y(){let e=react.useContext(rn);if(e===null)throw new Q("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Y,"useEverfurContext");function Xl(){return Y().handle}i(Xl,"useEverfur");var Ql=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Zl=globalThis,fr=Zl[Ql]??(Zl[Ql]=react.createContext(ft));fr.displayName??="EverfurThemeContext";function F(){return react.useContext(fr)}i(F,"useEverfurTheme");function nn(e){let{runtime:t}=Y(),r=t.entitlements,n=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?oh(e.clientTheme):"",f=react.useMemo(()=>e.clientTheme?je(e.clientTheme):null,[p]),m=n.branding??null,y=react.useMemo(()=>Fo({branding:m,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(y),react.createElement(fr.Provider,{value:y},e.children)}i(nn,"EverfurThemeProviderCore");function oh(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(oh,"stableKey");function nu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=react.useRef(null),c=react.useRef(null),[p,f]=react.useReducer(T=>T+1,0),m=react.useRef(null),y=react.useRef(void 0),k=r?.userRef??null;y.current!==k&&(y.current!==void 0&&(m.current=null),y.current=k);let g=m.current!==null?m.current.user:r??null,R=react.useRef(null),w=react.useRef(void 0),_=n??null;w.current!==_&&(w.current!==void 0&&(R.current=null),w.current=_);let x=R.current!==null?R.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:ql({config:l.withDefaults?l.withDefaults(t):t,user:g,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,P=react.useRef(null);react.useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||P.current!==T&&(P.current=T,f());}),react.useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let L=g?.userRef??null;react.useLayoutEffect(()=>{b.setUser(g);},[b,L]),react.useLayoutEffect(()=>{b.setActivePet(x);},[b,x]),react.useEffect(()=>()=>b.dispose(),[b]),react.useEffect(()=>{s==="onMount"&&b.prepare(x===null?{}:{petRef:x});},[b,s,L,x]);let I=react.useMemo(()=>({setUser:i(T=>{m.current={user:T},b.setUser(T),f();},"setUser"),setActivePet:i(T=>{R.current={pet:T},b.setActivePet(T),f();},"setActivePet"),open:i(T=>b.open(T),"open"),prepare:i(T=>b.prepare(T),"prepare"),registerPet:i((T,V)=>b.registerPet(T,V),"registerPet"),updatePet:i((T,V)=>b.updatePet(T,V),"updatePet"),deletePet:i(T=>b.deletePet(T),"deletePet"),eraseUserData:i(()=>b.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let T=b.logout();return f(),T},"logout")}),[b,f]),S=react.useMemo(()=>({runtime:b,handle:I,userRef:L,activePet:x,scopeEpoch:b.scopeEpoch}),[b,I,L,x,p]),O=react.createElement(nn,{clientTheme:o??null,seams:l.theme,children:a});return react.createElement(rn.Provider,{value:S},l.wrap?l.wrap(O):O)}i(nu,"EverfurProviderCore");var ah=2;function lh(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<ah)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(lh,"readEventSourceResponseHeader");function ou(){let e=sh__default.default;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>lh(n,o),"getResponseHeader")})}}i(ou,"createRnEventSourceFactory");function ph(){let e=reactNative.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(ph,"useRnColorScheme");function fh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(fh,"isThenable");function mh(){let[e,t]=react.useState(false);return react.useEffect(()=>{let r=true,n=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(reactNative.AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(mh,"useRnReducedMotion");function au(){let e=reactNative.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(reactNative.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(au,"readFontScale");function yh(e){let t=reactNative.Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(reactNative.Dimensions,"change",e);return ()=>r?.remove?.()}i(yh,"subscribeFontScale");function gh(){return react.useSyncExternalStore(yh,au,au)}i(gh,"useRnTextScale");function cu(){try{let e=reactNative.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(cu,"platformOS");function hh(){return cu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(hh,"contrastSignal");function bh(){let[e,t]=react.useState(false);return react.useEffect(()=>{let r=true,{query:n,event:o}=hh(),a=reactNative.AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(reactNative.AccessibilityInfo);fh(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=reactNative.AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(reactNative.AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(bh,"useRnHighContrast");function vh(){return cu()==="ios"?"Menlo":De}i(vh,"rnPlatformMonoFamily");function Ch(){return globalThis.__DEV__!==false}i(Ch,"isDevelopment");var lu=new Set;function Eh(e){if(!Ch()||lu.has(e))return;lu.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(Eh,"warnUnregisteredFace");function Rh(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||Eh(e),o}i(Rh,"rnIsFontRegistered");var sn=Object.freeze({useColorScheme:ph,useReducedMotion:mh,useTextScale:gh,useHighContrast:bh,scaleTypeSizes:false,platformMonoFamily:vh,isFontRegistered:Rh});function Th(e){return react.createElement(reactNativeSafeAreaContext.SafeAreaProvider,null,e)}i(Th,"wrapInSafeArea");var Ph=Object.freeze({platform:"react-native",eventSourceFactory:ou(),wrap:Th,theme:sn});function kh(e){return react.createElement(nu,{...e,seams:Ph})}i(kh,"EverfurProvider");function Mt(e){let{runtime:t}=Y(),r=t.entitlements,n=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return react.useMemo(()=>Xa(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Mt,"useCapability");function Oh(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Oh,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=F(),n=Oh(r,e);return react.createElement(reactNative.Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Lt=react.forwardRef(i(function(t,r){return react.createElement(reactNative.TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Fh=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function E(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Fh[t]]}}i(E,"face");var zo=class zo extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(zo,"HostRenderBoundary");var Bo=zo;function Lh({render:e}){return e()}i(Lh,"RenderHost");function bt({render:e,fallback:t,resetKey:r}){return react.createElement(Bo,{fallback:t,resetKey:r,children:react.createElement(Lh,{render:e})})}i(bt,"HostRender");var Dh=48;function Nh(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Nh,"selectView");function Go(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Mt(t),l=react.useMemo(()=>Nh(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsxRuntime.jsx(bt,{render:o,fallback:jsxRuntime.jsx(gu,{capability:t,style:s})}):jsxRuntime.jsx(gu,{capability:t,style:s});case "disabled":return n?jsxRuntime.jsx(bt,{render:()=>n(a),fallback:jsxRuntime.jsx(hu,{decision:a,style:s}),resetKey:a}):jsxRuntime.jsx(hu,{decision:a,style:s});default:return Xe(l)}}i(Go,"CapabilityGate");function gu({capability:e,style:t}){let r=F(),n=react.useMemo(()=>bu(r),[r]);return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsxRuntime.jsx(reactNative.View,{style:n.skeletonBar})})}i(gu,"PendingSkeleton");function hu({decision:e,style:t}){let r=F(),n=react.useMemo(()=>bu(r),[r]),o=e.disabled?.reason??"";return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsxRuntime.jsx(C,{style:n.offstateText,children:o}):null})}i(hu,"OffState");function bu(e){let{color:t,space:r,radius:n,type:o}=e;return reactNative.StyleSheet.create({offstate:{minHeight:Dh,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...E(e,"regular"),fontSize:o.size.body,lineHeight:Math.round(o.size.body*o.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}i(bu,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting\u2026",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var Ko=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),vu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Uh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Uh,"sentimentToFeedbackType");function Cu(e,t){if(e==="down"&&t!==null){let r=Ko.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Uh(e)}i(Cu,"feedbackTypeFor");var zh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function mr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=Y(),s=e?.petRef??n??null,a=e?.conversationId??null,l=react.useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[u,d]=react.useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=react.useRef(null);react.useEffect(()=>{let S=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=S,d({scope:l,controller:S}),()=>{p.current=null,d(O=>O?.controller===S?null:O),t.registry.releaseChat(S);}},[t,r,s,a,o,l]);let f=react.useCallback(S=>c?c.subscribe(S):jh,[c]),m=react.useCallback(()=>c?c.getSnapshot():zh,[c]),y=react.useSyncExternalStore(f,m,m),k=react.useCallback((S,O)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?$o(c,c.send(S,O?.imageS3Keys===void 0?{}:{imageS3Keys:O.imageS3Keys}),()=>p.current===c):Promise.resolve(Yo()),[c]),g=react.useCallback(S=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?$o(c,c.askEverfur(S),()=>p.current===c):Promise.resolve(Yo()),[c]),R=react.useCallback(()=>c&&p.current===c?$o(c,c.retryLast(),()=>p.current===c):Promise.resolve(Yo()),[c]),w=react.useCallback(()=>{c&&p.current===c&&c.stop();},[c]),_=react.useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[x,b]=react.useState({controller:null,byMessage:{}}),P=x.controller===c?x.byMessage:Wh,L=react.useCallback(async(S,O,T,V)=>{if(!c||p.current!==c)return v(D("accessDenied"));let j=String(S),G=x.controller===c?x.byMessage[j]:void 0;if(G===O&&T==null)return b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return delete Pe[j],{controller:c,byMessage:Pe}}),M(Object.freeze({feedbackId:""}));b(de=>({controller:c,byMessage:{...de.controller===c?de.byMessage:{},[j]:O}}));let ne=await c.submitFeedback(S,Cu(O,T??null),V??null);return p.current!==c?v(D("accessDenied")):(ne.ok||b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return G===void 0?delete Pe[j]:Pe[j]=G,{controller:c,byMessage:Pe}}),ne)},[c,x]),I=react.useMemo(()=>{let S=i(async O=>{if(!c||p.current!==c)return v(D("accessDenied"));let T=await O(c);return p.current===c?T:v(D("accessDenied"))},"run");return {listConversations:i(O=>S(T=>T.listConversations({...s?{petRef:s}:{},...O})),"listConversations"),getMessages:i((O,T)=>S(V=>V.getMessages(O,T)),"getMessages"),resumeConversation:i(O=>S(T=>T.resumeConversation(O)),"resumeConversation"),loadOlderMessages:i(()=>S(O=>O.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>S(O=>O.markRead()),"markRead"),refreshActiveThread:i(()=>S(O=>O.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((O,T)=>S(V=>V.answerCheckin(O,T)),"answerCheckin"),openCheckin:i(O=>S(T=>T.openCheckin(O)),"openCheckin")}},[c,s]);return react.useMemo(()=>({status:y.status,messages:y.messages,conversationId:y.conversationId,petRef:s,error:y.error,isStreaming:y.isStreaming,isBootstrapping:y.isBootstrapping,historyCursor:y.historyCursor??null,isLoadingHistory:y.isLoadingHistory??false,stopped:y.stopped??false,reconnecting:y.reconnecting??false,...I,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:_,sentimentByMessage:P,feedback:L,send:k,askEverfur:g,retryLast:R,stop:w}),[y,s,k,g,R,w,I,_,P,L])}i(mr,"useEverfurChat");var jh=i(()=>{},"NOOP_UNSUBSCRIBE"),Wh=Object.freeze({});async function $o(e,t,r){for await(let o of t);if(!r())return v(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):M(Gh(n.messages))}i($o,"driveToResult");function Gh(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i(Gh,"lastAssistantResponseId");function Yo(){return v(D("internalError",{retryable:true}))}i(Yo,"notReadyError");function Su(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:fo(Wr),filename:e.filename,size:fo(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Gr});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(Su,"attachmentErrorMessage");function Tu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(Tu,"attachControlLabel");var Yh=Object.freeze({attachments:Object.freeze([])});function an(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??Gr,s=react.useMemo(()=>{if(e.queue)return e.queue;let{services:g}=t.registry;return Ta({funnel:ke({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.queue,e.transport]);react.useEffect(()=>()=>{s!==e.queue&&s.dispose();},[s,e.queue]);let a=react.useSyncExternalStore(s.subscribe,s.getSnapshot,()=>Yh),[l,u]=react.useState(null),d=react.useCallback(g=>{let w=(Array.isArray(g)?g:[g]).map(x=>s.add(x)),_=w.find(x=>!x.ok);return _!==void 0&&!_.ok&&u(_.error),w},[s,u]),c=react.useCallback(g=>s.retry(g),[s]),p=react.useCallback(g=>s.remove(g),[s]),f=react.useCallback(()=>s.clear(),[s]),m=react.useCallback(()=>u(null),[u]),y=a.attachments.some(g=>g.status==="uploading"),k=a.attachments.some(g=>g.status==="failed");return react.useMemo(()=>({available:s.available,attachments:a.attachments,maxPerMessage:o,uploading:y,failed:k,blocked:y||k,s3Keys:a.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:l,add:d,retry:c,remove:p,clear:f,dismissRejected:m}),[s.available,a,o,y,k,l,d,c,p,f,m])}i(an,"useChatAttachments");var Zh="pet_not_registered";function xu(e){return e!=null&&e.reasonCode===Zh}i(xu,"isPetNotRegistered");var Jh=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function _u(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Y(),a=react.useCallback(()=>Qe(n.registry.services.authFor(o)),[n,o,s]),l=react.useMemo(()=>t===void 0?null:Qo(t),[t]),[u,d]=react.useState({key:null,status:"idle",error:null,registered:null}),c=react.useRef(0),p=react.useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=react.useCallback(()=>{if(e===null||t===void 0||f===null)return;let k=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(g=>{k===c.current&&(g.ok?(d({key:f,status:"registered",error:null,registered:g.value}),p.current?.()):d({key:f,status:"failed",error:g.error,registered:null}));});},[a,e,f]);react.useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let y=react.useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return react.useMemo(()=>f===null?Jh:u.key!==f?{status:"registering",error:null,registered:null,retry:y}:{status:u.status,error:u.error,registered:u.registered,retry:y},[f,u,y])}i(_u,"useChatPetRegistration");function Qo(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Qo).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${Qo(n)}`).join(",")}}`}i(Qo,"stableKey");var Zo=Object.freeze({});function Iu(e){let[t,r]=react.useState(Zo),n=react.useRef(null),o=react.useRef([]);o.current=e.map(a=>a.id),react.useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Zo?u:Zo);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[l.id]:a.images})));},[e]);let s=react.useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return react.useMemo(()=>({byMessage:t,stage:s}),[t,s])}i(Iu,"useSentImages");var ib=500;function Jo(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,ib):null}i(Jo,"sanitizeSeedPrompt");function Ou(e,t,r){let n=Jo(r),o=react.useRef(e);o.current=e;let s=react.useRef(null);react.useEffect(()=>{if(n===null||t||s.current===n)return;let a=o.current;a!==void 0&&(s.current=n,Promise.resolve(a(n)).catch(()=>{}));},[n,t]);}i(Ou,"useInitialAsk");function sb(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(sb,"isCoalesced");function Fu(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:sb(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Fu,"decideChatRefresh");function ei(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ei,"reportHostFailure");function ab(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(ab,"isThenable");function q(e,...t){if(typeof e=="function")try{let r=e(...t);return ab(r)&&Promise.resolve(r).then(void 0,ei),r}catch(r){ei(r);return}}i(q,"callHost");var Mu=new WeakMap;function Lu(e){if(typeof e!="function")return;let t=Mu.get(e);if(t!==void 0)return t;let r=i((...n)=>{q(e,...n);},"guarded");return Mu.set(e,r),r}i(Lu,"guardHost");function Dt(e,...t){let r;try{r=e(...t);}catch(n){return ei(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Dt,"callHostAsync");function Nu(e,t){let r=react.useRef(t);r.current=t;let n=react.useRef(null),o=react.useRef(null),s=e?.isOffline===void 0?false:q(()=>e.isOffline?.()===!0)===true,a=react.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(()=>{});}},react.useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),react.useEffect(()=>{if(e===void 0)return;let l=[],u=i((d,c)=>{if(d===void 0)return;let p=q(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)q(d);}},[e]);}i(Nu,"useChatLifecycle");function ub(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(ub,"targetKey");function Vu(e,t){let r=ub(t),n=react.useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=react.useRef(null);react.useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:s,target:a}=n.current;s===void 0||a===void 0||Promise.resolve(s(a)).catch(()=>{});},[r]);}i(Vu,"useCheckinTarget");function zu(e,t,r){let[n,o]=react.useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);react.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=react.useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(zu,"useChatDraft");function ju(e,t,r,n){let o=react.useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=react.useRef(null),[a,l]=react.useState(null);react.useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await Dt(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),react.useEffect(()=>{e===void 0||a!==`${t??""}`||q(()=>e.write(t,r));},[e,t,r,a]);}i(ju,"usePersistedDraft");var Z=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function un(e){let t=e?.replace(/\s+/g," ").trim();return t||Z.untitled}i(un,"conversationTitle");function Gu(e){return `${e.unreadCount!==null&&e.unreadCount>0?Z.unreadPrefix:""}${Z.openConversation} ${un(e.title)}`}i(Gu,"openConversationLabel");function Wu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Wu,"normalizeForSearch");function yb(e,t){let r=Wu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Wu(un(o.title)),a=s.indexOf(r);if(a<0)continue;let l=a===0?0:s.charAt(a-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(yb,"filterConversations");function ni(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(ni,"fresh");function Ku(e){let[t,r]=react.useState(false),[n,o]=react.useState(""),s=e.listConversations,a=react.useRef(0),[l,u]=react.useState(()=>ni(s)),d=l.scope===s?l:ni(s);react.useEffect(()=>(a.current+=1,r(false),o(""),u(ni(s)),()=>{a.current+=1;}),[s]);let c=react.useCallback(async _=>{let x=++a.current,b=_!==void 0;u(L=>({...L,scope:s,loading:!b,loadingMore:b,error:null}));let P=await e.listConversations(_?{cursor:_}:void 0);if(x===a.current){if(!P.ok){u(L=>({...L,loading:false,loadingMore:false,error:P.error.displayMessage}));return}u(L=>{let I=_&&L.scope===s?L.rows:[],S=new Set(I.map(O=>O.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...I,...P.value.conversations.filter(O=>!S.has(O.id))],cursor:P.value.nextCursor===_?null:P.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async _=>{let x=++a.current;u(P=>({...P,loading:true,error:null}));let b=await e.resumeConversation(_);x===a.current&&(u(P=>({...P,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),y=i(async()=>{let _=a.current,x=await e.loadOlderMessages();_===a.current&&!x.ok&&u(b=>({...b,error:x.error.displayMessage}));},"earlier"),k=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),g=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),R=react.useMemo(()=>yb(d.rows,n),[d.rows,n]),w=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:k,loadMore:g,query:n,setQuery:o,searching:w,filtered:R,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Ku,"useHistoryPanel");var dn="#111111",cn="#FFFFFF",bb=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:dn,pillColor:cn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:dn,pillColor:cn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false})});function vb(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(vb,"urgencySignature");function Cb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Cb,"generalUrgencyReason");function Yu(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Cb(t)}:null}return null}i(Yu,"latestUrgencySource");function Xu(e){let t=e===null?null:vb(e),[r,n]=react.useState(null),[o,s]=react.useState(false);react.useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:bb[e.level],d=e!==null&&!l&&e.level!=="general",c=react.useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=react.useCallback(()=>s(true),[]);return react.useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Xu,"useUrgencySurface");function Qu(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Qu,"selectView");function Eb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Eb,"needsNewConversation");function Zu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Eb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(Zu,"turnNotice");function Ju(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Ju,"awaitingAssistant");function ed(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(ed,"buildChatOpts");var gr=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function nd(e){let t=F(),r=react.useMemo(()=>Tb(t),[t]);return jsxRuntime.jsxs(reactNative.View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${gr.title}. ${gr.body}`,children:[jsxRuntime.jsx(C,{style:r.title,children:gr.title}),jsxRuntime.jsx(C,{style:r.body,children:gr.body})]})}i(nd,"ClinicalDisclaimer");function Tb(e){let{color:t,space:r,type:n}=e;return reactNative.StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:reactNative.StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...E(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...E(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Tb,"makeStyles");var se={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function te(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(te,"box");function fe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(fe,"stroke");function od({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{gap:e*.22}],...se,children:[jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.View,{style:o})]})}i(od,"MenuGlyph");function id({size:e,color:t,strokeWidth:r,rotate:n}){let o=fe(e,r),s=e*.78;return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{transform:[{rotate:n}]}],...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(id,"Cross");function sd(e){return jsxRuntime.jsx(id,{...e,rotate:"0deg"})}i(sd,"PlusGlyph");function vt(e){return jsxRuntime.jsx(id,{...e,rotate:"45deg"})}i(vt,"CloseGlyph");function tt({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxRuntime.jsx(reactNative.View,{style:te(e),...se,children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(tt,"CheckGlyph");var xb={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function pn({size:e,color:t,strokeWidth:r,direction:n}){let o=fe(e,r),s=e*.46,a=xb[n];return jsxRuntime.jsx(reactNative.View,{style:te(e),...se,children:jsxRuntime.jsx(reactNative.View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}i(pn,"ChevronGlyph");function ad({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{flexDirection:"row",gap:1}],...se,children:[jsxRuntime.jsx(reactNative.View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsxRuntime.jsx(reactNative.View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(ad,"BookGlyph");function ld({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.5;return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}i(ld,"ArrowUpRightGlyph");function ud({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:[s,{top:0,left:0}]}),jsxRuntime.jsx(reactNative.View,{style:[s,{bottom:0,right:0}]})]})}i(ud,"CopyGlyph");function fn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=fe(e,r),a=n?t:"transparent";return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{transform:[{rotate:o}]}],...se,children:[jsxRuntime.jsx(reactNative.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}}),jsxRuntime.jsx(reactNative.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"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}i(fn,"ThumbGlyph");function dd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...se,children:[jsxRuntime.jsx(reactNative.View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsxRuntime.jsx(reactNative.View,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}i(dd,"InfoGlyph");function cd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.34;return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}i(cd,"UploadGlyph");function pd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxRuntime.jsxs(reactNative.View,{style:[te(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(pd,"PhotoGlyph");function fd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.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}}),jsxRuntime.jsx(reactNative.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:jsxRuntime.jsx(reactNative.View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}i(fd,"CameraGlyph");function md({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.66;return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.02,right:e*.02,width:n,height:e*.4,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}})]})}i(md,"SearchGlyph");function yd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}i(yd,"EditGlyph");function gd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.62;return jsxRuntime.jsxs(reactNative.View,{style:te(e),...se,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsxRuntime.jsx(reactNative.View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(gd,"MapPinGlyph");function hd({size:e,color:t,testID:r}){let n=e*.36;return jsxRuntime.jsx(reactNative.View,{style:te(e),testID:r,...se,children:jsxRuntime.jsx(reactNative.View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}i(hd,"SendGlyph");function bd({size:e,color:t,testID:r}){return jsxRuntime.jsx(reactNative.View,{style:te(e),testID:r,...se,children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(bd,"StopGlyph");function mn({size:e,strokeWidth:t,color:r,children:n}){return jsxRuntime.jsx(reactNative.View,{style:[te(e),{borderRadius:e/2,borderWidth:t??reactNative.StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(mn,"Ring");var hr=Object.freeze({standard:pt.standard,emphasized:pt.emphasized,exit:pt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var vd=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,reduced:false}),_b=Object.freeze({...vd,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,reduced:true});function Cd(e){return e.motion.reducedMotion?_b:vd}i(Cd,"chatMotion");function yn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(yn,"followUpDelayMs");function Ed(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(Ed,"nextRevealLength");function X(){let e=F();return Cd(e)}i(X,"useChatMotion");var Mb=8;function Sd(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Sd,"bezierComponent");function Lb(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Lb,"bezierSlope");function gn(e){let[t,r,n,o]=e;return s=>{if(s<=0)return 0;if(s>=1)return 1;let a=s;for(let l=0;l<Mb;l+=1){let u=Lb(a,t,n);if(u===0)break;a-=(Sd(a,t,n)-s)/u;}return Sd(Math.min(1,Math.max(0,a)),r,o)}}i(gn,"bezierEasing");var oi=gn(hr.standard),Db=gn(hr.outQuad);function li(e){let t=react.useRef(null);return t.current===null&&(t.current=new reactNative.Animated.Value(e)),t.current}i(li,"useAnimatedValue");function Ct(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=li(e>0?0:1);return react.useEffect(()=>{if(e<=0)return;let s=reactNative.Animated.timing(o,{toValue:1,duration:e,easing:Db,useNativeDriver:true}),a=n>0?reactNative.Animated.sequence([reactNative.Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),react.useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[o,r])}i(Ct,"useFadeIn");function ui({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=react.useState(e),l=li(e&&t<=0?1:0);return react.useEffect(()=>{if(e){a(true);let d=reactNative.Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:oi,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=reactNative.Animated.timing(l,{toValue:0,duration:r,easing:oi,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsxRuntime.jsx(reactNative.Animated.View,{style:[n,{opacity:l}],children:o})}i(ui,"FadePresence");var Nb=12;function B({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=X(),u=li(1),d=react.useCallback(c=>{l.pressMs<=0||l.pressScale===1||reactNative.Animated.timing(u,{toValue:c,duration:l.pressMs,easing:oi,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsxRuntime.jsx(reactNative.Pressable,{...a,hitSlop:s??Nb,style:t,onPressIn:c=>{d(l.pressScale),n?.(c);},onPressOut:c=>{d(1),o?.(c);},children:jsxRuntime.jsx(reactNative.Animated.View,{style:[e,{transform:[{scale:u}]}],children:r})})}i(B,"PressScale");function kd(e,t,r){let n=t&&r.revealTickMs>0,[o,s]=react.useState(0),a=react.useRef(e);return a.current=e,react.useEffect(()=>{if(!n)return;let l=setInterval(()=>{s(u=>Ed(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(kd,"useRevealedText");var Td=false;function Ub(e){e.layoutMs<=0||(Td||(Td=true,reactNative.Platform.OS==="android"&&typeof reactNative.UIManager.setLayoutAnimationEnabledExperimental=="function"&&reactNative.UIManager.setLayoutAnimationEnabledExperimental(true)),reactNative.LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}));}i(Ub,"animateLayout");function br(e,t){let r=react.useRef(e);r.current!==e&&(r.current=e,Ub(t));}i(br,"useAnimateLayoutOn");var di=36,Gb=22,Kb=12,qb=12,$b=16,Yb="#000",Xb="rgba(0,0,0,0.45)";function xd({uri:e,label:t,onClose:r}){let n=F(),o=reactNativeSafeAreaContext.useSafeAreaInsets();return e===null?null:jsxRuntime.jsxs(reactNative.Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:h.closePreview,style:hn.backdrop,onPress:r,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:e},style:hn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[hn.closeWrap,{top:o.top+qb}],children:jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:Kb,style:hn.closeButton,onPress:r,children:jsxRuntime.jsx(vt,{size:Gb,color:n.color.surface,strokeWidth:2})})})]})}i(xd,"AttachmentImageLightbox");var hn=reactNative.StyleSheet.create({backdrop:{flex:1,backgroundColor:Yb,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:$b},closeButton:{width:di,height:di,borderRadius:di/2,backgroundColor:Xb,alignItems:"center",justifyContent:"center"}});var bn=12,tv=80,ci=44,_d=22,rv=.14,nv=18,ov=8,wd=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Id({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=react.useMemo(()=>iv(o),[o]);return jsxRuntime.jsxs(reactNative.View,{style:s.anchor,pointerEvents:"box-none",children:[jsxRuntime.jsx(reactNative.Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxRuntime.jsxs(reactNative.View,{style:s.bubble,children:[jsxRuntime.jsx(reactNative.View,{style:s.tilesRow,children:e.map(a=>jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:wd[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsxRuntime.jsx(reactNative.View,{style:s.tileIconWrap,children:a==="photo"?jsxRuntime.jsx(pd,{size:_d,color:o.color.brandInk,strokeWidth:1.5}):jsxRuntime.jsx(fd,{size:_d,color:o.color.brandInk,strokeWidth:1.5})}),jsxRuntime.jsx(C,{tier:"control",style:s.tileLabel,children:wd[a]})]},a))}),jsxRuntime.jsx(reactNative.View,{style:s.tail}),jsxRuntime.jsx(reactNative.View,{style:s.tailFill})]})]})}i(Id,"AttachmentPickerPopover");function iv(e){let t=e.color,r=e.radius;return reactNative.StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:rv,shadowRadius:nv,shadowOffset:{width:0,height:ov},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:tv,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:ci,height:ci,borderRadius:ci/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...E(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-bn/2,width:bn,height:bn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:bn+4,height:2,backgroundColor:t.surfaceCream}})}i(iv,"makeStyles");var Ad=56,Od=12,lv=14,uv=10,dv=.45,cv="rgba(7,193,104,0.55)",pv="rgba(185,28,28,0.55)",fv=200,mv=300,Hd=20,fi=22,yv=12,gv="rgba(0,0,0,0.78)",Fd=220,Md=100,Ld="rgba(255,255,255,0.15)";function Bd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=react.useMemo(()=>jd(a),[a]);return e.length===0&&t===null?null:jsxRuntime.jsxs(reactNative.View,{style:l.strip,children:[e.length>0?jsxRuntime.jsx(reactNative.View,{style:l.cards,children:e.map(u=>jsxRuntime.jsx(hv,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsxRuntime.jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsxRuntime.jsx(C,{style:l.rejected,accessibilityRole:"alert",children:Su(t)}):null]})}i(Bd,"AttachmentStrip");function hv({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=F(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=react.useRef(e.status),[c,p]=react.useState(false);return react.useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxRuntime.jsxs(reactNative.View,{style:t.card,children:[jsxRuntime.jsx(reactNative.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:jsxRuntime.jsxs(reactNative.View,{style:t.thumb,children:[jsxRuntime.jsx(reactNative.Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsxRuntime.jsx(reactNative.View,{style:t.uploadingOverlay,children:jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsxRuntime.jsx(bv,{styles:t,onDone:()=>p(false)}):null]})}),l?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsxRuntime.jsx(reactNative.View,{style:t.failedInner,children:jsxRuntime.jsx(vt,{size:Hd,color:s.color.surface,strokeWidth:2})})}):null,jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:K(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsxRuntime.jsx(vt,{size:yv,color:s.color.surface,strokeWidth:1.5})})]})}i(hv,"PreviewCard");function bv({styles:e,onDone:t}){let r=F(),n=X(),o=react.useRef(null);o.current===null&&(o.current=new reactNative.Animated.Value(0));let s=o.current;return react.useEffect(()=>{let a=reactNative.Animated.sequence([reactNative.Animated.timing(s,{toValue:1,duration:fv,useNativeDriver:true}),reactNative.Animated.delay(n.uploadFlashMs),reactNative.Animated.timing(s,{toValue:0,duration:mv,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsxRuntime.jsx(reactNative.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsxRuntime.jsx(tt,{size:Hd,color:r.color.surface,strokeWidth:2})})}i(bv,"SuccessFlash");function zd({images:e,onPreview:t}){let r=F(),n=react.useMemo(()=>jd(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsxRuntime.jsx(reactNative.View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsxRuntime.jsx(reactNative.Image,{source:{uri:s.uri},style:o?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${s.uri}-${a}`))})}i(zd,"SentImages");function jd(e){let t=e.color,r=e.type;return reactNative.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Ad,height:Ad,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Od,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...reactNative.StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:tl(e.color.brandInk,dv)??e.color.brandSofter},successOverlay:{...reactNative.StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:cv},failedOverlay:{...reactNative.StyleSheet.absoluteFillObject,borderRadius:Od,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:pv},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:fi,height:fi,borderRadius:fi/2,backgroundColor:gv,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Fd,height:Fd,borderRadius:lv,backgroundColor:Ld},gridImage:{width:Md,height:Md,borderRadius:uv,backgroundColor:Ld}})}i(jd,"makeStyles");var vv="file",Cv="chat attachment upload: the file handle has no uri",Ev="chat attachment upload failed";function Rv(e){return {uri:e.uri,name:po(e.name),type:e.mimeType}}i(Rv,"filePartOf");function Wd(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Cv));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Ev)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(vv,Rv(r));let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(Wd,"createRnChatAttachmentTransport");function vn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Y(),o=react.useMemo(()=>Qe(e.registry.services.authFor(t)),[e,t,n]),[s,a]=react.useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},u=react.useRef(0),d=react.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]);react.useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=react.useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return react.useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:d}),[l.pets,l.loading,l.error,c,d])}i(vn,"useEverfurPets");function Gd(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Gd,"headerPetOf");function me(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(me,"slotBox");function hi(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(hi,"ownGroundSlot");function we(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(we,"slotText");var Kd=Object.freeze({visitButton:"Talk to a vet"});var qd=Symbol.for("@everfur/sdk/televet");function Ge(){let e=globalThis,t=e[qd];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[qd]=r,r}i(Ge,"televetGlobal");function Cn(e){let t=Ge();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Cn,"publish");function $d(e){let t=Ge().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i($d,"callTelevetPresenter");function Yd(e){let t=Ge();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Yd,"subscribeTelevetExperience");function bi(){return Ge().snapshot}i(bi,"televetExperienceSnapshot");function xv(){return Ge().hosts.length>0}i(xv,"hasTelevetHost");function Xd(e){if(!xv())return false;let t=Object.freeze({...e});return Cn({request:t,serial:Ge().snapshot.serial+1}),true}i(Xd,"presentTelevetExperience");function vi(){Ge().snapshot.request!==null&&Cn({request:null});}i(vi,"dismissTelevetExperience");function Qd(){let e=Ge(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Cn({activeHost:e.hosts[0]??null}),t}i(Qd,"claimTelevetHost");function Zd(e){let t=Ge();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Cn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(Zd,"releaseTelevetHost");var Jd=false;function En(e,t){return t!==void 0?(q(t,e),"onStartInApp"):$d(e)==="presented"?"presenter":Xd(e)?"experience":(Jd||(Jd=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(En,"openVetVisitInApp");function rc(e){let t=null;return ()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null);}),r}}i(rc,"memoizeTelevetLoader");function nc(e){let[t,r]=react.useState(null);react.useEffect(()=>{let d=Qd();return r(d),()=>{Zd(d);}},[]);let n=react.useSyncExternalStore(Yd,bi,bi),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=react.useState(null),u=s!==null&&a===null;return react.useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),vi());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:vi}}i(nc,"useTelevetExperienceHost");var wv=rc(()=>import('@everfur/sdk/televet/booking'));function Er(){let e=nc(wv);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsxRuntime.jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(Er,"EverfurTelevetHost");var Ci=Object.freeze(["visit","join","summary","messages"]);function Ei(e){return typeof e=="string"&&Ci.includes(e)}i(Ei,"isVetVisitIntent");var Av="/widget/v1/televet/handoffs",Ov="/widget/v1/televet/availability",Fv="/widget/v1/televet/chat-entry",Mv=/^[a-z0-9][a-z0-9_-]{0,39}$/,Lv=/^[A-Za-z0-9_-]{22}$/;var oc=32,ic=128,sc=64;function Si(e){let t=e.httpStatus;switch(e.code){case "sessionRequired":return "sessionRequired";case "authExpired":case "authRejected":return "authRejected";case "sdkUpdateRequired":return "sdkUpdateRequired";case "validationFailed":return "invalidRequest";case "rateLimited":case "quotaExceeded":return "rateLimited";}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(Si,"vetVisitErrorReasonOf");function ac(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(ac,"invalid");function Ri(e){return v(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Ri,"unusable");function Dv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Mv.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let s=t?.visitRef,a=t?.intent,l=s!=null;if(l){let u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>sc)return {ok:false,message:`visitRef must be 1..${sc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Ei(a))return {ok:false,message:`intent must be one of ${Ci.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(Dv,"handoffBody");function Nv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Ei(r)?null:Object.freeze({visitRef:t,intent:r})}i(Nv,"parseVisitEcho");function uc(e){let t=e.funnel??ke({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(lc(r,"televet.visit.handoff_failed",{reason:Si(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let g=typeof o=="string"?[...o].length:0;if(g<1||g>ic)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${ic} characters`}));a=o;}let l=Dv(a,s);if(!l.ok){let g=ac(l.message);return g.ok?g:n(g.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:Av,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Uv(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!Lv.test(f))){let g=Ri("the handoff response carried no usable return flow id");return g.ok?g:n(g.error)}let m=u.visit_ref!==void 0,y=m?Nv(d.value?.visit):null;if(m&&y===null){let g=Ri("the handoff response did not confirm the visit it opens");return g.ok?g:n(g.error)}let k=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return k===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(lc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(k))},async checkAvailability(o){if(typeof o!="string"||o.length>oc)return ac(`state must be at most ${oc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Ov,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?Ri("the availability response carried no usable answer"):M(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Fv},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(uc,"createVetVisitController");function Uv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!zv(t)?null:Object.freeze({url:t,expiresAt:r})}i(Uv,"parseHandoff");var Vv=new Set(["localhost","127.0.0.1","[::1]"]),Hv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Bv=/[\s\u0000-\u001f\u007f]/;function zv(e){if(Bv.test(e))return false;let t=Hv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),s=r==="https",a=r==="http"&&Vv.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(zv,"isOpenableVisitUrl");function lc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(lc,"safeTrack");var Ti=Object.freeze({status:"idle",error:null,errorReason:null});function Wv(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=react.useState(null);if(react.useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let y=await f.checkAvailability(n);return y.ok&&y.value.available}catch{return false}},"ask")().then(y=>{p&&d({key:l,open:y});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(Wv,"usePreflight");var Gv=Object.freeze({status:"opening",error:null,errorReason:null});function pc(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Y(),s=Mt("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=react.useMemo(()=>{if(t.controller)return t.controller;let{services:T}=r.registry;return uc({auth:T.authFor(n),telemetry:T.telemetry,...T.errorPolicy?{errorPolicy:T.errorPolicy}:{}})},[r,n,o,t.controller]),f=react.useRef(p);f.current=p;let m=react.useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),y=Wv(f,a,{usState:l,chat:u,scope:m}),k=a&&(y===null||y.open)&&(!u||d!==null),g=t.returnTo??null,[R,w]=react.useState(Ti),_=react.useRef(null),x=react.useRef({runtime:r,userRef:n,scopeEpoch:o});x.current={runtime:r,userRef:n,scopeEpoch:o};let b=react.useRef(p);b.current=p;let P=react.useRef(k);P.current=k;let L=react.useCallback((T,V)=>{if(_.current)return _.current;let j=i((ce,ot)=>(w({status:ce==="cancelled"?"idle":"error",error:ot,errorReason:ce==="cancelled"?null:ce}),Object.freeze({opened:false,reason:ce,error:ot})),"fail");if(!P.current)return Promise.resolve(j("unavailable",null));let G=e.prepare();if(!G.ok)return Promise.resolve(j(G.reason,null));let ne=x.current,de=b.current;w(Gv);let Gt=(async()=>{let ce,ot={...g!==null?{returnTo:g}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},wr=Object.keys(ot).length===0?void 0:ot,Kt=T===void 0?d:T;try{ce=await(wr===void 0?de.createHandoff(Kt):de.createHandoff(Kt,wr));}catch{return e.abandon(G.value),j("unknown",null)}let xt=x.current;if(xt.runtime!==ne.runtime||xt.userRef!==ne.userRef||xt.scopeEpoch!==ne.scopeEpoch)return e.abandon(G.value),j("cancelled",null);if(!ce.ok)return e.abandon(G.value),j(Si(ce.error),ce.error);let _t=await e.finish(G.value,ce.value);return _t!==null?j(_t,null):(w(Ti),Object.freeze(ce.value.flowId===void 0?{opened:true}:{opened:true,flowId:ce.value.flowId}))})().finally(()=>{_.current===Gt&&(_.current=null);});return _.current=Gt,Gt},[e,d,g,u]),I=react.useCallback((T,V)=>{if(!P.current)return w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let j=T===void 0?d:T,G={...j!==null?{petRef:j}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return En(G)===null?(w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(w(Ti),Promise.resolve(Object.freeze({opened:true})))},[d,l]),S=react.useCallback(T=>c?L(T,null):I(T,null),[c,L,I]),O=react.useCallback((T,V)=>c?L(void 0,{visitRef:T,intent:V??null}):I(void 0,{visitRef:T,intent:V??null}),[c,L,I]);return {available:k,isPending:s.isPending||(y?.pending??false),status:R.status,error:R.error,errorReason:R.errorReason,open:S,openVisit:O}}i(pc,"useVetVisitWith");var $v=i(e=>reactNative.Linking.openURL(e),"defaultOpenUrl");function Sn(e={}){let{openUrl:t,...r}=e,n=react.useMemo(()=>{let o=t??$v;return {prepare:i(()=>({ok:true,value:null}),"prepare"),async finish(s,a){try{return await o(a.url),null}catch{return "openFailed"}},abandon:i(()=>{},"abandon")}},[t]);return pc(n,r)}i(Sn,"useVetVisit");var fc=44,Jv=.6;function Vt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:m,onStartInApp:y,prefer:k}=e,g=k==="redirect",R=Sn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:g?"redirect":"in-app"}),w=F(),_=react.useMemo(()=>eC(w),[w]),x=react.useRef(false);if(!R.available)return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[null,jsxRuntime.jsx(Er,{})]});let b=R.status==="opening",P=r??Kd.visitButton;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(reactNative.Pressable,{onPress:i(()=>{if(!(b||x.current)){if(!g){let I={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};En(I,y)===null&&q(s,"unavailable",null);return}x.current=true,(f==null?R.open():R.openVisit(f,m??null)).then(I=>{I.opened?q(o,I.flowId??null):I.reason!=="cancelled"&&q(s,I.reason,I.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:P,accessibilityState:{busy:b,disabled:b},style:[_.button,b?_.busy:null,a],children:jsxRuntime.jsx(C,{style:[_.label,l],children:P})}),jsxRuntime.jsx(Er,{})]})}i(Vt,"VetVisitButton");function eC(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return reactNative.StyleSheet.create({button:{minHeight:fc,minWidth:fc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...me(s.vetVisitButton)},busy:{opacity:Jv},label:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...we(s.vetVisitButton)}})}i(eC,"makeStyles");function Pi(e){return sr(e)==="cat"?"cat":"dog"}i(Pi,"speciesOf");function ki(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(ki,"petAgeYears");function hc(e){let t=ki(e.ageYears),r=Pi(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(hc,"formatPetMeta");var gc=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function tC(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return gc[t%gc.length]}i(tC,"pickInitialsPalette");function xi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(xi,"getInitial");function bc(e){return {...tC(e.petRef),initial:xi(e.name)}}i(bc,"petInitials");function iC(e){return Math.max(12,Math.round(e*.42))}i(iC,"letterSize");function Sr({pet:e,size:t,ringStroke:r}){let n=F(),o=react.useMemo(()=>sC(n),[n]),s=t-r*2,a=e===null?null:bc(e),l=iC(s);return jsxRuntime.jsx(mn,{size:t,strokeWidth:r,color:n.color.success,children:jsxRuntime.jsx(reactNative.View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsxRuntime.jsx(C,{tier:"badge",style:[o.letter,{fontSize:l,lineHeight:Math.round(l*1.2),color:a===null?n.color.text.muted:a.foreground}],children:a===null?xi(null):a.initial})})})}i(Sr,"PetDisc");function sC(e){return reactNative.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...E(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(sC,"makeStyles");var wi=48,Rc=2,cC=320,pC="80%",fC="rgba(17,17,17,0.45)",mC=18,vc=22,yC=12,Cc=.4,gC=44;function Ii(e){return e?.name?.trim()||h.yourPet}i(Ii,"petDisplayName");function Sc({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=react.useMemo(()=>hC(a),[a]);return e?jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxRuntime.jsxs(reactNative.View,{style:l.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:reactNative.StyleSheet.absoluteFill,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsxRuntime.jsx(reactNative.View,{style:l.backdrop})}),jsxRuntime.jsxs(reactNative.View,{style:l.panel,accessibilityViewIsModal:true,children:[jsxRuntime.jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsxRuntime.jsx(reactNative.ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=Ii(u),p=hc(u);return jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsxRuntime.jsx(Sr,{pet:u,size:wi,ringStroke:Rc}),jsxRuntime.jsxs(reactNative.View,{style:l.copy,children:[jsxRuntime.jsx(C,{style:l.name,numberOfLines:1,children:c}),jsxRuntime.jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsxRuntime.jsx(tt,{size:mC,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsxRuntime.jsx(reactNative.View,{style:l.addDisc,children:jsxRuntime.jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsxRuntime.jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsxRuntime.jsx(C,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(Sc,"PetSwitcherSheet");function hC(e){let t=e.color,r=e.radius;return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:fC},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:vc,borderTopRightRadius:vc,gap:14,maxHeight:pC},title:{...E(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:cC,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:gC,paddingHorizontal:8},addDisc:{width:wi,height:wi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Rc,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...E(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...E(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...E(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...E(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Cc},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:yC,backgroundColor:t.brandSoft},closeText:{...E(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Cc}})}i(hC,"makeStyles");var CC=44,Pn=36,EC=22,Oi=9,RC=1.5,Tc=6,Rt=35,kn=1.75,Fi=12.4,SC=.5,TC=8,PC=28,kC=160;function Li(e,t){return Gd(e,t)}i(Li,"headerPet");function kc({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=react.useMemo(()=>_C(l),[l]),[d,c]=react.useState(false),p=Li(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,y=Ii(p),k=i(R=>{c(false),e.setActivePet(R),q(o,R);},"select"),g=s===void 0?null:()=>{c(false),q(s);};return jsxRuntime.jsxs(reactNative.View,{style:u.row,children:[jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsxRuntime.jsx(od,{size:EC,color:l.color.text.primary,strokeWidth:2}),r?jsxRuntime.jsx(reactNative.View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsxRuntime.jsx(reactNative.View,{style:u.center,pointerEvents:"box-none",children:jsxRuntime.jsx(xC,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsxRuntime.jsx(Vt,{entry:"chat",petRef:m,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsxRuntime.jsx(reactNative.View,{style:u.right,children:f?jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(h.switchActivePet,{name:y}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsxRuntime.jsx(Sr,{pet:p,size:Rt,ringStroke:kn}),jsxRuntime.jsx(reactNative.View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsxRuntime.jsx(sd,{size:TC,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsxRuntime.jsx(mn,{size:Rt,strokeWidth:kn,color:l.color.success,children:jsxRuntime.jsx(reactNative.View,{style:u.placeholderDisc})})}):jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:y,children:jsxRuntime.jsx(Sr,{pet:p,size:Rt,ringStroke:kn})})}),jsxRuntime.jsx(Sc,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:k,onAddPet:g,onClose:()=>c(false)})]})}i(kc,"ChatHeader");function xC({logoUrl:e,name:t,styles:r}){let[n,o]=react.useState(null);return e===null||n===e?null:jsxRuntime.jsx(reactNative.View,{style:r.logoBar,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:e},style:r.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:()=>o(e)})})}i(xC,"BrandLogo");function _C(e){let t=e.color,r=Rt-kn*2;return reactNative.StyleSheet.create({vetEntry:{minHeight:CC,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...E(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:t.surface},iconSlot:{borderRadius:Pn/2},iconButton:{width:Pn,height:Pn,borderRadius:Pn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Tc,right:Tc,width:Oi,height:Oi,borderRadius:Oi,backgroundColor:t.danger,borderWidth:RC,borderColor:t.surface},center:{...reactNative.StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:PC,width:kC},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Rt/2},avatarWrap:{width:Rt,height:Rt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Fi,height:Fi,borderRadius:Fi/2,borderWidth:SC,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(_C,"makeStyles");var _c=44,FC="rgba(17,17,17,0.55)",wc=26,MC=36,Ic=4,Ni=20,Ui=38,LC=18,DC=12;function Ac({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=react.useMemo(()=>NC(n),[n]),[s,a]=react.useState(null),[l,u]=react.useState(""),[d,c]=react.useState(false),[p,f]=react.useState(false),m=i(()=>{a(null),u(""),c(false),f(false);},"reset"),y=i(()=>{d||(m(),r());},"skip"),k=i(async()=>{if(d)return;c(true),f(false);let R=l.trim();await t(s,R.length>0?R:null)?m():(c(false),f(true));},"submit");if(!e)return null;let g=[...l].length>At;return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:reactNative.Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:o.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y}),jsxRuntime.jsxs(reactNative.View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsxRuntime.jsx(reactNative.View,{style:o.handle}),jsxRuntime.jsxs(reactNative.View,{style:o.header,children:[jsxRuntime.jsx(reactNative.View,{style:o.iconBadge,children:jsxRuntime.jsx(fn,{size:LC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxRuntime.jsxs(reactNative.View,{style:o.headerText,children:[jsxRuntime.jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsxRuntime.jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsxRuntime.jsx(reactNative.View,{style:o.options,children:Ko.map(R=>{let w=s===R.key;return jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:R.label,accessibilityState:{selected:w},style:[o.option,w?o.optionSelected:null],onPress:()=>a(_=>_===R.key?null:R.key),children:[jsxRuntime.jsx(C,{style:[o.optionLabel,w?o.optionLabelSelected:null],children:R.label}),jsxRuntime.jsx(reactNative.View,{style:[o.radio,w?o.radioSelected:null],children:w?jsxRuntime.jsx(tt,{size:DC,color:n.color.surface,strokeWidth:2}):null})]},R.key)})}),jsxRuntime.jsxs(reactNative.View,{style:o.inputWrap,children:[jsxRuntime.jsx(Lt,{style:o.input,placeholder:h.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:h.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsxRuntime.jsx(C,{tier:"compact",style:[o.counter,g?o.counterOver:null],children:`${[...l].length}/${At}`}):null]}),p?jsxRuntime.jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxRuntime.jsxs(reactNative.View,{style:o.actions,children:[jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:h.feedbackSubmit,accessibilityState:{busy:d,disabled:d||g},disabled:d||g,style:[o.submit,d||g?o.submitDisabled:null],onPress:()=>{k();},children:jsxRuntime.jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:y,style:o.skip,children:jsxRuntime.jsx(C,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(Ac,"FeedbackReasons");function NC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...reactNative.StyleSheet.absoluteFillObject,backgroundColor:FC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:wc,borderTopRightRadius:wc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:MC,height:Ic,borderRadius:Ic/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Ui,height:Ui,borderRadius:Ui/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...E(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...E(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,backgroundColor:t.surface},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:Ni,height:Ni,borderRadius:Ni/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...E(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...E(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...E(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...me(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...we(o.primaryButton)},skip:{minHeight:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(NC,"makeStyles");var QC=.88,ZC=420,JC=58,eE="rgba(17,17,17,0.28)",tE=.08,rE=.1,nE=.08,oE=.18,iE=.78,sE=.7,Vi=36,aE=10,lE=14,uE=12,dE=16,cE=14,Hi=8,pE=1.5,fE=.5,mE=gn(hr.standard);function yE(e){return Math.min(Math.round(e*QC),ZC)}i(yE,"drawerPanelWidth");function Fc({chat:e,history:t}){let[r,n]=react.useState(t.open),o=react.useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsxRuntime.jsx(gE,{chat:e,history:t,onHidden:o}):null}i(Fc,"HistoryDrawer");function gE({chat:e,history:t,onHidden:r}){let n=F(),o=react.useMemo(()=>bE(n),[n]),s=X(),a=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:l}=reactNative.useWindowDimensions(),u=yE(l),d=t.open,c=react.useRef(null);c.current===null&&(c.current=new reactNative.Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;react.useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let R=reactNative.Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:mE,useNativeDriver:true});return R.start(({finished:w})=>{w&&!d&&r();}),()=>R.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,y=t.rows.length===0,k=y&&t.loading?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,accessibilityLabel:Z.loading,accessibilityState:{busy:true},children:[jsxRuntime.jsx(reactNative.ActivityIndicator,{color:n.color.onPrimary}),jsxRuntime.jsx(C,{style:o.emptyBody,children:Z.loading})]}):y&&t.error!==null?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:Z.loadFailed}),jsxRuntime.jsx(C,{style:o.emptyBody,children:t.error}),jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsxRuntime.jsx(C,{tier:"control",style:o.retryText,children:Z.retry})})]}):jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?Z.empty:Z.noMatch}),jsxRuntime.jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?Z.emptyBody:Z.noMatchBody})]}),g=!t.searching&&t.loadingMore?jsxRuntime.jsx(reactNative.View,{style:o.loadMoreFooter,children:jsxRuntime.jsx(C,{style:o.loadMoreLabel,children:Z.loadingMore})}):null;return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxRuntime.jsxs(reactNative.View,{style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:reactNative.StyleSheet.absoluteFill,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Z.closeA11y,children:jsxRuntime.jsx(reactNative.Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsxRuntime.jsx(reactNative.Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(JC,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:reactNative.Platform.OS==="ios"?"padding":"height",children:[jsxRuntime.jsxs(reactNative.View,{style:o.searchRow,children:[jsxRuntime.jsxs(reactNative.View,{style:o.searchPill,children:[jsxRuntime.jsx(md,{size:cE,color:n.color.text.muted,strokeWidth:1.5}),jsxRuntime.jsx(Lt,{value:t.query,onChangeText:R=>t.setQuery(R.replace(/^\s+/,"")),style:o.searchInput,placeholder:Z.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Z.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.newConversation,style:o.newButton,onPress:t.newConversation,children:jsxRuntime.jsx(yd,{size:dE,color:n.color.text.primary,strokeWidth:1.5})})]}),jsxRuntime.jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:Z.heading}),t.error!==null&&!y?jsxRuntime.jsx(reactNative.View,{style:o.errorCard,children:jsxRuntime.jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsxRuntime.jsx(reactNative.FlatList,{data:m,keyExtractor:R=>R.id,renderItem:({item:R})=>jsxRuntime.jsx(hE,{row:R,active:R.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(R.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:g,onEndReached:t.loadMore,onEndReachedThreshold:fE})]})})]})})}i(gE,"DrawerModal");function hE({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:Gu(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:jsxRuntime.jsxs(reactNative.View,{style:n.itemRow,children:[jsxRuntime.jsx(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:un(e.title)}),s?jsxRuntime.jsx(reactNative.View,{style:n.unreadDot}):null]})})}i(hE,"Row");function wn(e,t){if(!/^#[0-9a-f]{6}$/i.test(e))return "transparent";let r=Math.round(Math.min(1,Math.max(0,t))*255);return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}i(wn,"inkWash");function bE(e){let t=e.color,r=e.slots,n=t.onPrimary;return reactNative.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:eE},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.brand,paddingHorizontal:16,borderRightWidth:.5,borderRightColor:t.brandBorder,gap:12},keyboardAvoider:{flex:1,gap:12},searchRow:{flexDirection:"row",alignItems:"center",gap:10},searchPill:{flex:1,flexDirection:"row",alignItems:"center",gap:8,borderRadius:e.radius.pill,backgroundColor:t.surface,paddingHorizontal:14,paddingVertical:10,borderWidth:1,borderColor:wn(n,rE)},searchInput:{...E(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:Vi,height:Vi,borderRadius:Vi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...E(e,"bold"),fontSize:14,lineHeight:17,color:n,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:aE},itemActive:{backgroundColor:wn(n,tE)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...E(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:n},itemTitleUnread:E(e,"bold"),unreadDot:{width:Hi,height:Hi,borderRadius:Hi/2,backgroundColor:t.danger,borderWidth:pE,borderColor:n},errorCard:{borderRadius:uE,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...E(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:lE,padding:14,gap:6,backgroundColor:wn(n,nE),borderWidth:.5,borderColor:wn(n,oE)},emptyTitle:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...E(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:iE},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...me(r.primaryButton)},retryText:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n,...we(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...E(e,"regular"),fontSize:11,lineHeight:14,color:n,opacity:sE}})}i(bE,"makeStyles");function Mc(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}i(Mc,"chatVetVisitOptions");var RE=16,SE=.75,Bi=12,Lc=15,TE=18,In=22,PE=14,kE=8,xE=20,_E=10,wE=13;function Nc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=react.useMemo(()=>IE(s),[s]),l=X(),u=e.tier,d=e.source;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(ui,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxRuntime.jsxs(reactNative.View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsxRuntime.jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsxRuntime.jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsxRuntime.jsx(bt,{render:()=>r(u.level),fallback:jsxRuntime.jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsxRuntime.jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:kE,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsxRuntime.jsx(vt,{size:PE,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsxRuntime.jsx(ui,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:_E,onPress:e.expand,children:jsxRuntime.jsx(dd,{size:xE,color:s.color.text.muted,strokeWidth:2})})})]})}i(Nc,"UrgencyBanner");function Dc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=Sn(Mc(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{q(r,e.level);}:null;if(u===null)return null;let d=hi(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.findVetA11y,accessibilityState:{busy:l},containerStyle:o.findVetSlot,style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,l?o.findVetBusy:null],onPress:u,children:[jsxRuntime.jsx(gd,{size:wE,color:d,strokeWidth:1.5}),jsxRuntime.jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(Dc,"VetAction");function IE(e){let t=hi(e.slots.vetVisitButton);return reactNative.StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:RE,borderWidth:SE,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...E(e,"monoBold"),fontSize:Bi,lineHeight:Lc},reason:{...E(e,"regular"),fontSize:Bi,lineHeight:TE,paddingRight:In},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...me(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...E(e,"monoBold"),fontSize:Bi,lineHeight:Lc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:In,height:In,borderRadius:In/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(IE,"makeStyles");function Uc(){let e=vn(),{handle:t}=Y(),r=react.useCallback(n=>t.setActivePet(n),[t]);return react.useMemo(()=>({...e,setActivePet:r}),[e,r])}i(Uc,"useChatPets");var Kc=300,qc=3e3,Hc=120,Bt=44,LE=120,DE="86%",Bc=15,zc=22,An=.5,NE=.04,UE=8,VE=2,HE=1,BE=.6,zE=22,jE=48,jc=1.25,WE=14,GE=18,KE=6,qE=14,$E=.04,YE=12,XE=2,QE=2,Wc=36,ZE=20,Ht=36,zt=(Bt-Ht)/2,$c=24,Yc=22,JE=.4,On=30,Xc=20,eR=.4,tR=480,rR=8,Gc=14,nR=10,oR=14,iR=12,sR=13,aR=18,lR="12%";function Ce(){let e=F(),t=react.useMemo(()=>uR(e),[e]);return {theme:e,styles:t}}i(Ce,"useChatTheme");function uR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return reactNative.StyleSheet.create({container:{flex:1,minHeight:Hc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Hc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:lR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:tR,gap:18},errorText:{...E(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Bt,minWidth:Bt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...me(s.primaryButton)},retryLabel:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...we(s.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.lg,backgroundColor:t.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Bt,justifyContent:"center"},turnNoticeActionLabel:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...E(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},list:{flex:1},listContent:{padding:r.lg,gap:r.md},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:DE},bubbleUser:{padding:Bc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:An,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:NE,shadowRadius:UE,shadowOffset:{width:0,height:VE},elevation:HE,...me(s.userBubble,An)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...me(s.assistantBubble,An)}:{padding:Bc,borderRadius:n.xl,...me(s.assistantBubble,An)},bubblePending:{opacity:BE},bubbleTextUser:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:zc,...we(s.userBubble)},bubbleTextAssistant:{...E(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:zc,...we(s.assistantBubble)},bubbleBold:E(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:E(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:rR},followUpSlot:{alignSelf:"stretch",borderRadius:Gc},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:iR,paddingVertical:nR,paddingHorizontal:oR,borderRadius:Gc,backgroundColor:t.brandSoft},followUpText:{...E(e,"medium"),flex:1,color:t.text.primary,fontSize:sR,lineHeight:aR},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:jE,justifyContent:"center",paddingLeft:WE,paddingRight:GE,paddingVertical:KE,backgroundColor:t.composerFill,borderWidth:jc,borderColor:t.composerBorder,borderRadius:zE,shadowColor:t.shadow,shadowOpacity:$E,shadowRadius:YE,shadowOffset:{width:0,height:XE},elevation:QE,...me(s.composerInput,jc)},composerRow:{flexDirection:"row",alignItems:"center",gap:qE,minHeight:Wc},attachControl:{width:On,height:On,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:eR},input:{flex:1,minHeight:Wc,maxHeight:LE,paddingHorizontal:0,paddingVertical:0,...E(e,"regular"),fontSize:o.size.body,lineHeight:ZE,color:t.text.primary,...we(s.composerInput)},sendControl:{minHeight:Ht,minWidth:Ht,alignItems:"center",justifyContent:"center"},sendDisc:{width:Ht,height:Ht,borderRadius:Ht/2,alignItems:"center",justifyContent:"center",...me(s.sendButton)},sendControlDisabled:{opacity:JE},poweredBy:{...E(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(uR,"makeStyles");var dR=Object.freeze({kind:"live"}),cR=Object.freeze({kind:"folded"});function ji(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=no(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(ji,"askOf");function Zc(e){let t=new Map,r=new Map;for(let o of e){let s=ji(o);if(s===null)continue;let a=r.get(s.caseId);(a===void 0||s.dueDay>=a.dueDay)&&r.set(s.caseId,{messageId:o.id,dueDay:s.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let s=ji(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,dR),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,cR);continue}let a=[s.dueDay];n={id:o.id,caseId:s.caseId,days:a},t.set(o.id,{kind:"past",runDueDays:a});}return t}i(Zc,"placeCheckins");var Qc=864e5,pR=365;function Fn(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let o=Math.floor(n/Qc)-Math.floor(r/Qc);return o<1||o>pR?null:o}i(Fn,"checkinDayNumber");function Jc(e){return ji(e)?.dueDay||null}i(Jc,"checkinDueDay");var Se=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),ep=Object.freeze(Vr.map(e=>Object.freeze({answer:e,label:Se.answers[e]})));function tp(e,t){let[r,n]=react.useState(null),[o,s]=react.useState(null),[a,l]=react.useState(null),u=react.useCallback(c=>{t!==null&&(n(c),s(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):s(p.error);}));},[t,e.caseId]),d=a??e.answer;return {answer:d,answerable:!ua(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(tp,"useCheckinCard");var op=44,yR=.6;function sp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s}){let a=F(),l=react.useMemo(()=>gR(a),[a]),u=tp(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable,p=Fn(t.openedAt,Jc(e));return jsxRuntime.jsxs(reactNative.View,{style:l.card,accessibilityLabel:Se.eyebrow,children:[jsxRuntime.jsxs(reactNative.View,{style:l.head,children:[jsxRuntime.jsx(C,{tier:"compact",style:l.eyebrow,children:Se.eyebrow}),p!==null?jsxRuntime.jsx(C,{tier:"compact",style:l.headDay,children:K(Se.day,{day:p})}):null]}),jsxRuntime.jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsxRuntime.jsx(reactNative.View,{style:[l.row,u.pending?l.rowPending:null],children:ep.map(({answer:f,label:m})=>{let y=(u.pending??u.answer)===f;return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>u.choose(f),disabled:d,accessibilityRole:"button",accessibilityLabel:m,accessibilityState:{selected:y,disabled:d,busy:u.pending===f},style:[l.pill,y?l.pillSelected:null],children:jsxRuntime.jsx(C,{tier:"control",style:[l.pillLabel,y?l.pillLabelSelected:null],children:m})},f)})}):null,u.answer!==null?jsxRuntime.jsx(C,{style:l.logged,children:Se.logged}):null,u.escalated?o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Se.findVet,style:l.findVet,children:jsxRuntime.jsx(C,{tier:"control",style:l.findVetLabel,children:Se.findVet})}):n?jsxRuntime.jsx(Vt,{entry:"chat",petRef:n,label:Se.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:l.findVet,labelStyle:l.findVetLabel}):null:null,t.resolutionText?jsxRuntime.jsx(C,{style:l.resolution,children:t.resolutionText}):null,u.error?jsxRuntime.jsx(C,{style:l.error,accessibilityRole:"alert",children:u.error.displayMessage}):null]})}i(sp,"CheckinCard");function gR(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:yR},pill:{flex:1,minHeight:op,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brand},pillLabel:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:op,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...E(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(gR,"makeStyles");var vR=1.5,CR=3;function lp({text:e,runDueDays:t,openedAt:r}){let n=F(),o=react.useMemo(()=>ER(n),[n]),s=t.map(l=>Fn(r,l)).filter(l=>l!==null),a=t.length>1;return a&&s.length===0?null:jsxRuntime.jsxs(reactNative.View,{style:o.row,children:[jsxRuntime.jsx(reactNative.View,{style:o.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),jsxRuntime.jsxs(reactNative.View,{style:o.body,children:[s.length>0?jsxRuntime.jsx(C,{tier:"compact",style:o.days,children:s.map(l=>K(Se.day,{day:l})).join(Se.daySeparator)}):null,a?null:jsxRuntime.jsx(C,{style:o.question,accessibilityRole:"text",children:e})]})]})}i(lp,"CheckinPastAsk");function ER(e){let t=e.color,r=e.space,n=e.type;return reactNative.StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:vR,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:CR},days:{...E(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...E(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(ER,"makeStyles");var RR=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),up="#C8BEB4";function SR(e){return e?RR[e.toUpperCase()]??up:up}i(SR,"tierColor");function TR(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(TR,"tierLabel");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ve,"text");function PR(e){let t=Ve(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(PR,"httpsUrl");function kR(e,t){let r=Ve(e.source_name)??Ve(e.sourceName),n=Ve(e.section),o=Ve(e.authority_tier)??Ve(e.authorityTier),s=TR(o),a=r??Ve(e.title)??`Source ${t+1}`,l=Ve(e.monograph_chunk_id)??Ve(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:PR(e.url),excerpt:Ve(e.excerpt),tierColor:SR(o),key:`${a}-${l??"none"}-${t}`})}i(kR,"toCitationCard");function dp(e){return e===void 0||e.length===0?xR:Object.freeze(e.map((t,r)=>kR(t,r)))}i(dp,"toCitationCards");var xR=Object.freeze([]);function $i(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i($i,"sourcesLabel");function cp(e,t){return `${t?h.hideSources:h.showSources} ${$i(e)}`}i(cp,"sourcesToggleLabel");function pp(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(pp,"citationA11yLabel");var OR=244,mp=8,yp=13,FR=14,MR=.3,LR=-0.24,DR=22,NR=10,UR=15;function gp({citations:e,onOpenUrl:t}){let r=F(),n=react.useMemo(()=>BR(r),[r]),o=react.useMemo(()=>dp(e),[e]),[s,a]=react.useState(false);if(o.length===0)return null;let l=o.length;return jsxRuntime.jsxs(reactNative.View,{style:n.block,children:[jsxRuntime.jsxs(B,{accessibilityRole:"button",accessibilityLabel:cp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsxRuntime.jsx(ad,{size:yp,color:r.color.brandInk,strokeWidth:1.5}),jsxRuntime.jsx(C,{tier:"compact",style:n.toggleLabel,children:$i(l)}),jsxRuntime.jsx(pn,{size:yp,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsxRuntime.jsx(VR,{cards:o,styles:n,open:t}):null]})}i(gp,"CitationCards");function VR({cards:e,styles:t,open:r}){let n=X(),o=Ct(n.citationsInMs,{risePx:n.citationsRisePx});return jsxRuntime.jsx(reactNative.Animated.View,{style:o,children:jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsxRuntime.jsx(HR,{card:s,styles:t,open:r},s.key))})})}i(VR,"Deck");function HR({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=pp(o?e:{...e,url:null}),a=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:t.cardHeader,children:[jsxRuntime.jsx(reactNative.View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsxRuntime.jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsxRuntime.jsx(ld,{size:FR,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsxRuntime.jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsxRuntime.jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsxRuntime.jsx(B,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>r(l),children:a})}return jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}i(HR,"Card");function BR(e){let t=e.color,r=e.space,n=e.radius,o=e.type.size;return reactNative.StyleSheet.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...E(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:MR,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:OR,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:mp,height:mp,borderRadius:n.pill},cardTitle:{...E(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:DR,color:t.text.primary,letterSpacing:LR},cardTitleLink:{color:t.linkInk},cardMeta:{...E(e,"monoMedium"),fontSize:o.nano,lineHeight:NR,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...E(e,"regular"),fontSize:o.tiny,lineHeight:UR,color:t.text.muted}})}i(BR,"makeStyles");function hp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(hp,"formatMessageTime");var kr=15,qR=15,$R=6,YR=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function Rp({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=react.useMemo(()=>XR(s),[s]),l=X(),u=e.role==="user",d=react.useMemo(()=>hp(e.createdAt),[e.createdAt]),c=t!==void 0&&e.text.length>0,p=!u&&n!==void 0&&e.responseId!==void 0,[f,m]=react.useState(false),y=react.useRef(null);react.useEffect(()=>()=>{y.current&&clearTimeout(y.current);},[]);let k=i(()=>{t!==void 0&&(Dt(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxRuntime.jsxs(reactNative.View,{style:a.wrap,children:[jsxRuntime.jsxs(reactNative.View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsxRuntime.jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:qR,onPress:k,style:a.iconHit,children:f?jsxRuntime.jsx(tt,{size:kr,color:s.color.success,strokeWidth:2}):jsxRuntime.jsx(ud,{size:kr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?vu.map(({sentiment:g,label:R})=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{selected:r===g},hitSlop:$R,onPress:()=>n?.(g),style:a.iconHit,children:jsxRuntime.jsx(fn,{size:kr,color:s.color.sentiment[g],active:r===g,rotate:YR[g],strokeWidth:1.5})},g)):null]}),o?jsxRuntime.jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(Rp,"MessageFooter");function XR(e){let t=e.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...E(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:kr,height:kr,alignItems:"center",justifyContent:"center"},thanks:{...E(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(XR,"makeStyles");var Sp="#10462E",Tp="#000000",QR="#83E0B4",ZR=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:QR,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:Sp,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit.",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),JR=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function eS(e){return e==null?e:e.replace(JR,"").trim()}i(eS,"formatBreedForPrompt");var tS=new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function rS(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return tS.has(t)}i(rS,"isUninformativeBreed");function nS(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(nS,"unspecifiedBreedLabel");function oS(e,t){return rS(e)?nS(t):String(e).replace(/\s+/gu," ").trim()}i(oS,"resolveBreedLabel");function Pp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(Pp,"emptyStateTitle");function kp(e,t=Sp){let r=Pi(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=oS(eS(e?.breed),r)||null,l=ki(e?.ageYears),u=l===null?null:String(l);return Object.freeze(ZR.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),m=d.fallbackLabel!==void 0&&(c&&!a||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,y=K(m,{petName:s,breed:a??n,species:r,ageYears:u??""}),k=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:k,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(kp,"resolveQuickPrompts");var sS=36,wp=4,aS=340;function Ip({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=react.useMemo(()=>uS(s),[s]),l=react.useMemo(()=>kp(e,s.color.brandInk),[e,s.color.brandInk]),u=Pp(e);return jsxRuntime.jsxs(reactNative.View,{style:a.block,children:[jsxRuntime.jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsxRuntime.jsx(reactNative.View,{style:a.list,children:l.map((d,c)=>jsxRuntime.jsx(lS,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Ip,"QuickPrompts");function lS({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=X(),d=Ct(u.followUpInMs,{delayMs:yn(u,t)}),c={backgroundColor:e.background,borderColor:e.borderColor,borderWidth:e.borderWidth};return e.intent==="vet_report"?s!==void 0?jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>{q(s,r);},children:jsxRuntime.jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(Vt,{entry:"chat",petRef:n,label:e.label,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:[l.chip,c],labelStyle:l.chipLabel})}):jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>o(e.label),children:jsxRuntime.jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(lS,"Chip");function uS(e){let t=e.color;return reactNative.StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...E(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:aS},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:sS,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...E(e,"bold"),fontSize:12,lineHeight:14,color:Tp,textAlign:"center"}})}i(uS,"makeStyles");var Xi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Ap(e){return e.includes("*")||e.includes("`")}i(Ap,"hasInlineMarkup");function Op(e){let t=[],r=0;Xi.lastIndex=0;for(let n=Xi.exec(e);n!==null;n=Xi.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],s=n[2],a=n[3];o!==void 0?t.push({kind:"bold",text:o}):s!==void 0?t.push({kind:"italic",text:s}):a!==void 0&&t.push({kind:"code",text:a}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(Op,"tokenizeInlineMarkdown");function Fp(e,t){return Ap(e)?Op(e).map((r,n)=>{switch(r.kind){case "bold":return jsxRuntime.jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsxRuntime.jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsxRuntime.jsx(C,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Fp,"renderInlineMarkdown");var Dp=6,Vp=520,yS=Math.round(Vp*.18),Np=.44,gS=.5,Up=[0,.5,1],hS=[0,1,2];function Hp(){let e=F(),t=react.useMemo(()=>vS(e),[e]),r=!e.motion.reducedMotion;return jsxRuntime.jsx(reactNative.View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:hS.map(n=>r?jsxRuntime.jsx(bS,{index:n,style:t.dot},n):jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotStatic]},n))})}i(Hp,"TypingIndicator");function bS({index:e,style:t}){let r=react.useRef(new reactNative.Animated.Value(0)).current;react.useEffect(()=>{let s=reactNative.Animated.sequence([reactNative.Animated.delay(e*yS),reactNative.Animated.loop(reactNative.Animated.timing(r,{toValue:1,duration:Vp,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Up,outputRange:[Np,1,Np]}),o=r.interpolate({inputRange:Up,outputRange:[0,-3.5,0]});return jsxRuntime.jsx(reactNative.Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(bS,"AnimatedDot");function vS(e){let t=e.color,r=e.space,n=e.radius;return reactNative.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:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},dot:{width:Dp,height:Dp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:gS}})}i(vS,"makeStyles");function Wp(e,t,r){switch(e){case "loading":return r.renderPending?jsxRuntime.jsx(bt,{render:r.renderPending,fallback:jsxRuntime.jsx(Bp,{})}):jsxRuntime.jsx(Bp,{});case "empty":return jsxRuntime.jsx(PS,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsxRuntime.jsx(xS,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsxRuntime.jsx(_S,{messages:t.messages,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl});default:return Xe(e)}}i(Wp,"renderView");function Bp(){let{theme:e,styles:t}=Ce(),[r,n]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>n(true),Kc);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx(reactNative.View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsxRuntime.jsx(reactNative.ActivityIndicator,{color:e.color.brandInk}):null})}i(Bp,"LoadingState");function PS({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=Ce();return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsxRuntime.jsx(Ip,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsxRuntime.jsx(Gp,{prompts:r,onSelectPrompt:n})]})}i(PS,"EmptyState");function Gp({prompts:e,onSelectPrompt:t}){let{styles:r}=Ce();return e.length===0?null:jsxRuntime.jsx(reactNative.View,{style:r.followUps,children:e.map((n,o)=>jsxRuntime.jsx(kS,{prompt:n,index:o,onSelectPrompt:t},n))})}i(Gp,"FollowUps");function kS({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Ce(),s=X(),a=Ct(s.followUpInMs,{delayMs:yn(s,t)});return jsxRuntime.jsx(reactNative.Animated.View,{style:a,children:jsxRuntime.jsxs(B,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:o.followUpSlot,style:o.followUpRow,children:[jsxRuntime.jsx(C,{style:o.followUpText,children:e}),jsxRuntime.jsx(pn,{size:AS,color:n.color.brandInk,direction:"right"})]})})}i(kS,"FollowUpRow");function xS({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ce(),o=xu(e)?Lu(r):void 0;return jsxRuntime.jsxs(reactNative.View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsxRuntime.jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsxRuntime.jsx(C,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(xS,"ErrorState");function _S({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:m,onStartNew:y,petRef:k,onFindVet:g,vet:R,onOpenUrl:w}){let{styles:_}=Ce(),x=X();br(e.length,x);let b=react.useMemo(()=>Zc(e),[e]),P=Ju(e,n),L=e[e.length-1];return jsxRuntime.jsxs(reactNative.ScrollView,{style:_.list,contentContainerStyle:_.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(I=>{let S=I.checkin?b.get(I.id):void 0;return S?.kind==="folded"?null:S?.kind==="past"?jsxRuntime.jsx(lp,{text:I.text,runDueDays:S.runDueDays,openedAt:I.checkin?.openedAt},I.id):I.checkin&&S!==void 0?jsxRuntime.jsx(sp,{message:I,checkin:I.checkin,onAnswer:o,petRef:k,onFindVet:g,vet:R},I.id):jsxRuntime.jsx(OS,{message:I,revealing:n&&I===L&&I.role==="assistant",onCopy:s,sentiment:I.responseId===void 0?null:a[String(I.responseId)]??null,onSentiment:l,thanks:u!==null&&I.responseId!==void 0&&String(I.responseId)===u,images:d[I.id]??IS,onPreview:c,onOpenUrl:w},I.id)}),f?jsxRuntime.jsx(C,{tier:"compact",style:_.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,P?jsxRuntime.jsx(Hp,{}):null,p!==null?jsxRuntime.jsx(wS,{notice:p,onRetry:m,onStartNew:y}):null,n?null:jsxRuntime.jsx(Gp,{prompts:t,onSelectPrompt:r})]})}i(_S,"PopulatedState");function wS({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Ce(),o=e.tone==="error";return jsxRuntime.jsxs(reactNative.View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsxRuntime.jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsxRuntime.jsx(reactNative.Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:zt,style:n.turnNoticeAction,children:jsxRuntime.jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(wS,"TurnNoticeCard");var IS=Object.freeze([]),AS=14;function OS({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u}){let{styles:d}=Ce(),c=X(),p=Ct(c.messageInMs),f=kd(e.text,t,c),m=e.role==="user",y=m?h.senderUser:h.senderAssistant,k=react.useCallback(R=>o(e,R),[o,e]),g=e.pending!==true;return jsxRuntime.jsxs(reactNative.Animated.View,{style:[d.rowBlock,m?d.rowBlockUser:d.rowBlockAssistant,p],children:[jsxRuntime.jsx(reactNative.View,{style:[d.row,m?d.rowUser:d.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxRuntime.jsxs(reactNative.View,{style:[d.bubble,m?d.bubbleUser:d.bubbleAssistant,e.pending?d.bubblePending:null],children:[m&&a.length>0?jsxRuntime.jsx(zd,{images:a,onPreview:R=>l({uri:R.uri,label:R.filename})}):null,jsxRuntime.jsx(C,{style:m?d.bubbleTextUser:d.bubbleTextAssistant,children:m?e.text:Fp(f,{bold:d.bubbleBold,italic:d.bubbleItalic,code:d.bubbleCode})})]})}),!m&&!t?jsxRuntime.jsx(gp,{citations:e.citations,onOpenUrl:u}):null,g?jsxRuntime.jsx(Rp,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:k,thanks:s}):null]})}i(OS,"MessageRow");var NS=Object.freeze(["photo"]),US=1;function qp(e){let{style:t,renderPending:r}=e;return jsxRuntime.jsx(Go,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsxRuntime.jsx(VS,{...e})})}i(qp,"EverfurChat");function VS({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:y,lifecycle:k,draftStore:g,vetReturnTo:R,vetUsState:w,vetPrefer:_,onOpenUrl:x}){let{theme:b,styles:P}=Ce(),L=X(),I=react.useMemo(()=>ed(e,t),[e,t]),S=mr(I),O=Qu(S),T=Uc(),V=Ku(S),j=reactNativeSafeAreaContext.useSafeAreaInsets(),G=Zu(S),ne=react.useMemo(()=>l===void 0?void 0:()=>{q(l,"emergency");},[l]),de=react.useMemo(()=>R===void 0&&w===void 0&&_===void 0?void 0:{returnTo:R,usState:w,prefer:_},[R,w,_]),Pe=Li(T.pets,S.petRef),Gt=react.useMemo(()=>Yu(S.messages,Pe?.name??null),[S.messages,Pe?.name]),ce=Xu(Gt);br(ce.showBanner,L),Vu(S.openCheckin,f),Ou(S.askEverfur,S.isBootstrapping,m);let ot=react.useMemo(()=>Jo(y),[y]);Nu(k,{conversationId:S.conversationId===null?null:String(S.conversationId),isTurnInFlight:S.isStreaming,refresh:S.refreshActiveThread});let wr=(S.hasUnreadThreads??false)||V.rows.some(Ee=>Ee.unreadCount!==null&&Ee.unreadCount>0)||(S.unreadCount??0)>0,Kt=Iu(S.messages),[xt,_t]=react.useState(null),Yp=react.useCallback(()=>_t(null),[]),[qt,Un]=react.useState(null),[Xp,es]=react.useState(null),wt=react.useRef(null);react.useEffect(()=>()=>{wt.current&&clearTimeout(wt.current);},[]);let ts=react.useCallback(Ee=>{es(String(Ee)),wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{es(null),wt.current=null;},qc);},[]),Qp=react.useCallback((Ee,Ir)=>{let $t=Ee.responseId;if($t===void 0)return;let rf=S.sentimentByMessage[String($t)];S.feedback($t,Ir),Ir==="down"&&rf!=="down"&&Un($t);},[S]),Zp=react.useCallback(async(Ee,Ir)=>qt===null||!(await S.feedback(qt,"down",Ee??"other",Ir)).ok?false:(Un(null),ts(qt),true),[S,qt,ts]),Jp=react.useCallback(()=>Un(null),[]),ef=react.useCallback(Ee=>{S.send(Ee);},[S.send]),tf=react.useMemo(()=>x===void 0?void 0:Ee=>{q(x,Ee,"citation");},[x]),rs={send:S.send,stop:S.stop,isStreaming:S.isStreaming,conversationId:S.conversationId,seed:ot,draftStore:g,onStage:Kt.stage,onPreview:_t};return jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:[P.container,{paddingTop:j.top},r],behavior:reactNative.Platform.OS==="ios"?"padding":void 0,children:[jsxRuntime.jsx(kc,{pets:T,petRef:S.petRef,historyUnread:wr,onOpenHistory:V.show,onPetChange:s,onAddPet:p,vet:de}),c!==void 0?jsxRuntime.jsx(HS,{petRef:e??null,pet:c,onRegistered:T.refresh}):null,jsxRuntime.jsx(Nc,{surface:ce,petRef:S.petRef,renderVetAction:u,onFindVet:l,vet:de}),jsxRuntime.jsx(reactNative.View,{style:P.body,children:Wp(O,S,{notice:G,vet:de,onCheckinFindVet:ne,onSelectPrompt:ef,renderPending:n,shownPet:Pe,onVetPrep:a,onCopy:o,onSentiment:Qp,thanksFor:Xp,imagesByMessage:Kt.byMessage,onPreview:_t,onAddPet:p,onOpenUrl:tf})}),d!==void 0?jsxRuntime.jsx(BS,{...rs,attachments:d}):jsxRuntime.jsx($p,{...rs,attachments:null}),jsxRuntime.jsx(nd,{}),b.meta.hidePoweredBy?null:jsxRuntime.jsx(C,{tier:"compact",style:P.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsxRuntime.jsx(Fc,{chat:S,history:V}),jsxRuntime.jsx(Ac,{visible:qt!==null,onSubmit:Zp,onSkip:Jp}),jsxRuntime.jsx(xd,{uri:xt?.uri??null,label:xt?.label??"",onClose:Yp}),jsxRuntime.jsx(Er,{})]})}i(VS,"ChatBody");function HS({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ce(),o=_u(e,t,r);return o.status!=="failed"||o.error===null?null:jsxRuntime.jsxs(reactNative.View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsxRuntime.jsx(reactNative.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:zt,children:jsxRuntime.jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(HS,"PetSetupNotice");function BS({attachments:e,...t}){let r=react.useMemo(()=>Wd(),[]),n=an({maxPerMessage:e.maxPerMessage??US,transport:r}),o=react.useMemo(()=>({state:n,sources:e.sources??NS,pick:e.pick}),[n,e.sources,e.pick]);return jsxRuntime.jsx($p,{...t,attachments:o})}i(BS,"ComposerWithAttachments");function $p({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=Ce(),p=X(),[f,m]=zu(e,n,s);ju(a,n===null?null:String(n),f,m);let[y,k]=react.useState(false),[g,R]=react.useState(false);react.useEffect(()=>{R(false);},[n]);let w=d.meta.placeholder??h.placeholder,_=o?.state.uploading??false,x=o?.state.failed??false,b=_||x,P=o?.state.attachments??zS;br(P.length,p);let L=react.useCallback(()=>{if(f.trim().length===0||b||[...f].length>Ot)return;let G=o?.state.s3Keys??jS;o!==null&&G.length>0?(l(o.state.attachments.filter(ne=>ne.status==="uploaded").map(ne=>({uri:ne.previewUri,filename:ne.filename}))),e(f,{imageS3Keys:G}),o.state.clear()):e(f),m(""),R(false);},[f,e,b,o,l]),I=react.useCallback(()=>{t();},[t]),S=react.useCallback(G=>{k(false),o!==null&&(R(false),o.state.dismissRejected(),Dt(o.pick,G).then(ne=>{if(!ne.ok){R(true);return}ne.value!==null&&o.state.add(ne.value);}));},[o]),T=react.useMemo(()=>[...f].length>Ot,[f])||b,V=o!==null&&P.length>=o.state.maxPerMessage,j=d.slots.sendButton?.textColor??d.color.brandInk;return jsxRuntime.jsxs(reactNative.View,{style:c.composerOuter,children:[o!==null&&y?jsxRuntime.jsx(Id,{sources:o.sources,full:V,onPick:S,onClose:()=>k(false)}):null,jsxRuntime.jsxs(reactNative.View,{style:c.composer,children:[o!==null?jsxRuntime.jsx(Bd,{attachments:P,rejected:g?WS:o.state.rejected,uploadFailed:x,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:G=>u({uri:G.previewUri,label:G.filename})}):null,jsxRuntime.jsxs(reactNative.View,{style:c.composerRow,children:[o!==null?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:Tu(P.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:y},disabled:V,hitSlop:(Bt-On)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>k(G=>!G),children:jsxRuntime.jsx(cd,{size:Xc,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsxRuntime.jsx(Lt,{style:c.input,value:f,onChangeText:m,placeholder:w,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:w,onSubmitEditing:L,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsxRuntime.jsx(reactNative.Pressable,{onPress:I,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:zt,style:c.sendControl,children:jsxRuntime.jsx(reactNative.View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsxRuntime.jsx(bd,{size:Yc,color:j,testID:"everfur-stop-glyph"})})}):jsxRuntime.jsx(reactNative.Pressable,{onPress:L,disabled:T,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:T,busy:_},hitSlop:zt,style:[c.sendControl,T?c.sendControlDisabled:null],children:jsxRuntime.jsx(reactNative.View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsxRuntime.jsx(hd,{size:$c,color:j,testID:"everfur-send-glyph"})})})]})]})]})}i($p,"Composer");var zS=Object.freeze([]),jS=Object.freeze([]),WS=Object.freeze({code:"unknown",retryable:true,filename:""});function YS(e){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=react.useMemo(()=>Qe(t.registry.services.authFor(r)),[t,r,n]),s=react.useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=react.useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=react.useRef(0),c=react.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 react.useEffect(()=>(c(),()=>{d.current+=1;}),[c]),react.useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(YS,"useEverfurPetProfile");function QS(e){return react.createElement(nn,{clientTheme:e.clientTheme??null,seams:sn,children:e.children})}i(QS,"EverfurThemeProvider");exports.CapabilityGate=Go;exports.EverfurChat=qp;exports.EverfurConfigError=Q;exports.EverfurProvider=kh;exports.EverfurThemeProvider=QS;exports.EverfurThrownError=Ar;exports.THEME_SLOT_KEYS=qy;exports.THEME_SLOT_NAMES=mt;exports.canonicalPetSpecies=sr;exports.categoryFor=Hn;exports.conversationId=cf;exports.createRnRecordsUploadTransport=kf;exports.face=E;exports.isErr=sf;exports.isOk=of;exports.isRetryableCode=Bn;exports.petRef=uf;exports.previewTheme=Eg;exports.unwrap=af;exports.useCapability=Mt;exports.useChatAttachments=an;exports.useEverfur=Xl;exports.useEverfurChat=mr;exports.useEverfurPetProfile=YS;exports.useEverfurPets=vn;exports.useEverfurTheme=F;exports.userFacingError=It;exports.userRef=df;