@everfur/sdk 1.5.0 → 1.5.2

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 (87) hide show
  1. package/dist/{bookingCopy.d-BuDv16WP.d.ts → bookingCopy.d-BL2-URcv.d.ts} +3 -2
  2. package/dist/{bookingCopy.d-rnBSqOSN.d.cts → bookingCopy.d-Dfew1pjY.d.cts} +3 -2
  3. package/dist/care/index.cjs +2 -2
  4. package/dist/care/index.js +2 -2
  5. package/dist/chat/index.cjs +235 -234
  6. package/dist/chat/index.js +311 -310
  7. package/dist/chat/lite/index.cjs +339 -338
  8. package/dist/chat/lite/index.js +314 -313
  9. package/dist/{chunk-4KFFE42Z.js → chunk-2T5CB5MW.js} +20 -20
  10. package/dist/{chunk-HHCGXQJR.js → chunk-ASE36WGP.js} +11 -11
  11. package/dist/{chunk-6IHY7HS7.js → chunk-CMDCBYUH.js} +1 -1
  12. package/dist/{chunk-BMYNDBUR.js → chunk-K7YHXFPQ.js} +1 -1
  13. package/dist/client/index.cjs +1 -1
  14. package/dist/client/index.d.cts +2 -2
  15. package/dist/client/index.d.ts +2 -2
  16. package/dist/client/index.js +1 -1
  17. package/dist/core/index.cjs +31 -31
  18. package/dist/core/index.js +31 -31
  19. package/dist/health-plan/index.cjs +266 -266
  20. package/dist/health-plan/index.js +443 -443
  21. package/dist/{inbox.d-DJ9xgU1Z.d.ts → inbox.d-B2JXK0uI.d.ts} +1 -1
  22. package/dist/{inbox.d-CPcMMz-Y.d.cts → inbox.d-CwA1ogzV.d.cts} +1 -1
  23. package/dist/index.cjs +257 -256
  24. package/dist/index.js +364 -363
  25. package/dist/{models.d-BULqCO2R.d.ts → models.d-NAWqF1wC.d.ts} +4 -1
  26. package/dist/{models.d-BKmOfoqV.d.cts → models.d-wJ_Ze4p5.d.cts} +4 -1
  27. package/dist/notifications/inbox/index.cjs +28 -28
  28. package/dist/notifications/inbox/index.d.cts +5 -5
  29. package/dist/notifications/inbox/index.d.ts +5 -5
  30. package/dist/notifications/inbox/index.js +53 -53
  31. package/dist/notifications/index.cjs +1 -1
  32. package/dist/notifications/index.d.cts +3 -3
  33. package/dist/notifications/index.d.ts +3 -3
  34. package/dist/notifications/index.js +1 -1
  35. package/dist/{parse.d-Cj3fURer.d.ts → parse.d-QjB2LJCd.d.ts} +19 -10
  36. package/dist/{parse.d-cH7ZmMeo.d.cts → parse.d-_Ttu2h5g.d.cts} +19 -10
  37. package/dist/records/depth/index.cjs +80 -80
  38. package/dist/records/depth/index.js +115 -115
  39. package/dist/records/index.cjs +653 -653
  40. package/dist/records/index.js +1074 -1074
  41. package/dist/{route.d-DSYEd2MR.d.ts → route.d-DtuKY5dM.d.ts} +1 -1
  42. package/dist/{route.d-DCzQh4ix.d.cts → route.d-Nt-r-7IO.d.cts} +1 -1
  43. package/dist/server/events/index.cjs +1 -1
  44. package/dist/server/events/index.js +1 -1
  45. package/dist/server/index.cjs +1 -1
  46. package/dist/server/index.js +1 -1
  47. package/dist/shop/index.cjs +188 -188
  48. package/dist/shop/index.js +386 -386
  49. package/dist/shop/orders-v2/index.cjs +72 -72
  50. package/dist/shop/orders-v2/index.js +126 -126
  51. package/dist/tabs/index.cjs +114 -111
  52. package/dist/tabs/index.d.cts +19 -6
  53. package/dist/tabs/index.d.ts +19 -6
  54. package/dist/tabs/index.js +191 -188
  55. package/dist/televet/booking/index.cjs +214 -212
  56. package/dist/televet/booking/index.d.cts +2 -2
  57. package/dist/televet/booking/index.d.ts +2 -2
  58. package/dist/televet/booking/index.js +344 -342
  59. package/dist/televet/call/index.cjs +53 -53
  60. package/dist/televet/call/index.js +67 -67
  61. package/dist/{useInboxUnread.d-CXiaR3BZ.d.ts → useInboxUnread.d-0DrQPn7J.d.ts} +1 -1
  62. package/dist/{useInboxUnread.d-DERpMelw.d.cts → useInboxUnread.d-CRcOTkmu.d.cts} +1 -1
  63. package/dist/web/health-plan/index.cjs +1 -1
  64. package/dist/web/health-plan/index.js +1 -1
  65. package/dist/web/inbox/index.cjs +1 -1
  66. package/dist/web/inbox/index.d.cts +6 -6
  67. package/dist/web/inbox/index.d.ts +6 -6
  68. package/dist/web/inbox/index.js +1 -1
  69. package/dist/web/index.cjs +184 -184
  70. package/dist/web/index.js +181 -181
  71. package/dist/web/notifications/index.cjs +1 -1
  72. package/dist/web/notifications/index.d.cts +2 -2
  73. package/dist/web/notifications/index.d.ts +2 -2
  74. package/dist/web/notifications/index.js +1 -1
  75. package/dist/web/records-sheet/index.cjs +1 -1
  76. package/dist/web/records-sheet/index.js +1 -1
  77. package/dist/web/shop/index.cjs +1 -1
  78. package/dist/web/shop/index.js +2 -2
  79. package/dist/web/televet/booking/index.cjs +7 -8
  80. package/dist/web/televet/booking/index.d.cts +2 -2
  81. package/dist/web/televet/booking/index.d.ts +2 -2
  82. package/dist/web/televet/booking/index.js +7 -8
  83. package/dist/web/televet/call/index.cjs +1 -1
  84. package/dist/web/televet/call/index.js +1 -1
  85. package/dist/web/ui/index.cjs +1 -1
  86. package/dist/web/ui/index.js +33 -33
  87. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- "use strict";var e=require("zod"),t=require("react"),r=require("react-native"),n=require("react-native-safe-area-context"),i=require("react-native-sse"),l=require("react/jsx-runtime"),o=require("@everfur/sdk/televet/booking"),s=require("@everfur/sdk/texting");function a(e){return e&&e.__esModule?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);if(e){Object.keys(e).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:true,get:function(){return e[r]}})}})}t.default=e;return Object.freeze(t)}var c=/*#__PURE__*/a(i);var d=/*#__PURE__*/u(o);var f=/*#__PURE__*/u(s);function h(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function p(e){return[...e].length}function ok(e,t){/* @__PURE__ */
2
+ "use strict";var e=require("zod"),t=require("react"),r=require("react-native"),n=require("react-native-safe-area-context"),i=require("react-native-sse"),l=require("react/jsx-runtime"),o=require("@everfur/sdk/televet/booking"),s=require("@everfur/sdk/texting");function a(e){return e&&e.__esModule?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);if(e){Object.keys(e).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:true,get:function(){return e[r]}})}})}t.default=e;return Object.freeze(t)}var c=/*#__PURE__*/u(r);var d=/*#__PURE__*/a(i);var f=/*#__PURE__*/u(o);var h=/*#__PURE__*/u(s);function p(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function g(e){return[...e].length}function ok(e,t){/* @__PURE__ */
3
3
  return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
4
- return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var g=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new g(e.error)}var m=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var b=128,y=128,v=/[\u0000-\u001F\u007F]/,x=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=p(t);if(r===0||r>y)throw new m("invalid-argument",`petRef must be 1..${y} characters`);if(v.test(t))throw new m("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=p(t);if(r===0||r>b)throw new m("invalid-argument",`userRef must be 1..${b} characters`);if(t.includes("@"))throw new m("invalid-argument","userRef must not contain '@'");if(v.test(t))throw new m("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!x.test(e))throw new m("invalid-argument","conversationId must be a UUID");return e}var w=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],k=/* @__PURE__ */Object.freeze(w.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(k.map(e=>e.wireCode));var C=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),S=/* @__PURE__ */Object.freeze(k.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:C[e.wireCode]}))),j=new Map(S.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),_=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(S.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",..._]){let t=j.get(e+r);if(t)return t}}var R=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return R[e]}function fromWire(e){let t=contractErrorFor(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":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(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"}var T=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return T.has(e)}var I=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||I.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var P=500,z=8e3,E=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(P*2**r,z);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var O="This feature isn't available on your account right now.",A="Something in that request was not right. Check the details and try again.",M=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:O,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:A,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:O,runtimeDisposed:A,unknown:"Something went wrong. Please try again."}),F="This session has ended. Please sign in again.",D="linked_account_read_only";function L(e,t,r){return e==="conflict"&&r===D?O:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?F:userFacingError(e)}function userFacingError(e){return M[e]}function B(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var V=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===D,i={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:L(e,t?.wireCode,n?D:null)};t?.httpStatus!==void 0&&(i.httpStatus=t.httpStatus),t?.requestId&&(i.requestId=t.requestId),typeof t?.reasonCode=="string"&&V.test(t.reasonCode)&&(i.reasonCode=t.reasonCode);let l=t?.retryAfterSeconds;if(typeof l=="number"&&Number.isFinite(l)&&l>=0&&(i.retryAfterSeconds=Math.round(l)),r);return t?.wireMessage&&B(i,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&B(i,"raw",t.raw),/* @__PURE__ */Object.freeze(i)}var H=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function U(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return q(e)}var N=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,$=/[\s\u0000-\u001f\u007f\\]/,W={"http:":"80","https:":"443"};function q(e,t){let r=e.trim();let n=$.test(r)?null:N.exec(r);if(n===null)return null;let[,i="",l="",o="",s="",a="",u="",c="",d=""]=n,f=`${i.toLowerCase()}:`,h=Number(a);if(h>65535)return null;let p=a===""||String(h)===W[f]?"":String(h),g=W[f]!==void 0,m=s.toLowerCase()+(p&&`:${p}`),b=u||(g?"/":""),y=l||o?`${l}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:l,password:o,hostname:s.toLowerCase(),port:p,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}var G="application/pdf",K=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Y=e=>K.includes(e);function Q(e,t){return e===G||t!==void 0&&Y(e)&&t.includes(e)}var X=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Z(e){return Q(e,K)?X[e]:X["application/pdf"]}var J="file",ee="multipart upload failed";function te(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(J,e.file)}catch{return Promise.reject(new Error(ee))}return e.fetch!==void 0?ie(e.fetch,e.url,t,e.signal):ne(e.url,t,e.signal)}function re(e){return e>=200&&e<300}function ne(e,t,r){return new Promise((n,i)=>{let l=globalThis.XMLHttpRequest;if(typeof l!="function"||r?.aborted===true){i(new Error(ee));return}let o=null,s=()=>{o!==null&&r?.removeEventListener("abort",o)},a=()=>{s(),i(new Error(ee))};try{let i=new l;i.open("POST",e),i.withCredentials=!1,i.onload=()=>{s(),n(re(i.status))},i.onerror=a,i.ontimeout=a,i.onabort=a,r!==void 0&&(o=()=>{try{i.abort()}finally{a()}},r.addEventListener("abort",o,{once:!0})),i.send(t)}catch{a()}})}function ie(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var le="records upload: the file handle has no uri",oe="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
5
- return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(le));let{signal:i,onProgress:l}=n,o=()=>Promise.reject(new Error(oe));return i?.aborted===true?o():te({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Z(r.mimeType),type:se(r.mimeType)},signal:i,fetch:e.fetch}).then(e=>{if(!e)return o();l?.(1)},o)}})}function se(e){return Q(e,K)?e:"application/pdf"}var ae=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var ue=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<E},maxAttempts(){return E}});var ce=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return fe(`optional peer '${e}' is not installed: ${he(t)}`)}let i=de(n);return i==null?fe(`optional peer '${e}' resolved to no module`):r&&!r(i)?fe(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:i})}function de(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function fe(e){/* @__PURE__ */
6
- return Object.freeze({available:false,module:null,reason:e})}function he(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
4
+ return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var m=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new m(e.error)}var b=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var y=128,v=128,x=/[\u0000-\u001F\u007F]/,w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=g(t);if(r===0||r>v)throw new b("invalid-argument",`petRef must be 1..${v} characters`);if(x.test(t))throw new b("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=g(t);if(r===0||r>y)throw new b("invalid-argument",`userRef must be 1..${y} characters`);if(t.includes("@"))throw new b("invalid-argument","userRef must not contain '@'");if(x.test(t))throw new b("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!w.test(e))throw new b("invalid-argument","conversationId must be a UUID");return e}var k=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],C=/* @__PURE__ */Object.freeze(k.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(C.map(e=>e.wireCode));var S=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),j=/* @__PURE__ */Object.freeze(C.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:S[e.wireCode]}))),_=new Map(j.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),R=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(j.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...R]){let t=_.get(e+r);if(t)return t}}var T=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return T[e]}function fromWire(e){let t=contractErrorFor(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":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(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"}var I=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return I.has(e)}var P=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||P.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var z=500,E=8e3,O=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(z*2**r,E);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var A="This feature isn't available on your account right now.",M="Something in that request was not right. Check the details and try again.",F=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:A,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:M,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:A,runtimeDisposed:M,unknown:"Something went wrong. Please try again."}),D="This session has ended. Please sign in again.",L="linked_account_read_only";function B(e,t,r){return e==="conflict"&&r===L?A:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?D:userFacingError(e)}function userFacingError(e){return F[e]}function V(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var H=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===L,i={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:B(e,t?.wireCode,n?L:null)};t?.httpStatus!==void 0&&(i.httpStatus=t.httpStatus),t?.requestId&&(i.requestId=t.requestId),typeof t?.reasonCode=="string"&&H.test(t.reasonCode)&&(i.reasonCode=t.reasonCode);let l=t?.retryAfterSeconds;if(typeof l=="number"&&Number.isFinite(l)&&l>=0&&(i.retryAfterSeconds=Math.round(l)),r);return t?.wireMessage&&V(i,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&V(i,"raw",t.raw),/* @__PURE__ */Object.freeze(i)}var U=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function N(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return G(e)}var $=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,W=/[\s\u0000-\u001f\u007f\\]/,q={"http:":"80","https:":"443"};function G(e,t){let r=e.trim();let n=W.test(r)?null:$.exec(r);if(n===null)return null;let[,i="",l="",o="",s="",a="",u="",c="",d=""]=n,f=`${i.toLowerCase()}:`,h=Number(a);if(h>65535)return null;let p=a===""||String(h)===q[f]?"":String(h),g=q[f]!==void 0,m=s.toLowerCase()+(p&&`:${p}`),b=u||(g?"/":""),y=l||o?`${l}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:l,password:o,hostname:s.toLowerCase(),port:p,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}var K="application/pdf",Y=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Q=e=>Y.includes(e);function X(e,t){return e===K||t!==void 0&&Q(e)&&t.includes(e)}var Z=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function J(e){return X(e,Y)?Z[e]:Z["application/pdf"]}var ee="file",te="multipart upload failed";function re(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(ee,e.file)}catch{return Promise.reject(new Error(te))}return e.fetch!==void 0?le(e.fetch,e.url,t,e.signal):ie(e.url,t,e.signal)}function ne(e){return e>=200&&e<300}function ie(e,t,r){return new Promise((n,i)=>{let l=globalThis.XMLHttpRequest;if(typeof l!="function"||r?.aborted===true){i(new Error(te));return}let o=null,s=()=>{o!==null&&r?.removeEventListener("abort",o)},a=()=>{s(),i(new Error(te))};try{let i=new l;i.open("POST",e),i.withCredentials=!1,i.onload=()=>{s(),n(ne(i.status))},i.onerror=a,i.ontimeout=a,i.onabort=a,r!==void 0&&(o=()=>{try{i.abort()}finally{a()}},r.addEventListener("abort",o,{once:!0})),i.send(t)}catch{a()}})}function le(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var oe="records upload: the file handle has no uri",se="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
5
+ return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(oe));let{signal:i,onProgress:l}=n,o=()=>Promise.reject(new Error(se));return i?.aborted===true?o():re({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:J(r.mimeType),type:ae(r.mimeType)},signal:i,fetch:e.fetch}).then(e=>{if(!e)return o();l?.(1)},o)}})}function ae(e){return X(e,Y)?e:"application/pdf"}var ue=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var ce=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<O},maxAttempts(){return O}});var de=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return he(`optional peer '${e}' is not installed: ${pe(t)}`)}let i=fe(n);return i==null?he(`optional peer '${e}' resolved to no module`):r&&!r(i)?he(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:i})}function fe(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function he(e){/* @__PURE__ */
6
+ return Object.freeze({available:false,module:null,reason:e})}function pe(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
7
7
  return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}function heartbeatFrame(e,t=null){/* @__PURE__ */
8
8
  return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}function deltaFrame(e,t,r=null){/* @__PURE__ */
9
9
  return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}function doneFrame(e,t=null){/* @__PURE__ */
@@ -11,376 +11,377 @@ return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,
11
11
  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,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}function analysisStartedFrame(e,t,r=null){/* @__PURE__ */
12
12
  return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
13
13
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
14
- return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var pe="/widget/v1/anon-identity",ge="x-everfur-anon-token",me="anonTokenInvalid";function be(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let i=null,l=null,o=null,s=null,a=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>i!==null&&(i.ttlMs===null||a(i.mintedAtMs)<i.ttlMs-2592e5),d=()=>i!==null&&(i.ttlMs===null||a(i.mintedAtMs)<i.ttlMs)?i.token:null,f=()=>l||(l=(async()=>{try{let l=null,s={method:"POST",path:pe,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{l=e("date")}},a=await e.request(s),u=a.ok?a.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(i={token:c,mintedAtMs:n(),ttlMs:be(u?.expires_at,l)},o=null,c)}catch{return o=n(),d()}finally{l=null}})(),l);return{token(e){return e?.forceRefresh?l||(u(s,3e4)?Promise.resolve(i?.token??null):(s=n(),i=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function ye(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function ve(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let i=null,l=false,o=null,s=false,a=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new m("invalid-argument","TokenProvider returned an empty token");return i=n,l=!1,r?.(typeof e=="string"?null:xe(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(s)throw new m("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(i=null),i!==null?i:a()},hasToken(){return!s&&i!==null},clear(){s=true,i=null},reportRejected(){s||l||(l=true,n?.())}}}function xe(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}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].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("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[ge]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...we(e.headers),...authHeaders(t)}}}function we(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===ge||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await ye(t),n=await t.transport.request(withAuthHeaders(e,ke(t,r)));if(n.ok||Se(n.error.raw)!==me||t.anonIdentity===void 0||t.userRef!==null)return n;let i=await t.anonIdentity.token({forceRefresh:true});return i===null||i===r?n:t.transport.request(withAuthHeaders(e,ke(t,i)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(ve(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let i;try{i=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(ve(e,{wireCode:Se(n.error.raw),requestId:n.error.requestId}))}let l=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:i,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!l.ok&&l.error.httpStatus===401?(t.identity.reportRejected?.(),err(Ce(l.error))):l}function ke(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function Ce(e){let t=e.raw,r=Se(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function Se(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var je="DAILY_QUOTA_EXCEEDED",_e=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function Re(e,t){if(!_e.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?je:e}var Te="free_cap_reached";function Ie(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function Pe(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==Te&&n.code!==Te)return null;let i=Ie(n.limit),l=Ie(n.used);if(i===null||l===null)return null;let o=n.resets_at,s=n.emergency_guidance;/* @__PURE__ */
15
- return Object.freeze({limit:i,used:l,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof s=="string"&&s.trim().length>0?{emergencyGuidance:s}:{}})}function ze(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:Pe(t)}function Ee(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let l="",o=0;for(;o<i.length;){let t=i[o];if(t<128){l+=String.fromCharCode(t),o+=1;continue}let r,s=128,a=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(s=160),t===237&&(a=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(s=144),t===244&&(a=143);else{l+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=i.length);){let e=i[o+c],t=c===1?s:128,r=c===1?a:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){l+="�",o+=c;continue}if(c<=r){n?e=i.slice(o):l+="�";break}l+=String.fromCodePoint(u),o+=r+1}return l}}}function Oe(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):Ee()}var Ae=`\n\n`,Me=1048576,Fe=/* @__PURE__ */e.z.record(/* @__PURE__ */e.z.string(),/* @__PURE__ */e.z.unknown()),De=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=Oe(),l="",o=0,s=false;for await(let t of e){for(l+=i.decode(t,{stream:true});;){let e=l.indexOf(Ae,o);if(e===-1)break;let t=l.slice(0,e);l=l.slice(e+Ae.length),o=0;let r=Le(t,n());if(r!==null&&(r.kind==="delta"&&(s=true),yield r,r.terminal))return}if(o=l.length>0?l.length-1:0,l.length>Me){yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(l+=i.decode(),l.trim().length>0){let e=Le(l,n());if(e!==null&&(e.kind==="delta"&&(s=true),yield e,e.terminal))return}yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function Le(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let l=Fe.safeParse(i);return l.success?Be(l.data,r,t):null}function Be(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:Ve(e.code)??"unknown",retryable:e.retryable===true,wireMessage:Ve(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:Pe(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:Ve(e.conversation_id)??"",messageId:Ve(e.message_id),title:Ve(e.title),followUpQuestions:$e(e.follow_up_questions),citations:qe(e.citations),citationStatus:Ve(e.citation_status),urgencyLevel:Ue(e.urgency_level),urgencyReason:Ve(e.urgency_reason),urgencyProvided:Ne(e),resultId:Ve(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(Ve(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=Ve(e.delta)??Ve(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(Ve(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:Ve(e.result_id),analysisType:Ve(e.analysis_type),modelVersion:Ve(e.model_version),confidence:He(e.confidence),detections:qe(e.detections),interpretation:Ve(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function Ve(e){return typeof e=="string"?e:null}function He(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ue(e){return typeof e=="string"&&De.includes(e)?e:null}function Ne(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ue(t)!==null}function $e(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return Array.isArray(e)?e.filter(We):[]}function Ge(e,t,r){return{...e,surface:t,requestId:r||null}}var Ke=64,Ye=/^[A-Za-z0-9._+() -]+$/;function Qe(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ke?null:Ye.test(t)?t:null}var Xe="1.5.0";var Ze="react-native",Je="2026-09-19",et="EVERFUR_API_BASE_URL";function tt(e,t){/* @__PURE__ */
14
+ return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var ge="/widget/v1/anon-identity",me="x-everfur-anon-token",be="anonTokenInvalid";function ye(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let i=null,l=null,o=null,s=null,a=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>i!==null&&(i.ttlMs===null||a(i.mintedAtMs)<i.ttlMs-2592e5),d=()=>i!==null&&(i.ttlMs===null||a(i.mintedAtMs)<i.ttlMs)?i.token:null,f=()=>l||(l=(async()=>{try{let l=null,s={method:"POST",path:ge,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{l=e("date")}},a=await e.request(s),u=a.ok?a.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(i={token:c,mintedAtMs:n(),ttlMs:ye(u?.expires_at,l)},o=null,c)}catch{return o=n(),d()}finally{l=null}})(),l);return{token(e){return e?.forceRefresh?l||(u(s,3e4)?Promise.resolve(i?.token??null):(s=n(),i=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function ve(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function xe(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let i=null,l=false,o=null,s=false,a=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new b("invalid-argument","TokenProvider returned an empty token");return i=n,l=!1,r?.(typeof e=="string"?null:we(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(s)throw new b("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(i=null),i!==null?i:a()},hasToken(){return!s&&i!==null},clear(){s=true,i=null},reportRejected(){s||l||(l=true,n?.())}}}function we(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}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].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("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[me]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...ke(e.headers),...authHeaders(t)}}}function ke(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===me||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await ve(t),n=await t.transport.request(withAuthHeaders(e,Ce(t,r)));if(n.ok||je(n.error.raw)!==be||t.anonIdentity===void 0||t.userRef!==null)return n;let i=await t.anonIdentity.token({forceRefresh:true});return i===null||i===r?n:t.transport.request(withAuthHeaders(e,Ce(t,i)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(xe(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let i;try{i=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(xe(e,{wireCode:je(n.error.raw),requestId:n.error.requestId}))}let l=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:i,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!l.ok&&l.error.httpStatus===401?(t.identity.reportRejected?.(),err(Se(l.error))):l}function Ce(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function Se(e){let t=e.raw,r=je(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function je(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var _e="DAILY_QUOTA_EXCEEDED",Re=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function Te(e,t){if(!Re.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?_e:e}var Ie="free_cap_reached";function Pe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function ze(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==Ie&&n.code!==Ie)return null;let i=Pe(n.limit),l=Pe(n.used);if(i===null||l===null)return null;let o=n.resets_at,s=n.emergency_guidance;/* @__PURE__ */
15
+ return Object.freeze({limit:i,used:l,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof s=="string"&&s.trim().length>0?{emergencyGuidance:s}:{}})}function Ee(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:ze(t)}function Oe(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let l="",o=0;for(;o<i.length;){let t=i[o];if(t<128){l+=String.fromCharCode(t),o+=1;continue}let r,s=128,a=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(s=160),t===237&&(a=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(s=144),t===244&&(a=143);else{l+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=i.length);){let e=i[o+c],t=c===1?s:128,r=c===1?a:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){l+="�",o+=c;continue}if(c<=r){n?e=i.slice(o):l+="�";break}l+=String.fromCodePoint(u),o+=r+1}return l}}}function Ae(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):Oe()}var Me=`\n\n`,Fe=1048576,De=/* @__PURE__ */e.z.record(/* @__PURE__ */e.z.string(),/* @__PURE__ */e.z.unknown()),Le=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=Ae(),l="",o=0,s=false;for await(let t of e){for(l+=i.decode(t,{stream:true});;){let e=l.indexOf(Me,o);if(e===-1)break;let t=l.slice(0,e);l=l.slice(e+Me.length),o=0;let r=Be(t,n());if(r!==null&&(r.kind==="delta"&&(s=true),yield r,r.terminal))return}if(o=l.length>0?l.length-1:0,l.length>Fe){yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(l+=i.decode(),l.trim().length>0){let e=Be(l,n());if(e!==null&&(e.kind==="delta"&&(s=true),yield e,e.terminal))return}yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function Be(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let l=De.safeParse(i);return l.success?Ve(l.data,r,t):null}function Ve(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:He(e.code)??"unknown",retryable:e.retryable===true,wireMessage:He(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:ze(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:He(e.conversation_id)??"",messageId:He(e.message_id),title:He(e.title),followUpQuestions:We(e.follow_up_questions),citations:Ge(e.citations),citationStatus:He(e.citation_status),urgencyLevel:Ne(e.urgency_level),urgencyReason:He(e.urgency_reason),urgencyProvided:$e(e),resultId:He(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(He(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=He(e.delta)??He(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(He(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:He(e.result_id),analysisType:He(e.analysis_type),modelVersion:He(e.model_version),confidence:Ue(e.confidence),detections:Ge(e.detections),interpretation:He(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function He(e){return typeof e=="string"?e:null}function Ue(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ne(e){return typeof e=="string"&&Le.includes(e)?e:null}function $e(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ne(t)!==null}function We(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return Array.isArray(e)?e.filter(qe):[]}function Ke(e,t,r){return{...e,surface:t,requestId:r||null}}var Ye=64,Qe=/^[A-Za-z0-9._+() -]+$/;function Xe(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ye?null:Qe.test(t)?t:null}var Ze="1.5.2";var Je="react-native",et="2026-09-19",tt="EVERFUR_API_BASE_URL";function rt(e,t){/* @__PURE__ */
16
16
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(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}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
17
- return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),i=tryResolveApiBaseUrl(e.apiBaseUrl);if(!i.ok)return i;let l=e.contractVersion?.trim()||Je,o=Qe(e.appVersion);/* @__PURE__ */
18
- return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:i.value,contractVersion:l,sdkVersion:Xe,platform:t?.platform??Ze,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:at(et);return r?ot(r):tt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${et}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function rt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function nt(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function it(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:nt(t)}function lt(e,t){return`${e}://${t}`}function ot(e){let t=e.trim(),r=H.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return tt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),i=rt(r[2]);if(i.length===0)return tt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let l=it(t,i)?`: ${lt(n,i)}`:"";if(n!=="https"){if(!(n==="http"&&st(i)))return n==="http"?tt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${l}`):tt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${l}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
19
- return Object.freeze({ok:true,value:o})}function st(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function at(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function ut(e,t){if(e.status!==429&&e.status!==503)return t;let r=dt(e.headers.get(ct),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&ft(n)?t:{...n??{},retry_after_seconds:r}}var ct="retry-after";function dt(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function ft(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var ht=3e4,pt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=mt(),n=false,i=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let i=e.data??"";for(let e of i.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},l=()=>{s(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let i=kt(e.message);if(i!==null){let e={type:"error",code:Te,retryable:false,limit:i.limit,used:i.used,resets_at:i.resetsAt,emergency_guidance:i.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=xt(n),i=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:i})}\n\n`))}}s(),r.end()};e.addEventListener("message",i),e.addEventListener("done",l),e.addEventListener("error",o);function s(){if(!n){n=true,e.removeEventListener("message",i),e.removeEventListener("done",l),e.removeEventListener("error",o);try{e.close()}catch{}}}return gt(r.source,s)}async function*gt(e,t){try{yield*e}finally{t()}}function mt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*i(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:i(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=Ct(t.config.apiBaseUrl,e.path,e.query),i=St(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),l=Rt(ht),o=Tt(l.signal,e.signal),s;try{s=await r(n,jt({...e,signal:o},i))}catch(e){return err(networkError(e))}finally{l.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>s.headers.get(e))}catch{}if(e.rawText&&s.ok)try{return ok(Number(s.headers.get("content-length"))>e.rawText?null:await s.text())}catch(e){return err(networkError(e))}let a=await It(s);return s.ok?ok(a):err(errorFromResponse(s.status,ut(s,a),requestIdOf(s)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>bt(_t(t,r),e)}}async function*bt(e,t){let r=Ct(t.config.apiBaseUrl,e.path,e.query),n=St(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let i=t.eventSourceFactory(r,yt(e,n));yield*parseSse(eventSourceByteSource(i),()=>eventSourceRequestId(i));return}let i=t.fetchImpl??getGlobalFetch(),l;try{l=await i(r,jt(e,n))}catch(e){yield wt("",true,At(e));return}let o=requestIdOf(l);if(!l.ok){let e=await It(l),t=zt(e)??xt(l.status),r=Ot(e)||isAutoRetryable(fromWire(t));yield wt(t,r,Et(e),o,Pe(e));return}if(l.body){yield*parseSse(fetchByteSource(l.body),o);return}yield*parseSse(fetchByteSource(null),o)}function yt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=zt(t),i=n?fromWire(n):fromHttpStatus(e),l=Et(t);return makeEverfurError(i,{httpStatus:e,...Ot(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Pt(t)?{reasonCode:Pt(t)}:{},...vt(t)!==null?{retryAfterSeconds:vt(t)}:{},...l?{wireMessage:l}:{},...t!=null?{raw:t}:{}})}function vt(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:At(e)})}function requestIdOf(e){let t=e.headers.get(pt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(pt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function xt(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":""}function wt(e,t,r,n=null,i=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:i})}function kt(e){if(typeof e!="string"||e.length===0)return null;try{return Pe(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new m("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function Ct(e,t,r){let n=t.startsWith("/")?t:`/${t}`,i=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(i+=`?${e}`)}return i}function St(e,t,r,n){let i={...buildBaseHeaders(e),accept:r};return n&&(i["content-type"]="application/json"),t&&Object.assign(i,t),i}function jt(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}function _t(e,t){return e.signal?e:{...e,signal:t}}function Rt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function Tt(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function It(e){try{return await e.json()}catch{return null}}function Pt(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function zt(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?Re(r,e):Pe(e)!==null?Te:null}function Et(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function Ot(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function At(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var Mt=3e4,Ft=z*2,Dt="idempotency-key",Lt=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),Bt=/* @__PURE__ */Object.freeze({onEvent(){}}),Vt=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Ht(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??Bt,r=e.timers??Vt,n=e.rng??Math.random,i=e.sleep??((e,t)=>nr(e,r,t)),l=e.maxAttempts??E,o=e.unaryTimeoutMs??Mt,s=e.newIdempotencyKey??Nt(),a=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??l),h=c?.idempotent??Lt.has(u.method),p=c?.idempotencyKey===void 0?null:Ht(c.idempotencyKey),g=h?p??s():null,m=Ut(u,g),b=0;for(;;){let l=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:b,...g?{idempotencyKey:g}:{},...e});a(l({phase:"attempt"}));let s=tr(o,r),c=rr(s.signal,u.signal),h;try{h=await authedSend({...m,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),s.cancel()}if(h.ok)return a(l({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=Wt(p,b,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return a(l({phase:"settled",...v})),err(p);if(a(l({phase:"retry",...v,delayMs:y.delayMs})),await i(y.delayMs,u.signal),u.signal?.aborted===true)return a(l({phase:"settled",...v,reason:"aborted"})),err(p);b+=1}}async function c(t){return withAuthHeaders(t,await er(e.auth))}async function*d(t,r,n){a(
17
+ return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),i=tryResolveApiBaseUrl(e.apiBaseUrl);if(!i.ok)return i;let l=e.contractVersion?.trim()||et,o=Xe(e.appVersion);/* @__PURE__ */
18
+ return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:i.value,contractVersion:l,sdkVersion:Ze,platform:t?.platform??Je,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:ut(tt);return r?st(r):rt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${tt}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function nt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function it(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function lt(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:it(t)}function ot(e,t){return`${e}://${t}`}function st(e){let t=e.trim(),r=U.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return rt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),i=nt(r[2]);if(i.length===0)return rt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let l=lt(t,i)?`: ${ot(n,i)}`:"";if(n!=="https"){if(!(n==="http"&&at(i)))return n==="http"?rt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${l}`):rt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${l}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
19
+ return Object.freeze({ok:true,value:o})}function at(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function ut(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function ct(e,t){if(e.status!==429&&e.status!==503)return t;let r=ft(e.headers.get(dt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&ht(n)?t:{...n??{},retry_after_seconds:r}}var dt="retry-after";function ft(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function ht(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var pt=3e4,gt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=bt(),n=false,i=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let i=e.data??"";for(let e of i.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},l=()=>{s(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let i=Ct(e.message);if(i!==null){let e={type:"error",code:Ie,retryable:false,limit:i.limit,used:i.used,resets_at:i.resetsAt,emergency_guidance:i.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=wt(n),i=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:i})}\n\n`))}}s(),r.end()};e.addEventListener("message",i),e.addEventListener("done",l),e.addEventListener("error",o);function s(){if(!n){n=true,e.removeEventListener("message",i),e.removeEventListener("done",l),e.removeEventListener("error",o);try{e.close()}catch{}}}return mt(r.source,s)}async function*mt(e,t){try{yield*e}finally{t()}}function bt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*i(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:i(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=St(t.config.apiBaseUrl,e.path,e.query),i=jt(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),l=Tt(pt),o=It(l.signal,e.signal),s;try{s=await r(n,_t({...e,signal:o},i))}catch(e){return err(networkError(e))}finally{l.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>s.headers.get(e))}catch{}if(e.rawText&&s.ok)try{return ok(Number(s.headers.get("content-length"))>e.rawText?null:await s.text())}catch(e){return err(networkError(e))}let a=await Pt(s);return s.ok?ok(a):err(errorFromResponse(s.status,ct(s,a),requestIdOf(s)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>yt(Rt(t,r),e)}}async function*yt(e,t){let r=St(t.config.apiBaseUrl,e.path,e.query),n=jt(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let i=t.eventSourceFactory(r,vt(e,n));yield*parseSse(eventSourceByteSource(i),()=>eventSourceRequestId(i));return}let i=t.fetchImpl??getGlobalFetch(),l;try{l=await i(r,_t(e,n))}catch(e){yield kt("",true,Mt(e));return}let o=requestIdOf(l);if(!l.ok){let e=await Pt(l),t=Et(e)??wt(l.status),r=At(e)||isAutoRetryable(fromWire(t));yield kt(t,r,Ot(e),o,ze(e));return}if(l.body){yield*parseSse(fetchByteSource(l.body),o);return}yield*parseSse(fetchByteSource(null),o)}function vt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=Et(t),i=n?fromWire(n):fromHttpStatus(e),l=Ot(t);return makeEverfurError(i,{httpStatus:e,...At(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...zt(t)?{reasonCode:zt(t)}:{},...xt(t)!==null?{retryAfterSeconds:xt(t)}:{},...l?{wireMessage:l}:{},...t!=null?{raw:t}:{}})}function xt(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:Mt(e)})}function requestIdOf(e){let t=e.headers.get(gt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(gt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function wt(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":""}function kt(e,t,r,n=null,i=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:i})}function Ct(e){if(typeof e!="string"||e.length===0)return null;try{return ze(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new b("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function St(e,t,r){let n=t.startsWith("/")?t:`/${t}`,i=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(i+=`?${e}`)}return i}function jt(e,t,r,n){let i={...buildBaseHeaders(e),accept:r};return n&&(i["content-type"]="application/json"),t&&Object.assign(i,t),i}function _t(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}function Rt(e,t){return e.signal?e:{...e,signal:t}}function Tt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function It(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function Pt(e){try{return await e.json()}catch{return null}}function zt(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function Et(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?Te(r,e):ze(e)!==null?Ie:null}function Ot(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function At(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function Mt(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var Ft=3e4,Dt=E*2,Lt="idempotency-key",Bt=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),Vt=/* @__PURE__ */Object.freeze({onEvent(){}}),Ht=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Ut(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??Vt,r=e.timers??Ht,n=e.rng??Math.random,i=e.sleep??((e,t)=>ir(e,r,t)),l=e.maxAttempts??O,o=e.unaryTimeoutMs??Ft,s=e.newIdempotencyKey??$t(),a=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??l),h=c?.idempotent??Bt.has(u.method),p=c?.idempotencyKey===void 0?null:Ut(c.idempotencyKey),g=h?p??s():null,m=Nt(u,g),b=0;for(;;){let l=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:b,...g?{idempotencyKey:g}:{},...e});a(l({phase:"attempt"}));let s=rr(o,r),c=nr(s.signal,u.signal),h;try{h=await authedSend({...m,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),s.cancel()}if(h.ok)return a(l({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=qt(p,b,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return a(l({phase:"settled",...v})),err(p);if(a(l({phase:"retry",...v,delayMs:y.delayMs})),await i(y.delayMs,u.signal),u.signal?.aborted===true)return a(l({phase:"settled",...v,reason:"aborted"})),err(p);b+=1}}async function c(t){return withAuthHeaders(t,await tr(e.auth))}async function*d(t,r,n){a(
20
20
  /* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:r.method,path:r.path,attempt:0}));try{yield*e.auth.transport.stream(r,n)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
21
- return Object.freeze({send:u,authorize:c,stream:d})}function Ut(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==Dt&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function Nt(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var $t=10;function Wt(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=qt(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let i=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let l=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min($t,Math.floor(t)))},o=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let s=Gt(e,r.now);return s!==null?s>Ft?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:i,delayMs:s}:{retry:true,reason:i,delayMs:backoffDelayMs(t,r.rng)}}function qt(e){let t=e.code==="unknown"?fromWire(Zt(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Gt(e,t){let r=Yt(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=Kt(e.raw);return n===null?null:Math.round(n*1e3)}function Kt(e){for(let t of Qt(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Yt(e){for(let t of Qt(e)){let e=t.resets_at,r=Xt(e);if(r!==null)return r}return null}function Qt(e){if(!Jt(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Jt(n)&&t.push(n)}return t}function Xt(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}function Zt(e){for(let t of Qt(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Jt(e){return typeof e=="object"&&e!==null}async function er(e){if(e.mode==="anonymous"){let t=await ye(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function tr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function rr(e,t){let r=()=>{};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 i=()=>n.abort();return e.addEventListener("abort",i,{once:true}),t.addEventListener("abort",i,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",i),t.removeEventListener("abort",i)}}}function nr(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let i=t.setTimeout(()=>{r?.removeEventListener("abort",l),n()},e),l=()=>{t.clearTimeout(i),n()};r?.addEventListener("abort",l,{once:true})})}var ir=/* @__PURE__ */Object.freeze(["better","same","worse"]),lr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function or(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function sr(){return err(makeEverfurError("internalError",{retryable:false}))}function ar(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):h(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var ur=e=>typeof e=="string"?e:null,cr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function dr(e){if(typeof e!="object"||e===null)return null;let t=e,r=ur(t.case_id),n=ur(t.status);if(r===null||n===null)return null;let i=ur(t.last_response);/* @__PURE__ */
22
- return Object.freeze({caseId:r,status:n,bodyLocation:ur(t.body_location),lastResponse:i!==null&&ir.includes(i)?i:null,checkInDueAt:ur(t.check_in_due_at),openedAt:ur(t.opened_at),resolvedAt:ur(t.resolved_at),resolutionText:ur(t.resolution_text),checkinAskCount:cr(t.checkin_ask_count),checkinAnswerCount:cr(t.checkin_answer_count)})}function fr(e){return{async list(t,r){let n=ar(t);if(typeof n!="string")return err(n);let i=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!i.ok)return err(i.error);let l=typeof i.value=="object"&&i.value!==null?i.value.cases:null;if(!Array.isArray(l))return sr();let o=l.map(dr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):sr()},async checkin(t,r,n,i){let l=ar(t);if(typeof l!="string")return err(l);if(typeof r!="string"||!lr.test(r))return or("case_id must be a UUID");if(!ir.includes(n))return or("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${l}/${r}/checkin`,body:{response:n},...i?.signal?{signal:i.signal}:{}});if(!o.ok)return err(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value:{},a=dr(s.case);return a===null?sr():ok(/* @__PURE__ */Object.freeze({case:a,ctaDeepLink:ur(s.cta_deep_link)}))}}}function hr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function pr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:hr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var gr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var mr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function br(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let i={handle:void 0},l=()=>{r.clearTimeout(i.handle),t.removeEventListener("abort",l),n()};i.handle=r.setTimeout(l,e),t.addEventListener("abort",l,{once:true})})}function yr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var vr=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?yr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===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()}};function xr(e,t,r){/* @__PURE__ */
23
- return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function wr(e,t,r){/* @__PURE__ */
24
- return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function kr(e){/* @__PURE__ */
25
- return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Cr(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),/* @__PURE__ */Object.freeze(r)}function Sr(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,/* @__PURE__ */Object.freeze(r)}function jr(e){/* @__PURE__ */
26
- return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function _r(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function Rr(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function Tr(e){return errorFrame({code:Ir(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function Ir(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"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function Pr(e){let t=Array.isArray(e)?e:Er(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!Er(e))continue;let t=Or(e.category)??Or(e.title)??"",n=Ar(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
27
- return Object.freeze(r)}function zr(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Or(e){return typeof e=="string"?e:null}function Ar(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Er(r)){let e=Or(r.text)??Or(r.prompt)??Or(r.title);e!==null&&t.push(e)}return t}function Mr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Fr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Dr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Lr(e,t,r,n){let i=e[Symbol.asyncIterator](),l=Hr(t.overallMs,n),o=Hr(t.idleMs,n),s=Ur(r);try{for(;;){if(r.aborted)return;let e=i.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),l.promise.then(()=>({tag:"overall"})),s.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield Vr();return}if(n.tag==="idle"||n.tag==="overall"){yield Br();return}let a=n.value;if(a.done||(o.reset(t.idleMs),yield a.value,a.value.terminal))return}}finally{o.cancel(),l.cancel(),Promise.resolve(i.return?.(void 0)).catch(()=>{})}}function Br(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Vr(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Hr(e,t){let r=()=>{},n=new Promise(e=>{r=e}),i=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(i),i=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(i)}}}function Ur(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var Nr="checkin",$r=/^\d{4}-\d{2}-\d{2}$/,Wr="watching";function qr(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function Gr(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,i=t.question,l=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof i!="string"||i.trim().length===0)return null;let o=typeof l=="string"&&l.length>0?l:null,s=Yr(o),a=s===null?null:/* @__PURE__ */Object.freeze({caseId:s.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:i,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...a===null?{}:{checkin:a}});/* @__PURE__ */
28
- return Object.freeze({conversationId:r,message:c,checkin:a,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Wr}function Kr(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}function Yr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==Nr||n===void 0||i===void 0||!lr.test(n)||!$r.test(i)?null:{caseId:n,dueDay:i}}function Qr(e){return Yr(e)?.caseId??null}function Xr(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||h(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function Zr(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)}function Jr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function en(e){return e==null||typeof e=="string"&&e.length>0&&!h(e)}function tn(){return err(makeEverfurError("internalError",{retryable:false}))}function rn(e){let t=Jr(e);if(!t||!Array.isArray(t.conversations)||!en(t.next_cursor))return tn();let r=[];for(let e of t.conversations){let t=Jr(e);if(!t||typeof t.conversation_id!="string"||!Zr(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return tn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return tn();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function nn(e){let t=Jr(e);if(!t||!Array.isArray(t.messages)||!en(t.next_cursor))return tn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=Jr(e);if(!t||typeof t.message_id!="string"||!Zr(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return tn();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(ln(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,l=t.role==="assistant"?Qr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:sn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:an(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...l!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function ln(e,t,r,n){let i=Jr(e.sender),l=on(i?.display_name)??on(e.sender_display_name),o=on(i?.specialty);/* @__PURE__ */
29
- return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:l,specialty:o})})}function on(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!h(t)?t:null}function sn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function an(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
30
- return Object.freeze(e.flatMap(e=>{let r=Jr(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function un(e,t,r){let n=new Set(e.map(e=>e.id)),i=e.filter(e=>r.has(e.id)),l=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=i.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){i.splice(r,1);continue}l.push(e)}return l}var cn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),dn=4e3;var fn=4e3;function hn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:_r("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:_r("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function pn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:_r("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>fn?{reason:"too_long",error:_r("validationFailed",false,`message is ${r} characters; the server accepts at most ${fn}`)}:null}function gn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*mn(e){yield e}async function*bn(){}var yn=6e4,vn=18e4,xn=24,wn=512,kn=false;function createChatController(e){return new _n(e)}function Cn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Sn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function jn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var _n=class extends vr{constructor(e){super(jr({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=fr(this.funnel),this.telemetry=e.telemetry??ae,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??ue,this.timers=e.timers??Dr,this.rng=e.rng??Math.random,this.newId=e.newId??Mr(),this.makeIdempotencyKey=e.makeIdempotencyKey??Fr(),this.budget={idleMs:e.budget?.idleMs??yn,overallMs:e.budget?.overallMs??vn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=_r(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):mn(Tr(e))}let i=pn(e)??hn(n.imageS3Keys);if(i!==null)return this.telemetry.track("chat.send.rejected",{reason:i.reason}),this.patch({status:"error",isStreaming:false,error:i.error}),r?(r.onError(i.error),()=>{}):mn(Tr(i.error));if(r)return this.driveWithHandlers(e,n,r);let l=this.beginTurn(e,n);return this.runTurn(l,n.signal)}askEverfur(e,t){if(this.disposed)return mn(Tr(_r("accessDenied",false)));let r=pn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),mn(Tr(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):bn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,xr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?kr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(zr(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Xr(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(_r("accessDenied",false));let i=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(_r("accessDenied",false));if(!i.ok)return i;let l=rn(i.value);if(l.ok){for(let e of l.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=l.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,l.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return l}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Gr(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Sn(n.error)?n.error:null;if(n.error.category==="notFound"&&jn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let i=qr(n.value.messages);i===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:i,checkin:i.checkin??null,occasionRef:i.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Cn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(_r("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let i=n.value.conversations[0];if(i===void 0)return ok(null);let l=await this.resumeConversation(i.id);return l.ok?ok(i.id):err(l.error)}async markRead(e){if(this.disposed)return err(_r("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(_r("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(_r("accessDenied",false));if(typeof e!="string"||e.trim().length===0||h(e))return err(_r("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!cn.includes(t))return err(_r("validationFailed",false,`feedback_type must be one of ${cn.join(", ")}`));let i=typeof r=="string"?r.trim():"";if([...i].length>dn)return err(_r("validationFailed",false,`notes is over ${dn} characters`));let l={feedback_type:t};i.length>0&&(l.notes=i);let o=this.epoch,s=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:l},n?.signal);if(!this.alive(o)||this.disposed)return err(_r("accessDenied",false));if(!s.ok)return err(s.error);let a=s.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof a=="string"?a:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(_r("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(_r("validationFailed",false,"a check-in needs the pet the case belongs to"));let i=this.epoch,l=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(i)||this.disposed)return err(_r("accessDenied",false));if(!l.ok)return l;let o=l.value.case.openedAt,s=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...o!==null?{openedAt:o}:{}}),a=t=>t.checkin?.caseId===e;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,checkin:s}):e)}),this.answeredCases.set(e,s);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:s}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),l}async getMessages(e,t){if(!Zr(e))return err(_r("validationFailed",false));let r=Xr(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(_r("accessDenied",false));let i=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(_r("accessDenied",false)):i.ok?nn(i.value):i}async resumeConversation(e){if(this.disposed)return err(_r("accessDenied",false));if(!Zr(e))return err(_r("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(_r("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Wr).map(e=>e.caseId)),i=new Map(r.value.map(e=>[e.caseId,e])),l=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;l=true;let r=i.get(t.caseId),o=t.openedAt??r?.openedAt??null,s=n.has(t.caseId),a=r!==void 0&&(!s||Kr({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
31
- return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:s?Wr:r?.status??"resolved",answer:t.answer??a,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});l&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(_r("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),i=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(_r("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=i===null?null:await i;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let l=await this.resumeConversation(r.id);return l.ok?ok(void 0):err(l.error)}let l=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(_r("accessDenied",false));if(!l.ok)return err(l.error);let o=un(this.snapshot.messages,l.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Sn(n.error))return err(n.error);let s=i===null?null:await i;return s!==null&&r===this.historyGeneration&&!this.disposed?err(s):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(_r("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(_r("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let i=new Set(this.snapshot.messages.map(e=>e.id)),l=n.value.messages.filter(e=>!i.has(e.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Tr(t.error))}async primeConversation(e){if(this.disposed)return err(_r("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(_r("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(_r("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let i=await n.settled;return!this.alive(t)||this.disposed?err(_r("accessDenied",false)):(!i.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),i)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let i=n.value?.conversation_id??n.value?.id;return typeof i!="string"||i.length===0?err(_r("internalError",true)):ok(i)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(_r("accessDenied",false));let r=e?.petRef??null;if(r!==null&&h(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",i=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(_r("accessDenied",false)):i.ok?ok(Pr(i.value)):err(i.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,i=yr(n.signal,t.signal),l=this.beginTurn(e,t),o=this.runTurn(l,i),s=false,a=()=>{s||(s=true,n.abort(),this.handlerTeardowns.delete(a))};return this.handlerTeardowns.add(a),(async()=>{for await(let e of o){if(s)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!s&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(a)})(),a}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,xr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,i=false,l=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,s=t?this.unadoptedCreate:null;if(s!==null&&(e.petRef===null||e.petRef===s.petRef)){let e=await s.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Tr(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let a=e.conversationIdOverride??this.snapshot.conversationId;if(a===null){let t=_r("internalError",!0);yield*this.emitTerminal(e,t,Tr(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=yr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,a))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Tr(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[ge]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Lr(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=_r("streamIncomplete",!0);yield*this.emitTerminal(e,t,Tr(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===me||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Rr(d),d);return}if(canRecreateOnNotFound(h)&&!i){i=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(kn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,Rr(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?kr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,wr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=wn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},xn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Cr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Sr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?kr(e):e),Sr(wr(r,"",this.stamp()),e)]}let i=zr([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=i.length>0?/* @__PURE__ */Object.freeze(i):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,i=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!l.ok||!this.alive(n)||this.disposed||i!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=gn(l.value?.urgency),s=typeof l.value?.reason=="string"?l.value.reason:null,a=e=>e.responseId===t;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:s,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?kr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?_r("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,i=e.resumeConversationId??null,l=[],o=false,s=false,a=false,u=null,c=null,d=i?r.resumeConversation(i).then(e=>e.ok?ok(i):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&l.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,Tn(e)?(s=true,u=e):(In(e)&&(o=true),a=true)}let m=[];p.ok?m=p.value:b(p.error);function b(e){Tn(e)?(s=true,u===null&&(u=e)):In(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
32
- return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:m,error:y,warning:y===null&&g===null&&a?Rn:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...l]),sawForbidden:o,sawUnauthorized:s,sawConversationInitFailure:a})})}var Rn="Chat is ready. Your first message will start the conversation.";function Tn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function In(e){return e.httpStatus===403||e.code==="accessDenied"}var Pn=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function zn(e){return e!==Pn}var En=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var On=10*1024*1024,An=5,Mn=120,Fn="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&En.includes(e.trim().toLowerCase())}function sanitizeFilename(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<=Mn)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Mn);let n=t.slice(r);return n.length>=Mn?t.slice(0,Mn):`${t.slice(0,r).slice(0,Mn-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var Dn=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),Ln=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function Bn(e,t,r,n){/* @__PURE__ */
33
- return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(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}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return Ln(Bn("unsupported_type",false,t));let n=attachmentSize(e);return n===null?Ln(Bn("unknown",false,t)):n>On?Ln(Bn("too_large",false,t,{sizeBytes:n})):Dn(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function Vn(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,i=r(t.upload_id),l=r(t.upload_url),o=r(t.s3_key);if(i===null||l===null||o===null)return null;let s={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[e,t]of Object.entries(a))typeof t=="string"&&(s[e]=t);/* @__PURE__ */
34
- return Object.freeze({upload_id:i,upload_url:l,upload_fields:/* @__PURE__ */Object.freeze(s),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??On,s3_key:o,purpose:r(t.purpose)})}function Hn(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Bn("quota_exceeded",false,t,{cause:e});case"rateLimited":return Bn("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Bn("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Bn("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Bn("network",true,t,{cause:e});default:return r===429?Bn("rate_limited",true,t,{cause:e}):r===503?Bn("network",true,t,{cause:e}):r===void 0?Bn("network",true,t,{cause:e}):Bn("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Fn,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Ln(Hn(n.error,t.filename));let i=Vn(n.value);return i===null?Ln(Bn("server",false,t.filename)):Dn(i)}async function uploadAttachmentBytes(e,t,r,n){let i=()=>n?.signal?.aborted===true;if(i())return Ln(Bn("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Dn(void 0)}catch{return i()?Ln(Bn("cancelled",true,r.filename)):Ln(Bn("server",true,r.filename))}}var Un=2,Nn=3,$n=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Wn=0;function qn(){return Wn+=1,`attachment-${Wn}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??Un),r=Math.max(1,e.maxAttempts??Nn),n=e.backoffMs??$n,i=Math.max(1,e.maxPerMessage??An),l=e.timers??mr,o=e.newId??qn,s=zn(e.transport),a=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=a.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},m=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},b=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=a.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),b()}))}},y=async t=>{let{attachment:i}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;m(t,{status:"uploading",error:null,progress:0});let s=await initiateAttachmentUpload(e.funnel,i,{signal:o});if(p||o.aborted)return;let a;if(!s.ok)a=Ln(s.error);else{let r=await uploadAttachmentBytes(e.transport,s.value,i,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&m(t,{progress:Gn(e)})}});if(p||o.aborted)return;a=r.ok?Dn(s.value.s3_key):Ln(r.error)}if(a.ok){m(t,{status:"uploaded",s3Key:a.value,error:null,progress:1});return}let u=a.error,c=u.retryable&&t.attempts<r;if(m(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await br(d,o,l)}},v=e=>{c.push(e.state.id),b()},x={available:s,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=i)return Ln(Bn("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(r,n),u.push(r),g(),v(n),Dn(n.state)},retry(e){let t=a.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,m(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=a.get(e);if(t===void 0)return;t.controller.abort(),a.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])x.remove(e)},dispose(){p=true;for(let e of a.values())e.controller.abort();a.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return x}function Gn(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Kn=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Kn,t)?Kn[t]:null}var Yn=50,Qn=128,Xn=120,Zn=120,Jn=2e3,ei=120,ti=80,ri=/* @__PURE__ */new Set(["male","female","unknown"]),ni=/* @__PURE__ */new Set(["day","month","year"]),ii=/* @__PURE__ */new Set(["low","medium","high","athletic"]),li=/* @__PURE__ */new Set(["indoor","outdoor","both"]),oi=/* @__PURE__ */new Set(["mild","moderate","severe"]),si=/^(\d{4})-(\d{2})-(\d{2})$/,ai=[["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"]],ui=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...ai,...ui].map(([e])=>e));function ci(e){let t=si.exec(e);if(t===null)return false;let[r,n,i]=[Number(t[1]),Number(t[2]),Number(t[3])],l=new Date(Date.UTC(r,n-1,i));return l.getUTCFullYear()===r&&l.getUTCMonth()===n-1&&l.getUTCDate()===i}var di=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,fi=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,hi=(e,t)=>typeof t=="string"&&ci(t)?null:`${e} must be a real date written YYYY-MM-DD`,pi=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(h(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let i=t.trimmed?n.trim():n;if(t.required&&i.length===0)return`${r} is required and must not be blank`;let l=p(i);return l<=e?null:`${r} is ${l} characters; the server accepts at most ${e}`},gi={sex:di(ri),spayedNeutered:fi,birthDate:hi,birthDatePrecision:di(ni),activityLevel:di(ii),indoorOutdoor:di(li),foodBrand:pi(ei),foodType:pi(ei),microchipId:pi(ti)},mi=["ref","ref",false,pi(Qn,{required:true,trimmed:true})],bi=["notes","notes",false,pi(Jn,{trimmed:true})],yi=[mi,["name","name",true,pi(Xn,{required:true,trimmed:true})],["dose","dose",false,pi(Zn,{trimmed:true})],["frequency","frequency",false,pi(Zn,{trimmed:true})],["startDate","start_date",false,hi],["endDate","end_date",false,hi],bi],vi={allergies:[mi,["allergen","allergen",true,pi(Xn,{required:true,trimmed:true})],["severity","severity",false,di(oi)],bi],medications:yi,supplements:yi,conditions:[mi,["conditionName","condition_name",true,pi(Xn,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,hi],bi]};function xi(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let i=r,l={};for(let[t,r,o,s]of vi[e]){let e=i[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(l[r]=null);continue}let a=s(`${n}.${t}`,e);if(a!==null)return{error:a};l[r]=e}let o=l.start_date,s=l.end_date;return typeof o=="string"&&typeof s=="string"&&s<o?{error:`${n}.endDate must not be before startDate`}:{item:l}}function wi(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Yn)return{error:`${e} has ${t.length} items; the server accepts at most ${Yn}`};let r=[],n=/* @__PURE__ */new Set;for(let i=0;i<t.length;i+=1){let l=xi(e,i,t[i]);if("error"in l)return l;let o=l.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(l.item)}return{items:r}}function ki(e,t){let r=e,n={};for(let[e,t]of ai){let i=r[e];if(i!==void 0){if(i!==null){let t=gi[e](e,i);if(t!==null)return{error:t}}n[t]=i}}let i=r.birthDate!==void 0,l=r.birthDatePrecision!==void 0;if(i!==l||i&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of ui){let i=r[e];if(i===void 0)continue;let l=wi(e,i);if("error"in l)return l;n[t]=l.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(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}}var Ci=e=>typeof e=="string"?e:null,Si=(e,t)=>typeof t=="string"&&e.has(t)?t:null,ji=e=>typeof e=="boolean"?e:null;function _i(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function Ri(e){let t=Ci(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Ci(e.ref),name:t,dose:Ci(e.dose),frequency:Ci(e.frequency),startDate:Ci(e.start_date),endDate:Ci(e.end_date),notes:Ci(e.notes)})}function Ti(e){let t=e.profile_version;/* @__PURE__ */
35
- return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Si(ri,e.sex),spayedNeutered:ji(e.spayed_neutered),birthDate:Ci(e.birth_date),birthDatePrecision:Si(ni,e.birth_date_precision),activityLevel:Si(ii,e.activity_level),indoorOutdoor:Si(li,e.indoor_outdoor),foodBrand:Ci(e.food_brand),foodType:Ci(e.food_type),microchipId:Ci(e.microchip_id),allergies:_i(e.allergies,e=>{let t=Ci(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Ci(e.ref),allergen:t,severity:Si(oi,e.severity),notes:Ci(e.notes)})}),medications:_i(e.medications,Ri),supplements:_i(e.supplements,Ri),conditions:_i(e.conditions,e=>{let t=Ci(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Ci(e.ref),conditionName:t,diagnosedDate:Ci(e.diagnosed_date),notes:Ci(e.notes)})})})}var Ii=100,Pi=50,zi=100,Ei=50,Oi=500,Ai=128,Mi=6e4;function Fi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Di(e,t,r){if(typeof t!="string")return Fi(`${e} must be a string`);let n=p(t);return n<=r?null:Fi(`${e} is ${n} characters; the server accepts at most ${r}`)}function Li(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Fi(`${e} must be a finite number between 0 and ${r}`)}function Bi(e,t){if(typeof e!="string")return Fi("pet_ref must be a string");if(e.trim().length===0)return Fi("pet_ref must not be blank");if(h(e))return Fi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Fi("profile must be an object");let r=[Di("pet_ref",e,Ai)];return t?.name!==void 0&&r.push(Di("name",t.name,Ii)),t?.species!==void 0&&r.push(Di("species",t.species,Pi)),t?.breed!==void 0&&r.push(Di("breed",t.breed,zi)),t?.ageYears!==void 0&&r.push(Li("age_years",t.ageYears,Ei)),t?.weightKg!==void 0&&r.push(Li("weight_kg",t.weightKg,Oi)),r.find(e=>e!==null)??null}function Vi(e,t){let r=ki(e,t);return"error"in r?{error:Fi(r.error)}:r}function Hi(e){if(typeof e!="object"||e===null)return{error:Fi("patch must be an object")};let t=e,r=[["name","name",e=>Di("name",e,Ii)],["species","species",e=>Di("species",e,Pi)],["breed","breed",e=>Di("breed",e,zi)],["ageYears","age_years",e=>Li("age_years",e,Ei)],["weightKg","weight_kg",e=>Li("weight_kg",e,Oi)]],n={};for(let[e,i,l]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=l(r);if(e!==null)return{error:e}}n[i]=r}}let i=Vi(t,t.species);return"error"in i?i:(Object.assign(n,i.body),Object.keys(n).length===0?{error:Fi("patch must change at least one field")}:{body:n})}function Ui(e){if(e==null)return{body:{}};let t=Vi(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}}}var Ni=e=>typeof e=="string"?e:null,$i=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Wi(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
36
- return Object.freeze({petRef:Ni(r.pet_ref)??t,name:Ni(r.name),species:Ni(r.species),breed:Ni(r.breed),ageYears:$i(r.age_years),weightKg:$i(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ni(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:Ni(t.pet_id),petRef:r,name:Ni(t.name),species:Ni(t.species),breed:Ni(t.breed),ageYears:$i(t.age_years),weightKg:$i(t.weight_kg),updatedAt:Ni(t.updated_at)})}function qi(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...Ti(e)})}function Gi(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
37
- return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Ki(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:Mi}))}function Ki(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>Bi(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(Gi(n.value)):err(n.error)},async registerPet(t,r,n){let i=Bi(t,r);if(i!==null)return err(i);let l=Ui(r);if("error"in l)return err(l.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:l.body},s=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return s.ok?ok(Wi(s.value,t)):err(s.error)},async updatePet(t,i,l){let o=n(t);if(typeof o!="string")return err(o);let s=Hi(i);if("error"in s)return err(s.error);let a=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:s.body},l?.signal));return a.ok?ok(Wi(a.value,t)):err(a.error)},async getPetProfile(t,i){let l=n(t);if(typeof l!="string")return err(l);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},i?.signal));if(!o.ok)return err(o.error);let s=qi(o.value);return s===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(s)},async deletePet(t,i){let l=n(t);if(typeof l!="string")return err(l);let o=await e.send("pets.deletePet",r({method:"DELETE",path:l},i?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Yi=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return Yi[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],i=/* @__PURE__ */new Set;for(let e of Object.keys(Yi))for(let t of Yi[e])i.has(t)||(i.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),i=/* @__PURE__ */new Map;for(let e of t)i.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!i.has(e)))return Zi({name:e,enabled:false,isPending:true,limits:{}});let l=Qi(n,i);return n.filter(e=>i.get(e)?.granted!==true).length===0?Zi({name:e,enabled:true,isPending:false,limits:l}):Zi({name:e,enabled:false,isPending:false,limits:l,disabled:Xi(n,i)})}function Qi(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function Xi(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
21
+ return Object.freeze({send:u,authorize:c,stream:d})}function Nt(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==Lt&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function $t(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Wt=10;function qt(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Gt(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let i=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let l=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Wt,Math.floor(t)))},o=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let s=Kt(e,r.now);return s!==null?s>Dt?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:i,delayMs:s}:{retry:true,reason:i,delayMs:backoffDelayMs(t,r.rng)}}function Gt(e){let t=e.code==="unknown"?fromWire(Jt(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Kt(e,t){let r=Qt(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=Yt(e.raw);return n===null?null:Math.round(n*1e3)}function Yt(e){for(let t of Xt(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Qt(e){for(let t of Xt(e)){let e=t.resets_at,r=Zt(e);if(r!==null)return r}return null}function Xt(e){if(!er(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];er(n)&&t.push(n)}return t}function Zt(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}function Jt(e){for(let t of Xt(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function er(e){return typeof e=="object"&&e!==null}async function tr(e){if(e.mode==="anonymous"){let t=await ve(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function rr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function nr(e,t){let r=()=>{};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 i=()=>n.abort();return e.addEventListener("abort",i,{once:true}),t.addEventListener("abort",i,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",i),t.removeEventListener("abort",i)}}}function ir(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let i=t.setTimeout(()=>{r?.removeEventListener("abort",l),n()},e),l=()=>{t.clearTimeout(i),n()};r?.addEventListener("abort",l,{once:true})})}var lr=/* @__PURE__ */Object.freeze(["better","same","worse"]),or=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sr(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function ar(){return err(makeEverfurError("internalError",{retryable:false}))}function ur(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):p(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var cr=e=>typeof e=="string"?e:null,dr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function fr(e){if(typeof e!="object"||e===null)return null;let t=e,r=cr(t.case_id),n=cr(t.status);if(r===null||n===null)return null;let i=cr(t.last_response);/* @__PURE__ */
22
+ return Object.freeze({caseId:r,status:n,bodyLocation:cr(t.body_location),lastResponse:i!==null&&lr.includes(i)?i:null,checkInDueAt:cr(t.check_in_due_at),openedAt:cr(t.opened_at),resolvedAt:cr(t.resolved_at),resolutionText:cr(t.resolution_text),checkinAskCount:dr(t.checkin_ask_count),checkinAnswerCount:dr(t.checkin_answer_count)})}function hr(e){return{async list(t,r){let n=ur(t);if(typeof n!="string")return err(n);let i=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!i.ok)return err(i.error);let l=typeof i.value=="object"&&i.value!==null?i.value.cases:null;if(!Array.isArray(l))return ar();let o=l.map(fr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):ar()},async checkin(t,r,n,i){let l=ur(t);if(typeof l!="string")return err(l);if(typeof r!="string"||!or.test(r))return sr("case_id must be a UUID");if(!lr.includes(n))return sr("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${l}/${r}/checkin`,body:{response:n},...i?.signal?{signal:i.signal}:{}});if(!o.ok)return err(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value:{},a=fr(s.case);return a===null?ar():ok(/* @__PURE__ */Object.freeze({case:a,ctaDeepLink:cr(s.cta_deep_link)}))}}}function pr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function gr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:pr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var mr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var br=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function yr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let i={handle:void 0},l=()=>{r.clearTimeout(i.handle),t.removeEventListener("abort",l),n()};i.handle=r.setTimeout(l,e),t.addEventListener("abort",l,{once:true})})}function vr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var xr=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?vr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===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()}};function wr(e,t,r){/* @__PURE__ */
23
+ return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function kr(e,t,r){/* @__PURE__ */
24
+ return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function Cr(e){/* @__PURE__ */
25
+ return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Sr(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),/* @__PURE__ */Object.freeze(r)}function jr(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,/* @__PURE__ */Object.freeze(r)}function _r(e){/* @__PURE__ */
26
+ return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function Rr(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function Tr(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function Ir(e){return errorFrame({code:Pr(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function Pr(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"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function zr(e){let t=Array.isArray(e)?e:Or(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!Or(e))continue;let t=Ar(e.category)??Ar(e.title)??"",n=Mr(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
27
+ return Object.freeze(r)}function Er(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ar(e){return typeof e=="string"?e:null}function Mr(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Or(r)){let e=Ar(r.text)??Ar(r.prompt)??Ar(r.title);e!==null&&t.push(e)}return t}function Fr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Dr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Lr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function Br(e){let t=e,r=Lr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let i=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof i=="function"){let t=i.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var Vr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Hr(e,t,r,n){let i=Br(e);if(i===null){yield Nr();return}let l=$r(t.overallMs,n),o=$r(t.idleMs,n),s=Wr(r);try{for(;;){if(r.aborted)return;let e=i.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),l.promise.then(()=>({tag:"overall"})),s.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield Nr();return}if(n.tag==="idle"||n.tag==="overall"){yield Ur();return}let a=n.value;if(a.done||(o.reset(t.idleMs),yield a.value,a.value.terminal))return}}finally{o.cancel(),l.cancel(),Promise.resolve(i.return?.(void 0)).catch(()=>{})}}function Ur(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Nr(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function $r(e,t){let r=()=>{},n=new Promise(e=>{r=e}),i=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(i),i=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(i)}}}function Wr(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var qr="checkin",Gr=/^\d{4}-\d{2}-\d{2}$/,Kr="watching";function Yr(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function Qr(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,i=t.question,l=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof i!="string"||i.trim().length===0)return null;let o=typeof l=="string"&&l.length>0?l:null,s=Zr(o),a=s===null?null:/* @__PURE__ */Object.freeze({caseId:s.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:i,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...a===null?{}:{checkin:a}});/* @__PURE__ */
28
+ return Object.freeze({conversationId:r,message:c,checkin:a,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Kr}function Xr(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}function Zr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==qr||n===void 0||i===void 0||!or.test(n)||!Gr.test(i)?null:{caseId:n,dueDay:i}}function Jr(e){return Zr(e)?.caseId??null}function en(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||p(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function tn(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)}function rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function nn(e){return e==null||typeof e=="string"&&e.length>0&&!p(e)}function ln(){return err(makeEverfurError("internalError",{retryable:false}))}function on(e){let t=rn(e);if(!t||!Array.isArray(t.conversations)||!nn(t.next_cursor))return ln();let r=[];for(let e of t.conversations){let t=rn(e);if(!t||typeof t.conversation_id!="string"||!tn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return ln();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return ln();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function sn(e){let t=rn(e);if(!t||!Array.isArray(t.messages)||!nn(t.next_cursor))return ln();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=rn(e);if(!t||typeof t.message_id!="string"||!tn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return ln();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(an(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,l=t.role==="assistant"?Jr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:cn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:dn(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...l!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function an(e,t,r,n){let i=rn(e.sender),l=un(i?.display_name)??un(e.sender_display_name),o=un(i?.specialty);/* @__PURE__ */
29
+ return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:l,specialty:o})})}function un(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!p(t)?t:null}function cn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function dn(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
30
+ return Object.freeze(e.flatMap(e=>{let r=rn(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function fn(e,t,r){let n=new Set(e.map(e=>e.id)),i=e.filter(e=>r.has(e.id)),l=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=i.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){i.splice(r,1);continue}l.push(e)}return l}var hn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),pn=4e3;var gn=4e3;function mn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:Rr("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:Rr("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function bn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:Rr("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>gn?{reason:"too_long",error:Rr("validationFailed",false,`message is ${r} characters; the server accepts at most ${gn}`)}:null}function yn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*vn(e){yield e}async function*xn(){}var wn=6e4,kn=18e4,Cn=24,Sn=512,jn=false;function createChatController(e){return new In(e)}function _n(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Rn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Tn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var In=class extends xr{constructor(e){super(_r({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=hr(this.funnel),this.telemetry=e.telemetry??ue,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??ce,this.timers=e.timers??Vr,this.rng=e.rng??Math.random,this.newId=e.newId??Fr(),this.makeIdempotencyKey=e.makeIdempotencyKey??Dr(),this.budget={idleMs:e.budget?.idleMs??wn,overallMs:e.budget?.overallMs??kn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=Rr(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):vn(Ir(e))}let i=bn(e)??mn(n.imageS3Keys);if(i!==null)return this.telemetry.track("chat.send.rejected",{reason:i.reason}),this.patch({status:"error",isStreaming:false,error:i.error}),r?(r.onError(i.error),()=>{}):vn(Ir(i.error));if(r)return this.driveWithHandlers(e,n,r);let l=this.beginTurn(e,n);return this.runTurn(l,n.signal)}askEverfur(e,t){if(this.disposed)return vn(Ir(Rr("accessDenied",false)));let r=bn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),vn(Ir(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):xn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,wr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Cr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(Er(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=en(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let i=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(Rr("accessDenied",false));if(!i.ok)return i;let l=on(i.value);if(l.ok){for(let e of l.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=l.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,l.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return l}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Qr(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Rn(n.error)?n.error:null;if(n.error.category==="notFound"&&Tn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let i=Yr(n.value.messages);i===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:i,checkin:i.checkin??null,occasionRef:i.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}_n(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let i=n.value.conversations[0];if(i===void 0)return ok(null);let l=await this.resumeConversation(i.id);return l.ok?ok(i.id):err(l.error)}async markRead(e){if(this.disposed)return err(Rr("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(Rr("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(Rr("accessDenied",false));if(typeof e!="string"||e.trim().length===0||p(e))return err(Rr("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!hn.includes(t))return err(Rr("validationFailed",false,`feedback_type must be one of ${hn.join(", ")}`));let i=typeof r=="string"?r.trim():"";if([...i].length>pn)return err(Rr("validationFailed",false,`notes is over ${pn} characters`));let l={feedback_type:t};i.length>0&&(l.notes=i);let o=this.epoch,s=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:l},n?.signal);if(!this.alive(o)||this.disposed)return err(Rr("accessDenied",false));if(!s.ok)return err(s.error);let a=s.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof a=="string"?a:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(Rr("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(Rr("validationFailed",false,"a check-in needs the pet the case belongs to"));let i=this.epoch,l=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(i)||this.disposed)return err(Rr("accessDenied",false));if(!l.ok)return l;let o=l.value.case.openedAt,s=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...o!==null?{openedAt:o}:{}}),a=t=>t.checkin?.caseId===e;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,checkin:s}):e)}),this.answeredCases.set(e,s);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:s}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),l}async getMessages(e,t){if(!tn(e))return err(Rr("validationFailed",false));let r=en(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let i=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(Rr("accessDenied",false)):i.ok?sn(i.value):i}async resumeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));if(!tn(e))return err(Rr("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Kr).map(e=>e.caseId)),i=new Map(r.value.map(e=>[e.caseId,e])),l=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;l=true;let r=i.get(t.caseId),o=t.openedAt??r?.openedAt??null,s=n.has(t.caseId),a=r!==void 0&&(!s||Xr({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
31
+ return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:s?Kr:r?.status??"resolved",answer:t.answer??a,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});l&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),i=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=i===null?null:await i;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let l=await this.resumeConversation(r.id);return l.ok?ok(void 0):err(l.error)}let l=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!l.ok)return err(l.error);let o=fn(this.snapshot.messages,l.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Rn(n.error))return err(n.error);let s=i===null?null:await i;return s!==null&&r===this.historyGeneration&&!this.disposed?err(s):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(Rr("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let i=new Set(this.snapshot.messages.map(e=>e.id)),l=n.value.messages.filter(e=>!i.has(e.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Ir(t.error))}async primeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(Rr("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let i=await n.settled;return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):(!i.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),i)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let i=n.value?.conversation_id??n.value?.id;return typeof i!="string"||i.length===0?err(Rr("internalError",true)):ok(i)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null;if(r!==null&&p(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",i=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):i.ok?ok(zr(i.value)):err(i.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,i=vr(n.signal,t.signal),l=this.beginTurn(e,t),o=this.runTurn(l,i),s=false,a=()=>{s||(s=true,n.abort(),this.handlerTeardowns.delete(a))};return this.handlerTeardowns.add(a),(async()=>{for await(let e of o){if(s)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!s&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(a)})(),a}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,wr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,i=false,l=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,s=t?this.unadoptedCreate:null;if(s!==null&&(e.petRef===null||e.petRef===s.petRef)){let e=await s.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Ir(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let a=e.conversationIdOverride??this.snapshot.conversationId;if(a===null){let t=Rr("internalError",!0);yield*this.emitTerminal(e,t,Ir(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=vr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,a))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Ir(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[me]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Hr(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=Rr("streamIncomplete",!0);yield*this.emitTerminal(e,t,Ir(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===be||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Tr(d),d);return}if(canRecreateOnNotFound(h)&&!i){i=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(jn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,Tr(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,kr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Sn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Cn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Sr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?jr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e),jr(kr(r,"",this.stamp()),e)]}let i=Er([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=i.length>0?/* @__PURE__ */Object.freeze(i):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,i=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!l.ok||!this.alive(n)||this.disposed||i!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=yn(l.value?.urgency),s=typeof l.value?.reason=="string"?l.value.reason:null,a=e=>e.responseId===t;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:s,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Cr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?Rr("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,i=e.resumeConversationId??null,l=[],o=false,s=false,a=false,u=null,c=null,d=i?r.resumeConversation(i).then(e=>e.ok?ok(i):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&l.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,zn(e)?(s=true,u=e):(En(e)&&(o=true),a=true)}let m=[];p.ok?m=p.value:b(p.error);function b(e){zn(e)?(s=true,u===null&&(u=e)):En(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
32
+ return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:m,error:y,warning:y===null&&g===null&&a?Pn:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...l]),sawForbidden:o,sawUnauthorized:s,sawConversationInitFailure:a})})}var Pn="Chat is ready. Your first message will start the conversation.";function zn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function En(e){return e.httpStatus===403||e.code==="accessDenied"}var On=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function An(e){return e!==On}var Mn=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Fn=10*1024*1024,Dn=5,Ln=120,Bn="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&Mn.includes(e.trim().toLowerCase())}function sanitizeFilename(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<=Ln)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ln);let n=t.slice(r);return n.length>=Ln?t.slice(0,Ln):`${t.slice(0,r).slice(0,Ln-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var Vn=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),Hn=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function Un(e,t,r,n){/* @__PURE__ */
33
+ return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(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}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return Hn(Un("unsupported_type",false,t));let n=attachmentSize(e);return n===null?Hn(Un("unknown",false,t)):n>Fn?Hn(Un("too_large",false,t,{sizeBytes:n})):Vn(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function Nn(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,i=r(t.upload_id),l=r(t.upload_url),o=r(t.s3_key);if(i===null||l===null||o===null)return null;let s={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[e,t]of Object.entries(a))typeof t=="string"&&(s[e]=t);/* @__PURE__ */
34
+ return Object.freeze({upload_id:i,upload_url:l,upload_fields:/* @__PURE__ */Object.freeze(s),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Fn,s3_key:o,purpose:r(t.purpose)})}function $n(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Un("quota_exceeded",false,t,{cause:e});case"rateLimited":return Un("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Un("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Un("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Un("network",true,t,{cause:e});default:return r===429?Un("rate_limited",true,t,{cause:e}):r===503?Un("network",true,t,{cause:e}):r===void 0?Un("network",true,t,{cause:e}):Un("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Bn,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Hn($n(n.error,t.filename));let i=Nn(n.value);return i===null?Hn(Un("server",false,t.filename)):Vn(i)}async function uploadAttachmentBytes(e,t,r,n){let i=()=>n?.signal?.aborted===true;if(i())return Hn(Un("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Vn(void 0)}catch{return i()?Hn(Un("cancelled",true,r.filename)):Hn(Un("server",true,r.filename))}}var Wn=2,qn=3,Gn=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Kn=0;function Yn(){return Kn+=1,`attachment-${Kn}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??Wn),r=Math.max(1,e.maxAttempts??qn),n=e.backoffMs??Gn,i=Math.max(1,e.maxPerMessage??Dn),l=e.timers??br,o=e.newId??Yn,s=An(e.transport),a=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=a.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},m=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},b=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=a.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),b()}))}},y=async t=>{let{attachment:i}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;m(t,{status:"uploading",error:null,progress:0});let s=await initiateAttachmentUpload(e.funnel,i,{signal:o});if(p||o.aborted)return;let a;if(!s.ok)a=Hn(s.error);else{let r=await uploadAttachmentBytes(e.transport,s.value,i,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&m(t,{progress:Qn(e)})}});if(p||o.aborted)return;a=r.ok?Vn(s.value.s3_key):Hn(r.error)}if(a.ok){m(t,{status:"uploaded",s3Key:a.value,error:null,progress:1});return}let u=a.error,c=u.retryable&&t.attempts<r;if(m(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await yr(d,o,l)}},v=e=>{c.push(e.state.id),b()},x={available:s,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=i)return Hn(Un("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(r,n),u.push(r),g(),v(n),Vn(n.state)},retry(e){let t=a.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,m(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=a.get(e);if(t===void 0)return;t.controller.abort(),a.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])x.remove(e)},dispose(){p=true;for(let e of a.values())e.controller.abort();a.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return x}function Qn(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Xn=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Xn,t)?Xn[t]:null}var Zn=50,Jn=128,ei=120,ti=120,ri=2e3,ni=120,ii=80,li=/* @__PURE__ */new Set(["male","female","unknown"]),oi=/* @__PURE__ */new Set(["day","month","year"]),si=/* @__PURE__ */new Set(["low","medium","high","athletic"]),ai=/* @__PURE__ */new Set(["indoor","outdoor","both"]),ui=/* @__PURE__ */new Set(["mild","moderate","severe"]),ci=/^(\d{4})-(\d{2})-(\d{2})$/,di=[["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"]],fi=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...di,...fi].map(([e])=>e));function hi(e){let t=ci.exec(e);if(t===null)return false;let[r,n,i]=[Number(t[1]),Number(t[2]),Number(t[3])],l=new Date(Date.UTC(r,n-1,i));return l.getUTCFullYear()===r&&l.getUTCMonth()===n-1&&l.getUTCDate()===i}var pi=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,gi=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,mi=(e,t)=>typeof t=="string"&&hi(t)?null:`${e} must be a real date written YYYY-MM-DD`,bi=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(p(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let i=t.trimmed?n.trim():n;if(t.required&&i.length===0)return`${r} is required and must not be blank`;let l=g(i);return l<=e?null:`${r} is ${l} characters; the server accepts at most ${e}`},yi={sex:pi(li),spayedNeutered:gi,birthDate:mi,birthDatePrecision:pi(oi),activityLevel:pi(si),indoorOutdoor:pi(ai),foodBrand:bi(ni),foodType:bi(ni),microchipId:bi(ii)},vi=["ref","ref",false,bi(Jn,{required:true,trimmed:true})],xi=["notes","notes",false,bi(ri,{trimmed:true})],wi=[vi,["name","name",true,bi(ei,{required:true,trimmed:true})],["dose","dose",false,bi(ti,{trimmed:true})],["frequency","frequency",false,bi(ti,{trimmed:true})],["startDate","start_date",false,mi],["endDate","end_date",false,mi],xi],ki={allergies:[vi,["allergen","allergen",true,bi(ei,{required:true,trimmed:true})],["severity","severity",false,pi(ui)],xi],medications:wi,supplements:wi,conditions:[vi,["conditionName","condition_name",true,bi(ei,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,mi],xi]};function Ci(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let i=r,l={};for(let[t,r,o,s]of ki[e]){let e=i[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(l[r]=null);continue}let a=s(`${n}.${t}`,e);if(a!==null)return{error:a};l[r]=e}let o=l.start_date,s=l.end_date;return typeof o=="string"&&typeof s=="string"&&s<o?{error:`${n}.endDate must not be before startDate`}:{item:l}}function Si(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Zn)return{error:`${e} has ${t.length} items; the server accepts at most ${Zn}`};let r=[],n=/* @__PURE__ */new Set;for(let i=0;i<t.length;i+=1){let l=Ci(e,i,t[i]);if("error"in l)return l;let o=l.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(l.item)}return{items:r}}function ji(e,t){let r=e,n={};for(let[e,t]of di){let i=r[e];if(i!==void 0){if(i!==null){let t=yi[e](e,i);if(t!==null)return{error:t}}n[t]=i}}let i=r.birthDate!==void 0,l=r.birthDatePrecision!==void 0;if(i!==l||i&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of fi){let i=r[e];if(i===void 0)continue;let l=Si(e,i);if("error"in l)return l;n[t]=l.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(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}}var _i=e=>typeof e=="string"?e:null,Ri=(e,t)=>typeof t=="string"&&e.has(t)?t:null,Ti=e=>typeof e=="boolean"?e:null;function Ii(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function Pi(e){let t=_i(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:_i(e.ref),name:t,dose:_i(e.dose),frequency:_i(e.frequency),startDate:_i(e.start_date),endDate:_i(e.end_date),notes:_i(e.notes)})}function zi(e){let t=e.profile_version;/* @__PURE__ */
35
+ return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Ri(li,e.sex),spayedNeutered:Ti(e.spayed_neutered),birthDate:_i(e.birth_date),birthDatePrecision:Ri(oi,e.birth_date_precision),activityLevel:Ri(si,e.activity_level),indoorOutdoor:Ri(ai,e.indoor_outdoor),foodBrand:_i(e.food_brand),foodType:_i(e.food_type),microchipId:_i(e.microchip_id),allergies:Ii(e.allergies,e=>{let t=_i(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:_i(e.ref),allergen:t,severity:Ri(ui,e.severity),notes:_i(e.notes)})}),medications:Ii(e.medications,Pi),supplements:Ii(e.supplements,Pi),conditions:Ii(e.conditions,e=>{let t=_i(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:_i(e.ref),conditionName:t,diagnosedDate:_i(e.diagnosed_date),notes:_i(e.notes)})})})}var Ei=100,Oi=50,Ai=100,Mi=50,Fi=500,Di=128,Li=6e4;function Bi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Vi(e,t,r){if(typeof t!="string")return Bi(`${e} must be a string`);let n=g(t);return n<=r?null:Bi(`${e} is ${n} characters; the server accepts at most ${r}`)}function Hi(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Bi(`${e} must be a finite number between 0 and ${r}`)}function Ui(e,t){if(typeof e!="string")return Bi("pet_ref must be a string");if(e.trim().length===0)return Bi("pet_ref must not be blank");if(p(e))return Bi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Bi("profile must be an object");let r=[Vi("pet_ref",e,Di)];return t?.name!==void 0&&r.push(Vi("name",t.name,Ei)),t?.species!==void 0&&r.push(Vi("species",t.species,Oi)),t?.breed!==void 0&&r.push(Vi("breed",t.breed,Ai)),t?.ageYears!==void 0&&r.push(Hi("age_years",t.ageYears,Mi)),t?.weightKg!==void 0&&r.push(Hi("weight_kg",t.weightKg,Fi)),r.find(e=>e!==null)??null}function Ni(e,t){let r=ji(e,t);return"error"in r?{error:Bi(r.error)}:r}function $i(e){if(typeof e!="object"||e===null)return{error:Bi("patch must be an object")};let t=e,r=[["name","name",e=>Vi("name",e,Ei)],["species","species",e=>Vi("species",e,Oi)],["breed","breed",e=>Vi("breed",e,Ai)],["ageYears","age_years",e=>Hi("age_years",e,Mi)],["weightKg","weight_kg",e=>Hi("weight_kg",e,Fi)]],n={};for(let[e,i,l]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=l(r);if(e!==null)return{error:e}}n[i]=r}}let i=Ni(t,t.species);return"error"in i?i:(Object.assign(n,i.body),Object.keys(n).length===0?{error:Bi("patch must change at least one field")}:{body:n})}function Wi(e){if(e==null)return{body:{}};let t=Ni(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}}}var qi=e=>typeof e=="string"?e:null,Gi=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ki(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
36
+ return Object.freeze({petRef:qi(r.pet_ref)??t,name:qi(r.name),species:qi(r.species),breed:qi(r.breed),ageYears:Gi(r.age_years),weightKg:Gi(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=qi(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:qi(t.pet_id),petRef:r,name:qi(t.name),species:qi(t.species),breed:qi(t.breed),ageYears:Gi(t.age_years),weightKg:Gi(t.weight_kg),updatedAt:qi(t.updated_at)})}function Yi(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...zi(e)})}function Qi(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
37
+ return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Xi(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:Li}))}function Xi(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>Ui(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(Qi(n.value)):err(n.error)},async registerPet(t,r,n){let i=Ui(t,r);if(i!==null)return err(i);let l=Wi(r);if("error"in l)return err(l.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:l.body},s=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return s.ok?ok(Ki(s.value,t)):err(s.error)},async updatePet(t,i,l){let o=n(t);if(typeof o!="string")return err(o);let s=$i(i);if("error"in s)return err(s.error);let a=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:s.body},l?.signal));return a.ok?ok(Ki(a.value,t)):err(a.error)},async getPetProfile(t,i){let l=n(t);if(typeof l!="string")return err(l);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},i?.signal));if(!o.ok)return err(o.error);let s=Yi(o.value);return s===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(s)},async deletePet(t,i){let l=n(t);if(typeof l!="string")return err(l);let o=await e.send("pets.deletePet",r({method:"DELETE",path:l},i?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Zi=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return Zi[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],i=/* @__PURE__ */new Set;for(let e of Object.keys(Zi))for(let t of Zi[e])i.has(t)||(i.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),i=/* @__PURE__ */new Map;for(let e of t)i.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!i.has(e)))return tl({name:e,enabled:false,isPending:true,limits:{}});let l=Ji(n,i);return n.filter(e=>i.get(e)?.granted!==true).length===0?tl({name:e,enabled:true,isPending:false,limits:l}):tl({name:e,enabled:false,isPending:false,limits:l,disabled:el(n,i)})}function Ji(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function el(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
38
38
  return Object.freeze({reason:e.reason,level:e.level,recoverable:e.recoverable})}/* @__PURE__ */
39
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function Zi(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function Ji(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,el)}catch(e){el(e)}}function el(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var tl=/* @__PURE__ */new WeakMap,rl=/* @__PURE__ */new Map;function nl(e,t){tl.set(e,t)}function il(e,t,r,n){let i=tl.get(e);if(i===void 0)return null;let l;if(t.mode==="personalized"&&typeof t.userRef=="string")l=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")l=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${i}|${l}|${r}|${ol(n)}`}function ll(e,t){if(e===null)return t();let r=rl.get(e);if(r!==void 0)return r;let n=t().finally(()=>{rl.get(e)===n&&rl.delete(e)});return rl.set(e,n),n}function ol(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ol).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${ol(t)}`).join(",")}}`}var sl=/* @__PURE__ */new WeakMap;function al(e,t){let r=sl.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,sl.set(e,r)),r.add(t),()=>{r?.delete(t)}}function ul(e){let t=sl.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var cl=/* @__PURE__ */new Map;function dl(e,t){return()=>{let r=cl.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let i=n.finally(()=>{cl.get(e)===i&&cl.delete(e)});return cl.set(e,i),i}}function parseColor(e){let t=fl(e);return t===null?null:vl(t)}function fl(e){if(typeof e=="number")return gl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return hl(t.slice(1));if(t.toLowerCase().startsWith("0x"))return hl(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return pl(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=hl(t);if(e!==null)return e}return/^\d+$/.test(t)?gl(Number.parseInt(t,10)):null}function hl(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:bl(t[0]),g:bl(t[1]),b:bl(t[2]),a:1};if(t.length===6)return{r:ml(t,0),g:ml(t,2),b:ml(t,4),a:1};if(t.length===8){let e=ml(t,0);return{r:ml(t,2),g:ml(t,4),b:ml(t,6),a:e/255}}return null}function pl(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(e=>e.trim());if(n.length<3)return null;let i=yl(Number(n[0])),l=yl(Number(n[1])),o=yl(Number(n[2]));if(i===null||l===null||o===null)return null;let s=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;s=Math.min(1,Math.max(0,e))}return{r:i,g:l,b:o,a:s}}function gl(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}}function ml(e,t){return Number.parseInt(e.slice(t,t+2),16)}function bl(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function yl(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function vl(e){if(e.a>=1)return xl(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function xl(e,t,r){return`#${wl(e)}${wl(t)}${wl(r)}`.toUpperCase()}function wl(e){return e.toString(16).padStart(2,"0")}var kl="#111111",Cl="#FFFFFF",Sl="#000000";function readableOn(e){let t=fl(e);if(t===null)return Cl;let r=Rl(t),n=Rl({r:17,g:17,b:17}),i=Rl({r:255,g:255,b:255});return Il(r,i)>=Il(r,n)?Cl:kl}function jl(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(Cl,e)>=contrastRatio(Sl,e)?Cl:Sl}function _l(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(Cl)>=t(Sl)?Cl:Sl}function Rl(e){let t=Tl(e.r/255),r=Tl(e.g/255),n=Tl(e.b/255);return.2126*t+.7152*r+.0722*n}function Tl(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function Il(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=fl(e),n=fl(t);if(r===null||n===null)return 1;let i=n.a>=1?n:{...n},l=r.a>=1?r:Pl(r,i);return Il(Rl(l),Rl(i))}function Pl(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function zl(e,t){let r=fl(e),n=fl(t);if(r===null||n===null)return null;let i=r.a>=1?r:Pl(r,{...n});return xl(i.r,i.g,i.b)}function El(e,t){let r=fl(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var Ol=.05;function Al(e,t,r,n){let i=t[0];if(i===void 0)return r;let l=e=>t.every(t=>contrastRatio(e,t)>=n);if(fl(e)===null)return r;if(l(e))return e;let o=zl(e,i),s=o===null?null:fl(o),a=fl(r);if(s===null||a===null)return r;for(let e=1;e<1/Ol;e+=1){let t=e*Ol,r=(e,r)=>Math.round(e+(r-e)*t),n=xl(r(s.r,a.r),r(s.g,a.g),r(s.b,a.b));if(l(n))return n}return r}function Ml(e,t,r){let n=e/255,i=t/255,l=r/255,o=Math.max(n,i,l),s=Math.min(n,i,l),a=(o+s)/2;if(o===s)return{h:0,s:0,l:a};let u=o-s,c=u/(1-Math.abs(2*a-1)),d;return o===n?(d=(i-l)/u*60,d<0&&(d=d+360)):o===i?d=((l-n)/u+2)*60:d=((n-i)/u+4)*60,{h:d,s:c,l:a}}function Fl(e){let{h:t,s:r,l:n}=e,i=(1-Math.abs(2*n-1))*r,l=t/60,o=i*(1-Math.abs(l%2-1)),s=n-i/2,a=Math.floor(l)%6,u=[[i,o,0],[o,i,0],[0,i,o],[0,o,i],[o,0,i],[i,0,o]],[c,d,f]=u[a];return{r:Dl(c+s),g:Dl(d+s),b:Dl(f+s)}}function Dl(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var Ll=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),Bl=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Vl=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return Vl[e]??Bl}var Hl=4.5,Ul=/* @__PURE__ */Object.freeze({});function Nl(e){return Ll.includes(e)}function $l(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,i]of Object.entries(e)){if(!Nl(n)||i===null||typeof i!="object")continue;let e=Gl(i);if(e===null)continue;let l=Wl(n,e);l!==null&&(t[n]=l,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function Wl(e,t){let r=Vl[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function ql(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Gl(e){let t={},r=parseColor(ql(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(ql(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let i=$l(ql(e,"border_radius","borderRadius"));i!==null&&(t.borderRadius=i);let l=parseColor(ql(e,"text_color","textColor"));return l!==null&&(t.textColor=l),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Ul:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Kl(e){let t=fl(e);return t!==null&&t.a>=1}var Yl=3,Ql=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Xl(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Zl(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>zl(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=Yl))return null;let i=[...t,...n,...r];return Al(n[0],i,_l(i),Yl)}function Jl(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>zl(e,t)??t)}function eo(e,t){let r=_l(e);return e.every(e=>contrastRatio(r,e)>=t)}function to(e,t){let r=t[0];return r===void 0?null:zl(e,r)}function ro(e){let t=jl(e[0],Hl);return e.every(e=>contrastRatio(t,e)>=Hl)?t:_l(e)}function no(e,t,r,n,i){return Ql.has(e)?false:i?true:r!==void 0&&Xl(t,r)?false:!(n!==void 0&&r!==void 0&&Kl(r))}function guardSlotContrast(e,t,r){let n=false,i={};for(let l of Ll){let o=e[l];if(o===void 0)continue;let s=o.backgroundColor,a=t?.[l]??[],u=Jl(s,a),c={...o},d=false;if(s!==void 0&&u.length>1&&!eo(u,Hl)){let e=to(s,a);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[l],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Kl(h)&&Zl(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(s!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<Hl))&&(c.textColor=ro(u),d=true);else if(e!==void 0){let t=Al(e,u,_l(u),Hl);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&no(l,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=Al(o.borderColor,e,_l(e),Yl);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Zl(h,f,u);e!==null&&(c.borderColor=e,d=true)}i[l]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(i):e}var io=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),lo=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var oo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){oo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var so=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ao=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),uo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},co={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},fo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},ho={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},po={regular:"400",medium:"500",bold:"700"},go={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},mo=0,bo="System",yo="monospace",vo=["content","heading","control","compact","badge"];function xo(e){let t={};for(let r of vo)t[r]=e;return t}var wo=[];function ko(){return{family:bo,mono:yo,fontUrl:null,families:{regular:bo,medium:bo,bold:bo,mono:yo,monoMedium:yo,monoBold:yo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:fo,tierSizes:xo(fo),lineHeight:ho,weight:po,letterSpacing:go,scale:1,maxScale:mo,scaleCaps:so,headingFamily:null,headingWeight:null,fontSources:wo,roles:lo,typeScale:1}}var Co={},So=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var jo={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(So.standard),emphasized:cssCubicBezier(So.emphasized),exit:cssCubicBezier(So.exit)},reducedMotion:false},_o={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},Ro=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:_o,space:uo,radius:co,type:ko(),motion:jo,slots:Co}),To={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},Io=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:To,space:uo,radius:co,type:ko(),motion:jo,slots:Co});function Po(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function zo(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function Eo(e){return zo(e).every(t=>contrastRatio(e.brand,t)>=Yl)}function Oo(e){return[e.chatGround,e.surface,e.surfaceCream]}function Ao(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...Mo(e,t)]}function Mo(e,t){return[zl(t,e.surface)??e.surface,zl(t,e.surfaceCream)??e.surfaceCream]}function Fo(e){return[e.composerFill,e.chatGround]}var Do=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Lo(e,t){let r=new Set(Po(t));return Po(e).every(e=>r.has(e))}function Bo(e){let t=e.color,r=(e.brightness==="dark"?Io:Ro).color,n=(e.brightness==="dark"?Ro:Io).color,i=Po(t),l=_l(i)!==_l(Po(r)),o=Lo(t,r),s=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,a=(e,t,r,n,i,a)=>{let u=t===r&&(e!=="errorRed"||s);return u&&o&&Do.has(e)?t:Al(u&&l?n:t,i,_l(i),a)},u=(e,i,l)=>a(`text.${e}`,t.text[e],r.text[e],n.text[e],i,l),c=(e,t,i,l)=>a(e,t,r[e],n[e],i,l),d=e=>l&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=jl(f,Hl),p=c("danger",t.danger,[...i,...Mo(t,t.badgeBgCritical)],Hl),g={...t,onPrimary:h,onAccent:jl(t.accent,Hl),onDanger:contrastRatio(h,p)>=Hl?h:jl(p,Hl),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,i,Hl),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,Oo(t),Hl),text:{...t.text,primary:u("primary",i,Hl),secondary:u("secondary",i,Hl),muted:u("muted",i,Hl),metaCool:u("metaCool",i,Hl),timestamp:u("timestamp",i,Hl),placeholder:u("placeholder",zo(t),Yl)},danger:p,errorRed:c("errorRed",t.errorRed,Ao(t,t.badgeBgCritical),Hl),warningStrong:c("warningStrong",t.warningStrong,Ao(t,t.badgeBgCaution),Hl),composerBorder:c("composerBorder",t.composerBorder,Fo(t),Yl),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,zo(t),Yl)},m={...g,...Go(g,r,o)};return{...m,...Vo(t,m,r)}}function Vo(e,t,r){let n={},i=(e,t,r)=>Al(e,t,_l(t),r);if((!$o(e.success,r.success)||!$o(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=i(e.success,Ao(t,e.badgeBgPositive),Hl)),(!$o(e.cautionAccent,r.cautionAccent)||!$o(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=i(e.cautionAccent,Ao(t,e.badgeBgCaution),Hl)),Ho(e,r)){n.info=i(e.info,Ao(t,e.badgeBgInfo),Hl);let r=[t.surface,t.chatGround,...Mo(t,e.badgeBgInfo)];n.infoEdge=i(e.infoEdge,r,Yl)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function Ho(e,t){return!$o(e.info,t.info)||!$o(e.badgeBgInfo,t.badgeBgInfo)}var Uo=.24,No=.3;function $o(e,t){return parseColor(e)===parseColor(t)}function Wo(e,t){return $o(e.accent,t.accent)?$o(e.brand,t.brand)?null:e.brand:e.accent}function qo(e,t,r){let n=El(e,r);return(n===null?null:zl(n,t))??t}function Go(e,t,r){let n=Wo(e,t),i=zo(e),l=_l(i),o=_l([e.surface])===Cl,s=n===null&&r,a;s?a=t.highlight:n===null?a=o?qo(Ro.color.highlight,e.surface,No):Ro.color.highlight:a=qo(n,e.surface,o?No:Uo);let u=s?t.onHighlight:Al(e.text.primary,[a],_l([a]),Hl),c=n===null?t.mark:Al(n,i,l,Yl),d=Eo(e)?e.brand:l,f=(e,t,n)=>r&&$o(e,t)?n:Al(e,i,d,Yl),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=Yl)?e.primary:Al(e.primary,h,_l(h),Yl);return{highlight:a,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Ko=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Yo(e,t){let r=(e.brightness==="dark"?Io:Ro).color,n=e.color,i=t.color,l=[],o=(e,t,r,n)=>{l.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},s=(e,t)=>!Ko(e,t);s(n.text.primary,r.text.primary)&&!Ko(i.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,i.text.primary),s(n.brand,r.brand)&&(Ko(i.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,i.brandInk),Ko(i.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,i.primaryEdge),!Ko(i.controlEdge,n.brandBorder)&&!Eo({...i,brand:n.brand})&&o("primary_color","control outline",n.brand,i.controlEdge)),s(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Ko(i.linkInk,n.accent)&&o("accent_color","link text",n.accent,i.linkInk),s(n.danger,r.danger)&&!Ko(i.danger,n.danger)&&o("danger_color","error text",n.danger,i.danger),s(n.success,r.success)&&!Ko(i.success,n.success)&&o("success_color","positive status",n.success,i.success),s(n.warningStrong,r.warningStrong)&&!Ko(i.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,i.warningStrong),s(n.cautionAccent,r.cautionAccent)&&!Ko(i.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,i.cautionAccent),(s(n.info,r.info)||s(n.badgeBgInfo,r.badgeBgInfo))&&(Ko(i.info,n.info)||o("info_color","information text",n.info,i.info),Ko(i.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,i.infoEdge));for(let r of Ll){let n=e.slots[r],i=t.slots[r];n===void 0||i===void 0||n===i||(i.backgroundColor!==void 0&&!Ko(i.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,i.backgroundColor),n.textColor!==void 0&&i.textColor!==void 0&&!Ko(i.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,i.textColor),i.borderColor!==void 0&&!Ko(i.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,i.borderColor))}/* @__PURE__ */
40
- return Object.freeze(l)}var Qo=/* @__PURE__ */new Set;function Xo(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(Qo.has(t))return;Qo.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Zo="#23272C",Jo=4.5,es=.6,ts=.9,rs=.02,ns="#FFFFFF",is="#111111";function ls(e){return contrastRatio(e,Zo)>=Jo&&Math.max(contrastRatio(e,ns),contrastRatio(e,is))>=Jo}function deriveDarkVariant(e){let t=fl(e);if(t===null)return null;let{h:r,s:n,l:i}=Ml(t.r,t.g,t.b),l=Math.min(Math.max(i,es),ts);for(let e=0;;e+=1){let t=l+e*rs;if(t>ts)break;let i=Fl({h:r,s:n,l:t}),o=xl(i.r,i.g,i.b);if(ls(o))return o}let o=Fl({h:r,s:n,l:ts});return xl(o.r,o.g,o.b)}var os=7,ss=.05,as="#000000",us="#FFFFFF";function cs(e,t,r,n){let i=zl(e,t);if(i===null)return r;if(contrastRatio(i,t)>=n)return i;let l=fl(i),o=fl(r);if(l===null||o===null)return r;for(let e=1;e<1/ss;e+=1){let r=e*ss,i=(e,t)=>Math.round(e+(t-e)*r),s=xl(i(l.r,o.r),i(l.g,o.g),i(l.b,o.b));if(contrastRatio(s,t)>=n)return s}return r}function ds(e,t){let r=Po(e),n=r[0],i=fs(n);for(let e of r){let r=fs(e);(t?r>i:r<i)&&(n=e,i=r)}return n}function fs(e){let t=fl(e);return t===null?0:Rl(t)}function hs(e,t){return zl(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=_l(Po(t))===us,n=r?us:as,i=ds(t,r),l=e=>cs(e,i,n,os),o={...t,brandSoft:hs(t.brandSoft,t.surface),brandSofter:hs(t.brandSofter,t.surface),brandBorder:l(t.brandBorder),borderHairlineGreen:l(t.borderHairlineGreen),brandBorderStrong:l(t.brandBorderStrong),controlEdge:l(t.controlEdge),structureEdge:l(t.structureEdge),brandInk:l(t.brandInk),linkInk:l(t.linkInk),borderRingCream:l(t.borderRingCream),composerBorder:l(t.composerBorder),text:{primary:l(t.text.primary),secondary:l(t.text.secondary),muted:l(t.text.muted),placeholder:l(t.text.placeholder),onBrand:t.text.onBrand,metaCool:l(t.text.metaCool),timestamp:l(t.text.timestamp)},badgeBgPositive:hs(t.badgeBgPositive,t.surface),badgeBgCaution:hs(t.badgeBgCaution,t.surface),badgeBgCritical:hs(t.badgeBgCritical,t.surface),badgeBgNeutral:hs(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:hs(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:hs(t.checkupCardConcernBg,t.surface),info:l(t.info),infoEdge:l(t.infoEdge),badgeBgInfo:hs(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var ps=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),gs=ps.cream,ms=ps.subtle,bs=ps.ring,ys=10;function vs(e,t,r){let n=fl(e),i=fl(t);if(n===null||i===null)return null;let l=(e,t)=>Math.round(e+(t-e)*r);return xl(l(n.r,i.r),l(n.g,i.g),l(n.b,i.b))}function xs(e){if(e===null)return{};let t=_l([e]),r=vs(e,t,gs),n=vs(e,t,ms),i=vs(e,t,bs);return r===null||n===null||i===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:i}}function ws(e){if(e===null)return{};let t=fl(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function ks(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let i={};for(let[e,t]of Object.entries(r.type.size))i[e]=Math.max(ys,Math.round(t*n*10)/10);return i}function Cs(e,t,r){if(e===null)return t;let n=e/r.space.xs,i=e=>Math.round(e*n),l=r.space;return{xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),xxl:i(l.xxl)}}function Ss(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),i=t.radius;return{tile:n(i.tile),xs:n(i.xs),sm:n(i.sm),md:n(i.md),lg:n(i.lg),xl:n(i.xl),pill:i.pill}}var js=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function _s(e,t){let r=fl(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function Rs(e,t){if(e===null)return{};let r=_s(e,t?js.success.dark:js.success.light),n=_s(e,t?js.successCard.dark:js.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function Ts(e,t){if(e===null)return{};let r=_s(e,t?js.warning.dark:js.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function Is(e,t){if(e===null)return{};let r=_s(e,t?js.info.dark:js.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function Ps(e,t,r){if(e===null)return t;let n=r.type.lineHeight,i=e/n.normal;if(i===1)return n;let l=e=>Math.round(e*i*100)/100;return{tight:l(n.tight),snug:l(n.snug),normal:l(n.normal),relaxed:l(n.relaxed)}}function zs(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Oo(e),header:[e.surface,e.background,e.chatGround],banner:[zl(e.badgeBgInfo,e.surface)??e.surface,zl(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function Es(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function Os(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var As=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),Ms=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),Fs=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function Ds(e){return typeof e=="string"&&As.includes(e.trim().toLowerCase())}function Ls(e,t){let r=e[t];return r??void 0}var Bs=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Bs)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Vs=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],Hs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Us=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Ns=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],$s=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!Os(e))return null;let t=Ds(e.theme)?Ms[e.theme.trim().toLowerCase()]:{},r=Os(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let i={},l=Ls(n,"colorScheme"),o=typeof l=="string"?l.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(i.color_scheme=o);let s=o==="dark"?"_dark":"";for(let[e,t]of Vs){let r=Ls(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of Hs){let r=Ls(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of Ns){let r=Ls(n,e);typeof r=="string"&&r.trim().length>0&&(i[t]=r.trim())}for(let[e,t]of $s){let r=parsePx(Ls(n,e));r!==void 0&&(i[t]=r)}for(let[e,t]of Us){let r=Ls(n,e);(typeof r=="number"||typeof r=="string")&&(i[t]=r)}let a=e.fonts;Array.isArray(a)&&a.length>0&&(i.font_sources=a);let u=e.rules;if(Os(u)){let e={};for(let t of Ll){let r=u[t];Os(r)&&(e[t]=r)}Object.keys(e).length>0&&(i.slots=e)}return Object.keys(i).length===0?null:/* @__PURE__ */Object.freeze(i)}var Ws="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function qs(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var Gs=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?qs(__EVERFUR_BRAND_CDN_ORIGIN__):Ws;var Ks=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Ys=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),Qs=Object.keys(Ys),Xs="presentation",Zs="presentation.";function isPresentationLockName(e){if(e===Xs)return true;if(!e.startsWith(Zs))return false;let t=e.slice(Zs.length);return Object.values(Ys).includes(t)}var Js={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},ea=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function ta(e,t){if(t==null)return;let r=Js[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:ea.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Qs){let n=Ys[e],i=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],l=ta(e,i);l!==void 0&&(r[e]=l)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${Zs}${Ys[e]}`;for(let e of t)if(e===Xs||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,i=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},l=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,s={};for(let e of Qs){let t=i[e],r=isPresentationFieldLocked(e,o)?void 0:l[e];s[e]=r??t??Ks[e]}/* @__PURE__ */
41
- return Object.freeze(s)}var ra=4,na=/* @__PURE__ */Object.freeze({min:1,max:2}),ia=100,la=2048,oa=["100","200","300","400","500","600","700","800","900"];function sa(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function aa(e){let t=sa(e);if(t===null)return null;let r=String(t);return oa.includes(r)?r:null}function ua(e){let t=sa(e);return t===null?null:Math.min(na.max,Math.max(na.min,t))}function ca(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>la?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function da(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>ia||/[\u0000-\u001F\u007F]/.test(t)?null:t}function fa(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function ha(e){if(!Os(e))return null;let t=da(e.family);if(t===null)return null;let r=fa(e,"src"),n=fa(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=ca(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let i=ca(r);if(i===null)return null;let l={family:t,src:i},o=aa(e.weight);o!==null&&(l.weight=o);let s=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(s==="normal"||s==="italic")&&(l.style=s),/* @__PURE__ */Object.freeze(l)}function pa(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=ra)break;let e=ha(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var ga=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),ma=["content","heading","control","compact","badge"],ba=["sans","heading","mono"],ya=/* @__PURE__ */Object.freeze({min:1,max:3.1});function va(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function xa(e,t){return Math.min(t.max,Math.max(t.min,e))}function wa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ka(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function Ca(e){let t=va(e);return t===null?null:xa(t,ga.typeScale)}function Sa(e){if(!wa(e))return null;let t={};for(let r of ma){let n=va(ka(e,r));n!==null&&(t[r]=n<=0?0:xa(n,ya))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function ja(e){if(!wa(e))return null;let t={},r=va(ka(e,"size","fontSize","font_size"));r!==null&&(t.size=xa(r,ga.size));let n=ua(ka(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let i=aa(ka(e,"weight","fontWeight","font_weight"));i!==null&&(t.weight=i);let l=ka(e,"face");typeof l=="string"&&ba.includes(l.trim())&&(t.face=l.trim());let o=va(ka(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=xa(o,ga.letterSpacing));let s=ka(e,"uppercase");return typeof s=="boolean"&&(t.uppercase=s),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function _a(e){if(!wa(e))return null;let t={};for(let r of io){let n=ja(ka(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var Ra=e=>Math.round(e*10)/10,Ta=e=>Math.round(e*100)/100;function Ia(e,t,r,n){if(t===null&&r===null&&n===null)return e;let i=t===null?null:t/lo.body.size,l=r===null?null:r/lo.body.lineHeight,o={};for(let t of io){let r=e[t],s=lo[t];o[t]=/* @__PURE__ */Object.freeze({...r,...i===null?{}:{size:Ra(s.size*i)},...l===null?{}:{lineHeight:Ta(s.lineHeight*l)},...n?.[t]??{}})}/* @__PURE__ */
42
- return Object.freeze(o)}function Pa(e,t){let r=false,n={};for(let i of io){let l=e[i],o=t(l);o===1?n[i]=l:(r=true,n[i]=/* @__PURE__ */Object.freeze({...l,size:Ra(l.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function za(e,t,r){return{nano:Ra(e.nano*r),small:Ra(e.small*r),micro:Ra(e.micro*r),tiny:Ra(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:Ra(e.verdict*r)}}var Ea=/* @__PURE__ */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","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),Oa="slots.",Aa=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||Aa.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
43
- return new Set(["hide_powered_by",...e?.lockedFields??[]])}function Ma(e){return e==="hide_powered_by"||Ea.includes(e)||isPresentationLockName(e)?true:e.startsWith(Oa)&&Ll.includes(e.slice(Oa.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=Da(t),n=expandAppearance(Va(t,"appearance")),i=n===null?r:Fa(Da(n),r);return isEmptyBranding(i)?null:/* @__PURE__ */Object.freeze(i)}function Fa(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function Da(e){return{displayName:Ha(Va(e,"display_name","displayName")),logoUrl:Ha(Va(e,"logo_url","logoUrl")),primaryColor:parseColor(Va(e,"primary_color","primaryColor")),accentColor:parseColor(Va(e,"accent_color","accentColor")),brightness:Ga(Va(e,"brightness","color_scheme","colorScheme")),fontFamily:Ha(Va(e,"font_family","fontFamily")),fontUrl:Ha(Va(e,"font_url","fontUrl")),fonts:Na(Va(e,"fonts")),fontUrls:Na(Va(e,"font_urls","fontUrls")),placeholder:Ha(Va(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ba(Va(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Va(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Va(e,"accent_color_dark","accentColorDark")),surfaceStyle:qa(Va(e,"surface_style","surfaceStyle"),$a),radiusScale:qa(Va(e,"radius_scale","radiusScale"),Wa),logoUrlDark:Ha(Va(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Va(e,"slots")),accessibilityMaxFontScale:Xa(Va(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:eu(Va(e,"locked_fields","lockedFields")),presentation:parsePresentation(Va(e,"presentation")),schemaVersion:Za(Va(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Va(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Va(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Va(e,"text_color","textColor")),textColorDark:parseColor(Va(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Va(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Va(e,"danger_color_dark","dangerColorDark")),fontSizeBase:La(Va(e,"font_size_base","fontSizeBase"),Fs.fontSizeBase),borderRadius:La(Va(e,"border_radius","borderRadius"),Fs.borderRadius),spacingUnit:La(Va(e,"spacing_unit","spacingUnit"),Fs.spacingUnit),successColor:parseColor(Va(e,"success_color","successColor")),successColorDark:parseColor(Va(e,"success_color_dark","successColorDark")),warningColor:parseColor(Va(e,"warning_color","warningColor")),warningColorDark:parseColor(Va(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Va(e,"info_color","infoColor")),infoColorDark:parseColor(Va(e,"info_color_dark","infoColorDark")),headingFontFamily:Ha(Va(e,"heading_font_family","headingFontFamily")),fontWeightBody:aa(Va(e,"font_weight_body","fontWeightBody")),fontWeightHeading:aa(Va(e,"font_weight_heading","fontWeightHeading")),lineHeight:ua(Va(e,"line_height","lineHeight")),fontSources:pa(Va(e,"font_sources","fontSources")),assistantAvatarUrl:Ha(Va(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Sa(Va(e,"text_scale_caps","textScaleCaps")),typeScale:Ca(Va(e,"type_scale","typeScale")),typeRoles:_a(Va(e,"type_roles","typeRoles"))}}function La(e,t){let r=Ka(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Ba(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}function Va(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function Ha(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Ua=["regular","medium","bold","mono","monoMedium","monoBold"];function Na(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Ua){let n=Ha(Va(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var $a=["white","cream","subtle"],Wa=["sharp","default","round"];function qa(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Ga(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Ka(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}var Ya=1,Qa=3.1;function Xa(e){let t=Ka(e);return t===null?null:t<=0?0:Math.min(Qa,Math.max(Ya,t))}function Za(e){if(e==null)return null;let t=Ka(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Ja(e){let t=e.trim();return t.startsWith(Oa)?t:t.startsWith(Zs)?Zs+t.slice(Zs.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function eu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Ja(r);Ma(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var tu=/* @__PURE__ */new RegExp(`^${Gs}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&tu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Io:Ro:e,n=r.brightness==="dark"?Io:Ro,i=r.brightness==="dark",l=i?t.primaryColorDark??ou(t.primaryColor):t.primaryColor,o=i?t.accentColorDark??ou(t.accentColor):t.accentColor,s=l??r.color.primary,a=o??r.color.accent,u=l!==null&&uu(t,s,n,i),c=u?n.color.primary:s,d=l!==null&&!u?fl(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?cu(n,r.color.text):{},p=(i?t.backgroundColorDark:t.backgroundColor)??null,g=xs(p),m={...r.color,...g},b=(i?t.textColorDark:t.textColor)??null,y=(e,t)=>(i?t??ou(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(i?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...ws(y(t.dangerColor,t.dangerColorDark)),...Rs(y(t.successColor,t.successColorDark),i),...Ts(y(t.warningColor,t.warningColorDark),i),...Is(y(t.infoColor,t.infoColorDark),i),...b!==null?{text:{...h.text??r.color.text,primary:b}}:{},...su(t.surfaceStyle??null,m),primary:c,accent:a,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Cs(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Ss(t.borderRadius,n):fu(t.radiusScale??null,r.radius,n),type:{...r.type,...lu(r.type,t),size:ks(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:Ps(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:Ia(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var ru={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},nu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function iu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function lu(e,t){let r=t.fonts??{},n=t.fontUrls??{},i={...e.families},l={...e.namedFaces},o={...e.fontUrls};for(let e of Ua){let s=ru[e].map(e=>r[e]).find(e=>e!==void 0),a=iu(e)?null:t.fontFamily;s!==void 0?(i[e]=s,l[e]=true):a!==null&&(i[e]=a,l[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:s!==void 0&&delete o[e]}for(let e of nu)for(let t of e)l[t]&&e.some(e=>e!==t&&i[e]===i[t])&&(l[t]=false);return{family:i.regular,mono:i.mono,fontUrl:o.regular??null,families:i,namedFaces:l,fontUrls:o}}function ou(e){return e===null?null:deriveDarkVariant(e)}function su(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function au(e,t){return e==null?false:parseColor(e)===parseColor(t)}function uu(e,t,r,n){return au(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&au(e.primaryColor,Ro.color.primary)}function cu(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}}var du={sharp:.5,default:1,round:1.5};function fu(e,t,r){if(e===null)return t;let n=du[e],i=r.radius,l=e=>Math.round(e*n);return{tile:l(i.tile),xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),pill:i.pill}}var hu="Everfur",pu=.5;function resolveTheme(e){return Pu(gu(e),e)}function themeAdjustments(e){let t=gu(e);return Yo(t,Pu(t,{...e,highContrast:false}))}function gu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=vu(e?.clientOverride??null,lockedFieldsOf(r)),i=e?.colorScheme==="dark"?"dark":"light",l=n?.brightness??r?.brightness??"light",o=wu((l==="auto"?i:l)==="dark"?Io:Ro,e?.typeProfile),s=withServerBranding(o,xu(r));return withServerBranding(s,xu(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function mu(e){return e==="placeholder"?"chat_placeholder":Ja(e)}var bu={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function yu(e,t){return t.has(mu(e))?true:(bu[e]??[]).some(e=>t.has(e))}function vu(e,t){if(e===null)return null;let r=false,n={...e};for(let i of Object.keys(e))(e[i]??null)!==null&&(yu(i,t)||i==="lockedFields")&&(n[i]=null,r=true);let i=n.slots??null;if(i!==null){let e={},l=false;for(let r of Ll){let n=i[r];n!==void 0&&(t.has(`${Oa}${r}`)?l=true:e[r]=n)}l&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let l=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(l)?null:l}function xu(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function wu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:ao}})}function ku(e,t){if(t===1)return e;let r={};for(let[n,i]of Object.entries(e))r[n]=Math.round(i*t*10)/10;return r}function Cu(e){return e===void 0||!Number.isFinite(e)?1:Math.max(pu,e)}var Su=["content","heading","control","compact","badge"];function ju(e,t){let r={};for(let n of Su){let i=e[n],l=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:so[n];n==="content"||!(t>0)?r[n]=l:r[n]=l===0?t:Math.min(l,t)}return Su.every(e=>r[e]===so[e])?so:r}function _u(e,t){return t>0?Math.min(e,t):e}function Ru(e,t,r,n){let i={};for(let l of Su)i[l]=n?ku(e,_u(t,r[l])):e;return i}function Tu(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function Iu(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,headingFamily:e.headingFamily};let i=e.headingFamily!==null&&r!==void 0&&Tu(r,e.headingFamily)===false?null:e.headingFamily,l={...e.families},o={...e.namedFaces};for(let e of Ua)!(l[e]===bo||l[e]===yo)&&r!==void 0&&Tu(r,l[e])===false&&(l[e]=iu(e)?yo:bo,o[e]=false),n!==null&&iu(e)&&l[e]===yo&&(l[e]=n);return{family:l.regular,mono:l.mono,families:l,namedFaces:o,headingFamily:i}}function Pu(e,t){let r=e.meta.displayName.trim().length===0?hu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),i={};for(let t of Ua){let r=e.type.fontUrls[t];r!==void 0&&(i[t]=hardenHttpsUrl(r))}let l=i.regular??null,o=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,s=Number.isFinite(e.type.maxScale)?e.type.maxScale:mo,a=Cu(t?.textScale),u=ju(e.type.scaleCaps,s),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=Pa(e.type.roles,()=>d),h=c?Pa(f,e=>_u(a,u[e.tier])):f,p=t?.typeProfile==="phone"?za(e.type.size,f,d):ku(e.type.size,d),g=Ru(p,a,u,c),m=Bo(e),b={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:m,space:e.space,radius:e.radius,type:{...e.type,...Iu(e.type,t),fontUrl:l,fontUrls:i,size:g.content,tierSizes:g,scale:a,maxScale:s,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,zs(m),Es(m))};return t?.highContrast===true?deriveHighContrast(deepFreeze(b)):deepFreeze(b)}var zu="/widget/v1/entitlements",Eu=304,Ou=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",Mu(t));return n.ok?Fu(n.value):n.error.httpStatus===Eu?Ou:{kind:"failed",error:n.error}}var Au=64;function Mu(e){let t={};return Uu(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Au?{method:"GET",path:zu,headers:t,query:{region:e.region}}:{method:"GET",path:zu,headers:t}}function Fu(e){if(e===null||typeof e!="object"||!Uu(e.revision))return Hu();let t=typeof e.region=="string"?e.region:"",r=Uu(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
44
- return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Bu(e.capabilities),branding:Lu(e),livemode:e.livemode!==false,...Du(e)})}function Du(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function Lu(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function Bu(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Vu(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
45
- return Object.freeze(t)}function Vu(e){return typeof e=="object"&&e!==null&&e.enabled===true}function Hu(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function Uu(e){return typeof e=="number"&&Number.isFinite(e)}var Nu=30;function createEntitlementPoller(e){let t=e.scheduler??$u,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??Nu),i=e.rng??Math.random,l=()=>n+i()*n,o=false,s=false,a=null,u=null,c=n,d=0,f=()=>{a!==null&&(t.clear(a),a=null)},h=e=>{s||!o||(c=Math.max(n,e),a=t.set(()=>{a=null,m()},c*1e3))},p=null,g=async()=>{if(s)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},i;try{i=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Wu(r)}),!s&&t===d&&(e.onSettled?.(),h(l())),null}if(s||t!==d)return null;switch(i.kind){case"updated":u=i.revision,i.smsProfilePublic!==void 0?e.update(i.decisions,i.branding??null,i.livemode!==false,i.smsProfilePublic):e.update(i.decisions,i.branding??null,i.livemode!==false),h(i.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:i.error.code}),h(l());break;default:h(l())}return e.onSettled?.(),i},m=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||s||(o=true,m())},prime(){return s?Promise.resolve(null):p??m()},stop(){s||(s=true,d++,f())},refresh(){s||!o||(d++,u=null,f(),m())}}}var $u={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function Wu(e){return e instanceof Error?e.message:"poll failed"}var qu=20;function Gu(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},i=/* @__PURE__ */new Map,l=/* @__PURE__ */new Set,o=0,s=/* @__PURE__ */new Map,a=(r,i)=>{let o=r??"",s=t.get(o)??n(r);if(!(s.hasUnread===i.hasUnread&&s.unreadCount===i.unreadCount&&s.conversationId===i.conversationId)){t.set(o,i);for(let e of[...l])e();l.size>0&&i.hasUnread!==null&&i.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:i.conversationId,unreadCount:i.unreadCount,hasUnread:i.hasUnread})}},u=(e,t)=>{s.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}a(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){s.delete(e??""),a(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,qu).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let i=new Set(n.map(e=>e.id)),l=(s.get(e??"")??[]).filter(e=>!i.has(e.id));u(e,[...n,...l].slice(0,qu))};return{subscribe(e){return l.add(e),()=>{l.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=i.get(r);if(n!==void 0)return n;let l=e.read(t);if(l===null)return Promise.resolve();let s=o,a=l.then(e=>{s!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{i.get(r)===a&&i.delete(r)});return i.set(r,a),a},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=s.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,i.clear(),s.clear(),t.size!==0){t.clear();for(let e of[...l])e()}}}}function Ku(e,t,r){let n=Xr({...t===null?{}:{petRef:t},limit:qu},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?rn(e.value):err(e.error)):Promise.resolve(err(n.error))}var Yu="everfur.notifications.device";var Qu="everfur.slots.v2",Xu="everfur.slots.installId.v2";var Zu=3e3,Ju=/* @__PURE__ */Object.freeze([Yu,Qu,Xu]);function ec(e){let{leaving:t,identity:r,hooks:n,telemetry:i}=e;if(t===null||r===null||n.size===0)return null;let l=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(l))}catch(e){return Promise.reject(e)}}),s=(e,t)=>{try{i.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},a=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&s("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||s("timeout",o.length),r()},Zu);a.then(r,r)})}function tc(e){let{leaving:t,identity:r,transport:n,sessionId:i}=e,l=r.currentToken();l.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>l,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:i}}async function rc(e,t){if(Ju.length===0)return;let r=await Promise.allSettled(Ju.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function nc(){/* @__PURE__ */
46
- return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function ic(e=nc){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var lc="everfur.branding.v1.";function oc(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function sc(e){let t=3421674724,r=2216829733;for(let n of oc(e)){r=(r^n)>>>0;let e=r*435,i=Math.floor(e/4294967296),l=e>>>0;t=t*435+i+r*256>>>0,r=l}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function ac(e){return`${lc}${sc(e)}`}function uc(e){return e?JSON.stringify(e):null}async function cc(e,t){try{let r=await e.getItem(ac(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function dc(e,t,r){try{r===null?await e.removeItem(ac(t)):await e.setItem(ac(t),r)}catch{}}function fc(e,t){let r;return{restore(r){cc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let i=uc(n);i!==r&&(r=i,dc(e,t,i))}}}function hc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function pc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:hc(),store:null,disposed:false}}function gc(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function mc(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}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function bc(e,t){/* @__PURE__ */
47
- return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:yc(r,n,t))}catch{}}})}function yc(e,t,r){let n=e.indexOf("."),i=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",l=typeof t?.requestId=="string"?t.requestId:null;return{...Ge(r,i,l),...t}}function vc(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(i,l)=>n.call(e,i,l??Ge(t,r,i.requestId))}:{}}}var xc=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${et} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function wc(e,t,r=Ze){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+xc[r])}function kc(e){/* @__PURE__ */
48
- return Object.freeze({request(){return Promise.resolve(err(gc(e)))},stream(t,r){let n=errorFrame({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)}}}})}var Cc=/* @__PURE__ */new WeakSet;function Sc(){let e=/* @__PURE__ */new Map,t={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(e=>e.startsWith(t))}};return Cc.add(t),t}var jc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Rc(e,t)}var _c=6e4,Rc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new m("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Xe,platform:t?.platform??Ze,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Qe(r?.appVersion)}),this.telemetry=r.telemetry?bc(r.telemetry,this.errorContext):ae,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",i=checkPublishableKey(r?.publishableKey),l=r.transport!==void 0,o,s=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(i!==null)o=kc(i);else if(r.transport!==void 0)o=r.transport;else{let e=mc(r,t?.platform);e.ok?(s=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(i=e.failure,o=kc(e.failure))}if(this.configFailure=i,this.publishableKey=i===null?n:"",this.mintScope=`${this.publishableKey}|${s??""}`,nl(this,this.mintScope),this.transport=o,i!==null&&(wc(i,this.telemetry,t?.platform),this.emit({type:"error",code:gc(i).code,requestId:null,context:Ge(this.errorContext,"runtime",null)})),this.errorPolicy=vc(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??ce,this.upload=r.upload??gr,this.uploadTransport=r.uploadTransport??Pn,this.imageCache=r.imageCache??jc,this.kv=r.storage??Sc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=i===null?ic():ic(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:s},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",Tc(e),()=>this.buildChatController(e),Ic),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${Tc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=Gu({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Ku(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),i===null){this.brandingCache=fc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=i===null?pc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let a=i===null&&(t?.startEntitlementPolling??!l);this.poller=i===null?this.buildPoller(t?.pollScheduler):null,a&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=dl(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-_c,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Ji(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let i=this.store.getSnapshot().branding??null,l=i!==null&&t!=null&&uc(i)===uc(t)?i:t;this.updateEntitlements({decisions:e,isPending:false,branding:l,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(l??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,i=false){let l=`${this.epoch}|${e}|${t}`,o=this.entries.get(l);if(o)return i||(o.warm?o.warm=false:o.refCount+=1),o.controller;let s=r();return this.entries.set(l,{controller:s,refCount:1,warm:i}),this.destroyers.set(s,n),s}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:vc(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await rc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return ec({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>tc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>ll(il(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(Pc(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&ul(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let i={key:r,result:null,promise:this.runPrepare(t).then(e=>(i.result=e,e))};return this.prepared=i,i.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?Pc("prepare"):r===null?null:gc(r),i=this.identity,[l,o,s]=await Promise.all([n?err(n):i===null?ok(void 0):i.currentToken().then(()=>ok(void 0),e=>(i.reportRejected?.(),err(ve(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),a=l.ok?o.ok&&(s?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:a})}catch{}if(a==="ready")this.emit({type:"ready"});else if(a==="failed"&&!l.ok&&r===null&&!this.disposed){let e=l.error.requestId??null;this.emit({type:"error",code:l.error.code,requestId:e,context:Ge(this.errorContext,"runtime",e)})}/* @__PURE__ */
49
- return Object.freeze({status:a,durationMs:u,session:l,entitlements:o,...s?{chat:s}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",Tc(t),()=>this.buildChatController(t),Ic,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function Tc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function Ic(e){e.dispose()}function Pc(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function zc(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function Ec(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function Oc(e){return e.ok?e:err(Ec(e.error))}function Ac(e){return{send:async(...t)=>Oc(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Mc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),Fc=globalThis,Dc=Fc[Mc]??(Fc[Mc]=t.createContext(null));Dc.displayName??="EverfurContext";function Lc(){let e=t.useContext(Dc);if(e===null)throw new m("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return Lc().handle}var Bc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Vc=globalThis,Hc=Vc[Bc]??(Vc[Bc]=t.createContext(Ro));Hc.displayName??="EverfurThemeContext";function useEverfurTheme(){return t.useContext(Hc)}var Uc=()=>()=>{},Nc=()=>null;function $c(e,r){return t.useSyncExternalStore(r?.subscribe??Uc,r?.get??Nc,r?.get??Nc)??e}function EverfurThemeProviderCore(e){let{runtime:r}=Lc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot),l=e.seams.useColorScheme(),o=e.seams.useReducedMotion(),s=e.seams.useTextScale(),a=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,c=e.seams.typeProfile,d=e.seams.platformMonoFamily?.(),f=e.seams.isFontRegistered,h=e.clientTheme?Wc(e.clientTheme):"",p=t.useMemo(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[h]),g=$c(i.branding??null,r.sdkConfigHost?.branding),m=t.useMemo(()=>resolveTheme({branding:g,clientOverride:p,colorScheme:l,reducedMotion:o,textScale:s,scaleTypeSizes:u,highContrast:a,...c===void 0?{}:{typeProfile:c},...d===void 0?{}:{platformMonoFamily:d},...f===void 0?{}:{isFontRegistered:f}}),[g,p,l,o,s,u,c,a,d,f]);e.seams.useResolvedTheme?.(m);let b=e.seams.isDevelopment;return t.useEffect(()=>{b===void 0||!qc(b)||Xo(themeAdjustments({branding:g,clientOverride:p,colorScheme:l}))},[b,g,p,l]),t.createElement(Hc.Provider,{value:m},e.children)}function Wc(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function qc(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:r,user:n,activePet:i,theme:l,warmUp:o,children:s,seams:a}=e,u=`${r?.publishableKey??""}|${r?.apiBaseUrl??""}|${r?.contractVersion??""}`,c=t.useRef(null),d=t.useRef(null),f=t.useRef(r?.onEvent);f.current=r?.onEvent;let h=t.useRef(e=>{f.current?.(e)}),[p,g]=t.useReducer(e=>e+1,0),m=t.useRef(null),b=t.useRef(void 0),y=n?.userRef??null;b.current!==y&&(b.current!==void 0&&(m.current=null),b.current=y);let v=m.current!==null?m.current.user:n??null,x=t.useRef(null),w=t.useRef(void 0),k=i??null;w.current!==k&&(w.current!==void 0&&(x.current=null),w.current=k);let C=x.current!==null?x.current.pet:i??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:createEverfurRuntime({config:Gc(a.withDefaults?a.withDefaults(r):r,h.current),user:v,activePet:C,theme:l??null},{platform:a.platform,...a.eventSourceFactory?{eventSourceFactory:a.eventSourceFactory}:{}})});let S=c.current.runtime,j=t.useRef(null);t.useEffect(()=>{let e=c.current?.runtime;e===void 0||!e.isDisposed||j.current!==e&&(j.current=e,g())}),t.useEffect(()=>{let e=d.current;e!==null&&(d.current=null,e.dispose())});let _=v?.userRef??null;t.useLayoutEffect(()=>{S.setUser(v)},[S,_]),t.useLayoutEffect(()=>{S.setActivePet(C)},[S,C]);let R=t.useRef(null);t.useEffect(()=>(R.current===S&&(R.current=null),()=>{R.current=S,Kc(()=>{R.current===S&&(R.current=null,S.dispose())})}),[S]),t.useEffect(()=>{o==="onMount"&&S.prepare(C===null?{}:{petRef:C})},[S,o,_,C]);let T=t.useMemo(()=>({setUser:e=>{m.current={user:e},S.setUser(e),g()},setActivePet:e=>{x.current={pet:e},S.setActivePet(e),g()},open:e=>S.open(e),prepare:e=>S.prepare(e),registerPet:(e,t)=>S.registerPet(e,t),updatePet:(e,t)=>S.updatePet(e,t),deletePet:e=>S.deletePet(e),eraseUserData:()=>S.eraseUserData(),logout:()=>{m.current={user:null};let e=S.logout();return g(),e}}),[S,g]),I=t.useMemo(()=>({runtime:S,handle:T,userRef:_,activePet:C,scopeEpoch:S.scopeEpoch,publishableKey:Yc(r)}),[S,T,_,C,p,u]),P=t.createElement(EverfurThemeProviderCore,{clientTheme:l??null,seams:a.theme,children:s});return t.createElement(Dc.Provider,{value:I},a.wrap?a.wrap(P):P)}function Gc(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Kc(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Yc(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Qc=2;function Xc(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Qc)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Zc(){let e=c.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:e=>Xc(n,e)})}}function Jc(){let e=r.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}function ed(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function td(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,t=r.AccessibilityInfo?.isReduceMotionEnabled;if(typeof t=="function"){let i=t.call(r.AccessibilityInfo);i!=null&&typeof i.then=="function"&&i.then(t=>{e&&n(t===true)},()=>{})}let i=r.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",e=>n(e===true));return()=>{e=false,i?.remove?.()}},[]),e}function rd(){let e=r.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(r.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function nd(e){let t=r.Dimensions?.addEventListener;if(typeof t!="function")return()=>{};let n=t.call(r.Dimensions,"change",e);return()=>n?.remove?.()}function id(){return t.useSyncExternalStore(nd,rd,rd)}function ld(){try{let e=r.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}function od(){return ld()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function sd(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,{query:t,event:i}=od(),l=r.AccessibilityInfo?.[t];if(typeof l!="function")return()=>{};try{let t=l.call(r.AccessibilityInfo);ed(t)&&Promise.resolve(t).then(t=>{e&&n(t===!0)},()=>{})}catch{}let o=r.AccessibilityInfo?.addEventListener,s=typeof o=="function"?o.call(r.AccessibilityInfo,i,e=>n(e===true)):void 0;return()=>{e=false,s?.remove?.()}},[]),e}function ad(){return ld()==="ios"?"Menlo":yo}function ud(){return globalThis.__DEV__!==false}var cd=/* @__PURE__ */new Set;function dd(e){if(!ud()||cd.has(e))return;cd.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{}}function fd(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 i=n.includes(e);return i||dd(e),i}var hd=/* @__PURE__ */new Set;function pd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var gd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function md(e){if(!ud())return;let t=pd(e).filter(e=>!hd.has(e));if(t.length===0)return;for(let e of t)hd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>gd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function bd(e){t.useEffect(()=>{try{md(e)}catch{}},[e])}var yd=/* @__PURE__ */Object.freeze({useColorScheme:Jc,useReducedMotion:td,useTextScale:id,useHighContrast:sd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:ad,isFontRegistered:fd,useResolvedTheme:bd,isDevelopment:ud});function vd(e){return t.createElement(n.SafeAreaProvider,null,e)}var xd=/* @__PURE__ */Object.freeze({platform:"react-native",...r.Platform.OS==="web"?{}:{eventSourceFactory:Zc()},wrap:vd,theme:yd});function EverfurProvider(e){return t.createElement(EverfurProviderCore,{...e,seams:xd})}function useCapability(e){let{runtime:r}=Lc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return t.useMemo(()=>decideCapability(e,i.decisions,{isPending:i.isPending}),[e,i])}function wd(e){let{runtime:r}=Lc(),n=r.entitlements,i=t.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),l=t.useCallback(()=>{if(n===void 0)return false;let t=n.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[n,e]);return t.useSyncExternalStore(i,l,l)}var kd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[kd[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[kd[t]]};let i=face(e,t);return i.fontWeight===void 0||n===null?i:{fontFamily:i.fontFamily,fontWeight:n}}function Cd(e){return e<=450?"regular":e<=650?"medium":"bold"}var Sd={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=jd.get(e);r===void 0&&(r=/* @__PURE__ */new Map,jd.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=_d(e,t);return r.set(t,i),i}var jd=/* @__PURE__ */new WeakMap;function _d(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,i=Cd(Number(n)),l=r.face==="mono"?face(e,Sd[i]):r.face==="heading"?headingFace(e,i):face(e,i),o=r.face==="heading"?e.type.headingWeight??n:n,s=l.fontWeight===void 0?l:{fontFamily:l.fontFamily,fontWeight:o},a=r.size,u={...s,fontSize:a,lineHeight:Math.round(a*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(a*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Rd(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:n,...i}){let l=useEverfurTheme(),o=n===void 0?void 0:l.type.roles[n],s=Rd(l.type,e??o?.tier??"content"),a=n===void 0?i:{...i,style:[{...textRole(l,n),color:l.color.text.primary,flexShrink:1},i.style]};return t.createElement(r.Text,s===void 0?a:{maxFontSizeMultiplier:s,...a})}var Td=t.forwardRef(function(e,n){return t.createElement(r.TextInput,{...e,...n===null?{}:{ref:n}})});var Id=class extends t.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:r,resetKey:n}){return t.createElement(Id,{fallback:r,resetKey:n,children:t.createElement(RenderHost,{render:e})})}var Pd=48;function zd(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:r,children:n,renderDisabled:i,renderPending:o,style:s}=e,a=useCapability(r),u=t.useMemo(()=>zd(a),[a]);switch(u){case"enabled":return n;case"pending":return o?/* @__PURE__ */l.jsx(HostRender,{render:o,fallback:/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s})}):/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s});case"disabled":return i?/* @__PURE__ */l.jsx(HostRender,{render:()=>i(a),fallback:/* @__PURE__ */l.jsx(OffState,{decision:a,style:s}),resetKey:a}):/* @__PURE__ */l.jsx(OffState,{decision:a,style:s});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Ed(i),[i]);/* @__PURE__ */
50
- return l.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */l.jsx(r.View,{style:o.skeletonBar})})}function OffState({decision:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Ed(i),[i]),s=e.disabled?.reason??"";/* @__PURE__ */
51
- return l.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityRole:"text",accessibilityLabel:s,children:s.length>0?/* @__PURE__ */l.jsx(Text,{style:o.offstateText,children:s}):null})}function Ed(e){let{color:t,space:n,radius:i,type:l}=e;return r.StyleSheet.create({offstate:{minHeight:Pd,justifyContent:"center",paddingHorizontal:n.lg,paddingVertical:n.md,backgroundColor:t.surfaceCream,borderRadius:i.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:n.md,borderRadius:i.xs,backgroundColor:t.brandSofter}})}var Od=t.createContext(null);function TelevetHostOutlet(){let e=t.useContext(Od);return e===null?null:/* @__PURE__ */l.jsx(e,{})}var Ad=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function Md(){let e=globalThis,t=e[Ad];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[Ad]=r,r}function Fd(e){let t=Md();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function Dd(e){let t=Md().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function Ld(e){let t=Md();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function Bd(){return Md().snapshot}function Vd(){return Md().hosts.length>0}function Hd(e){if(!Vd())return false;let t=/* @__PURE__ */Object.freeze({...e});return Fd({request:t,serial:Md().snapshot.serial+1}),true}function Ud(){Md().snapshot.request!==null&&Fd({request:null})}function Nd(){let e=Md(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Fd({activeHost:e.hosts[0]??null}),t}function $d(e){let t=Md();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;Fd(r===null?{activeHost:r,request:null}:{activeHost:r})}function Wd(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}}function qd(e){let[r,n]=t.useState(null);t.useEffect(()=>{let e=Nd();return n(e),()=>{$d(e)}},[]);let i=t.useSyncExternalStore(Ld,Bd,Bd),l=r!==null&&i.activeHost===r?i.request:null,[o,s]=t.useState(null),a=l!==null&&o===null;return t.useEffect(()=>{if(!a)return;let t=true;return e().then(e=>{t&&s(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),Ud())}),()=>{t=false}},[a,e]),l===null||o===null?null:{module:o,request:l,serial:i.serial,dismiss:Ud}}var Gd=Wd(()=>Promise.resolve(d));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let i=qd(Gd);if(i===null)return null;let{EverfurTelevetModal:o}=i.module;/* @__PURE__ */
52
- return l.jsx(o,{request:i.request,onClose:i.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},i.serial)}var Kd="Go to the nearest emergency vet now.";var Yd=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",sourcesHeading:"Sources",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:Kd,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",capReached:"You've used your {cap} free messages this month.",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 Qd(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function Xd(e){return e?.trim()||Yd.emptyTitlePetFallback}function Zd(e,t){return Qd(e,{petName:Xd(t)})}var Jd="tel:+18884264435";var ef=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function tf(e){let t=ef(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var rf=6;function nf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function lf(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let i of e){if(n.length>=r)break;if(i===null||typeof i!="object"||Array.isArray(i))continue;let e=t(i);e!==null&&n.push(e)}/* @__PURE__ */
53
- return Object.freeze(n)}function of(e){let t=ef(e.title,80),r=ef(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function sf(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=tf(e);t!==null&&r.length<rf&&r.push(t)}let n=lf(t.doses,e=>{let t=ef(e.label,60),r=ef(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:nf(e.minLb??e.min_lb),maxLb:nf(e.maxLb??e.max_lb)})},rf),i=lf(t.details,of,rf),l=t.fit,o=l!==null&&typeof l=="object"&&!Array.isArray(l)?of(l):null,s=o!==null&&l.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,a=/* @__PURE__ */Object.freeze({kicker:ef(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:i,fine:ef(t.fine,300),fit:s});return a.kicker===null&&r.length===0&&n.length===0&&i.length===0&&a.fine===null&&s===null?void 0:a}var af=128;var uf=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),cf=/* @__PURE__ */new Set(["y","c","g","r"]),df=/* @__PURE__ */new Set(["done","now","next"]),ff=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,hf=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,pf=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,gf=e=>typeof e=="string"&&uf.has(e)?e:null;function mf(e){let t=hf(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var bf=e=>typeof e=="number"&&Number.isInteger(e)?String(e):hf(e,af);function yf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function vf(e){/* @__PURE__ */
54
- return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function xf(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let i of e){if(n.length>=r)break;let e=t(i);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var wf=(e,t=12,r=300)=>xf(e,e=>hf(e,r),t);function kf(e){let t=ff(e),r=hf(t?.kicker,120),n=hf(t?.title,300);if(t===null||r===null||n===null)return null;let i=ff(t.risk),l=ff(t.odds),o=ff(t.quote),s=ff(t.jump);return vf({kicker:r,title:n,sources:xf(t.sources,e=>{let t=hf(ff(e)?.label,60);return t===null?null:vf({label:t,kind:pf(ff(e)?.kind)})},6),risk:hf(i?.lead,300)===null?null:vf({lead:hf(i?.lead,300),body:hf(i?.body),kind:pf(i?.kind)}),odds:hf(l?.label,120)===null||hf(l?.from,20)===null||hf(l?.to,20)===null?null:vf({label:hf(l?.label,120),tag:hf(l?.tag,40),from:hf(l?.from,20),to:hf(l?.to,20),toLabel:hf(l?.toLabel,120)}),quote:hf(o?.text)===null?null:vf({kicker:hf(o?.kicker,120),tag:hf(o?.tag,40),text:hf(o?.text)}),jump:hf(s?.title,300)===null||hf(s?.go,60)===null?null:vf({title:hf(s?.title,300),go:hf(s?.go,60)}),report:Cf(t.report)})}function Cf(e){let t=ff(e),r=hf(t?.label,120),n=hf(t?.text,1200);return r===null||n===null?null:vf({label:r,text:n,actions:wf(t?.actions,5,300)})}function Sf(e){let t=ff(e),r=hf(t?.title,300),n=xf(t?.steps,e=>{let t=ff(e),r=hf(t?.title,300),n=t?.tone;return r===null?null:vf({title:r,body:hf(t?.body),source:hf(t?.source,200),tone:typeof n=="string"&&cf.has(n)?n:null,icon:gf(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:vf({title:r,label:hf(t?.label,60),steps:n})}function jf(e){let t=ff(e),r=hf(t?.title,300);if(t===null||r===null)return null;let n=ff(t.rating),i=ff(t.reviews),l=ff(t.why),o=ff(l?.score),s=ff(t.dose),a=ff(t.ingredients),u=xf(i?.items,e=>{let t=ff(e),r=t?.stars,n=hf(t?.text),i=hf(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||i===null?null:vf({stars:Math.round(r),text:n,by:i})},5),c=xf(l?.rows,e=>{let t=ff(e),r=hf(t?.chip,40),n=hf(t?.title,300);return r===null||n===null?null:vf({chip:r,kind:pf(t?.kind),title:n,body:hf(t?.body)})}),d=xf(s?.stats,e=>{let t=ff(e),r=hf(t?.value,40),n=hf(t?.label,120),i=t?.kind;return r===null||n===null?null:vf({value:r,label:n,kind:i==="weight"||i==="dose"||i==="days"?i:null})},6),f=wf(a?.items,12,80);return vf({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:bf(t.productId),partnerSku:hf(t.partnerSku,200),rating:hf(n?.value,20)===null?null:vf({value:hf(n?.value,20),label:hf(n?.label,120)}),line:hf(t.line),reviews:hf(i?.label,200)===null||u===null?null:vf({label:hf(i?.label,200),items:u}),checkoutLine:hf(t.checkoutLine,300),why:hf(l?.title,200)===null||c===null?null:vf({title:hf(l?.title,200),rows:c,score:hf(o?.text,200)===null||hf(o?.value,20)===null?null:vf({text:hf(o?.text,200),value:hf(o?.value,20)})}),dose:hf(s?.title,200)===null||d===null?null:vf({title:hf(s?.title,200),stats:d,note:hf(s?.note)}),doseLabel:hf(t.doseLabel,120),ingredients:f===null?null:vf({label:hf(a?.label,200),items:f}),proof:hf(t.proof,300),trust:xf(t.trust,e=>{let t=ff(e),r=gf(t?.icon),n=hf(t?.label,120);return r===null||n===null?null:vf({icon:r,label:n})},6),more:hf(t.more,120),fine:hf(t.fine),checkin:hf(t.checkin,200),detail:sf(t.detail)??null})}function _f(e){let t=ff(e),r=hf(t?.title,200),n=xf(t?.items,e=>{let t=ff(e),r=hf(t?.title,300),n=hf(t?.body);return r===null||n===null?null:vf({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:vf({title:r,items:n})}function Rf(e){let t=ff(e),r=hf(t?.title,200),n=wf(t?.questions,12,300),i=hf(t?.add,80),l=hf(t?.added,80);return r===null||n===null||i===null||l===null?null:vf({title:r,questions:n,add:i,added:l})}function Tf(e){let t=ff(e),r=hf(t?.title,200),n=xf(t?.items,e=>{let t=ff(e),r=hf(t?.key,af),n=hf(t?.title,300),i=hf(t?.action,80),l=bf(t?.productId),o=hf(t?.added,80)??(l!==null?i:null);return r===null||n===null||i===null||o===null?null:vf({key:r,productId:l,title:n,body:hf(t?.body),price:hf(t?.price,40),was:hf(t?.was,40),tag:hf(t?.tag,40),imageUrl:mf(t?.imageUrl),icon:gf(t?.icon),kind:pf(t?.kind),action:i,added:o,owned:t?.owned===true?true:null,detail:sf(t?.detail)??null})},6);return r===null||n===null?null:vf({title:r,items:n})}function If(e){let t=ff(e),r=hf(t?.kicker,120),n=hf(t?.title,120);return t===null||r===null||n===null?null:vf({kicker:r,title:n,icon:gf(t.icon),track:xf(t.track,e=>{let t=ff(e),r=hf(t?.title,120),n=t?.state;return r===null?null:vf({title:r,detail:hf(t?.detail,120),state:typeof n=="string"&&df.has(n)?n:null,tag:hf(t?.tag,40)})},6),heading:hf(t.heading,200),rows:xf(t.rows,e=>{let t=ff(e),r=gf(t?.icon),n=hf(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return vf({icon:r,label:n,text:"",fromVet:true});let i=hf(t?.text,300);return i===null?null:vf({icon:r,label:n,text:i})},6),note:hf(t.note,300),action:hf(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=ff(e),r=hf(t?.title,300),n=jf(t?.pick);if(t===null||r===null||n===null)return null;let i=ff(t.byline);return vf({eyebrow:hf(t.eyebrow,120),title:r,subtitle:hf(t.subtitle,300),subtitleNoRecords:hf(t.subtitleNoRecords,300),headImageUrl:mf(t.headImageUrl),byline:hf(i?.name,120)===null?null:vf({name:hf(i?.name,120),role:hf(i?.role,120),imageUrl:mf(i?.imageUrl),shortName:hf(i?.shortName,60)}),focus:kf(t.focus),routine:Sf(t.routine),pick:n,signs:_f(t.signs),checkup:Rf(t.checkup),extras:Tf(t.extras),wait:If(t.wait),fine:hf(t.fine),checkoutRows:xf(t.checkoutRows,e=>{let t=ff(e),r=gf(t?.icon),n=hf(t?.label,60),i=hf(t?.value,200);return r===null||n===null||i===null?null:vf({icon:r,label:n,value:i})},6)})}function healthPlanPageFromWire(e,t){let r=ff(e);if(r===null||!("page"in r))return null;let n=ff(r.pet),i=n?.sex;/* @__PURE__ */
55
- return Object.freeze({petRef:hf(r.pet_ref,af)??t,pet:/* @__PURE__ */Object.freeze({name:hf(n?.name,120),species:hf(n?.species,60),sex:i==="female"||i==="male"?i:null,breed:hf(n?.breed,120),weightKg:yf(n?.weight_kg),weightLb:yf(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function Pf(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function zf(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function Ef(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var Of=e=>typeof e=="string"&&e.length>0&&e.length<=af;function Af(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function Mf(e,t,r){if(!Of(t))return err(Pf("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${Af(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let i=healthPlanPageFromWire(n.value,t);return i===null?err(zf("healthPlan.page.read")):ok(i)}var Ff=/* @__PURE__ */new WeakMap;function Df(e){let t=Ff.get(e);if(t!==void 0)return t;let r=Lf(e);return Ff.set(e,r),r}function Lf(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(Ef("getPage")));let{services:n}=e.registry,i=Ac(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return Mf(i,t,r)}}}function Bf(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function Vf(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Hf(e,...t){if(typeof e=="function")try{let r=e(...t);return Vf(r)&&Promise.resolve(r).then(void 0,Bf),r}catch(e){Bf(e);return}}var Uf=/* @__PURE__ */new WeakMap;function Nf(e){if(typeof e!="function")return;let t=Uf.get(e);if(t!==void 0)return t;let r=(...t)=>{Hf(e,...t)};return Uf.set(e,r),r}function $f(e,...t){let r;try{r=e(...t)}catch(e){return Bf(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Wf=6e4;function qf({lifecycle:e,refreshKey:r,readyAt:n,revalidate:i,refresh:l,now:o=Date.now}){let s=t.useRef({readyAt:n,revalidate:i,refresh:l??i,now:o});s.current={readyAt:n,revalidate:i,refresh:l??i,now:o},t.useEffect(()=>{if(e==null)return;let t=Hf(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=s.current;e!==null&&r()-e>=Wf&&t()}));return()=>{typeof t=="function"&&Hf(t)}},[e]);let a=t.useRef(r);t.useEffect(()=>{Object.is(a.current,r)||(a.current=r,s.current.refresh())},[r])}var Gf=Wf,Kf=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function Yf(){let e=globalThis,t=e[Kf];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[Kf]=r,r}function Qf(e,t,r,n,i){let l=Yf(),o=l.get(t);o===void 0&&(o=/* @__PURE__ */new Map,l.set(t,o));let s=o,a=`${r}\0${n}`,u=s.get(a);if(!i&&u!==void 0&&(u.at===null||Date.now()-u.at<Gf))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(s.get(a)===c&&(e.ok||zc(e.error)?c.at=Date.now():s.delete(a)),e))};return s.set(a,c),c.promise}function useHealthPlanPage(e){let{userRef:r,runtime:n}=Lc(),i=t.useMemo(()=>Df(n),[n]),l=e.repository,o=l??i,s=t.useCallback((e,t)=>l!==void 0||r==null?o.getPage(e):Qf(i,n,r,e,t),[l,o,i,n,r]),{petRef:a}=e,u=e.enabled!==false&&r!=null&&a!==null,[c,d]=t.useState({phase:"idle",petRef:null,page:null,error:null}),f=t.useRef(0),h=t.useRef(0),p=t.useCallback(async e=>{let t=++f.current;if(!u||a===null){d(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}d(e=>({phase:"loading",petRef:a,page:e.petRef===a?e.page:null,error:null}));let r=await s(a,e);t===f.current&&(r.ok?d({phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}):zc(r.error)?d({phase:"ready",petRef:a,page:null,error:null,missing:true,readyAt:Date.now()}):d({phase:"failed",petRef:a,page:null,error:r.error}))},[u,a,s]),g=t.useCallback(()=>p(true),[p]),m=c.phase==="ready"&&c.petRef===a,b=t.useCallback(async()=>{if(!u||a===null||!m)return;let e=f.current,t=++h.current,r=await s(a,true);e!==f.current||t!==h.current||!r.ok||d(e=>e.phase==="ready"&&e.petRef===a?{phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}:e)},[u,a,m,s]);qf({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:m?c.readyAt??null:null,revalidate:()=>{b()},refresh:()=>{m?b():g()}}),t.useEffect(()=>(p(false),()=>{f.current+=1}),[p]);let y=u&&c.petRef!==a;return t.useMemo(()=>({phase:y?"loading":c.phase,page:y?null:c.page,error:y?null:c.error,missing:!y&&c.missing===true,refresh:g}),[y,c,g])}var Xf=/* @__PURE__ */Object.freeze({branding:null}),Zf=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>Xf});function Jf(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function eh(e){let{runtime:r}=Lc(),n=r?.entitlements??Zf,i=t.useCallback(()=>n.getSnapshot()?.branding??null,[n]),l=$c(t.useSyncExternalStore(n.subscribe,i,i),r?.sdkConfigHost?.branding),o=Jf(e);return t.useMemo(()=>{let t=l?.lockedFields??null;return{presentation:resolvePresentation({server:l?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[l,o])}function th(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function rh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function nh(e){let t=ze(e);return t===null?null:{reached:Yd.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function ih(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function lh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=ih(r),n=t==="web",i=nh(r);return{tone:"error",title:i!==null?i.reached:e?Yd.turnUnreachableTitle:n?Yd.turnFailedTitleWeb:Yd.turnFailedTitle,body:r.displayMessage,actionLabel:e?Yd.turnStartNewChat:n?Yd.retry:Yd.turnRetry,action:e?"startNew":"retry",...i!==null&&i.guidance!==null?{guidance:i.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:Yd.turnStoppedTitle,body:Yd.turnStoppedBody,actionLabel:Yd.turnRetry,action:"retry"}:null}function oh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var sh=3,ah=/* @__PURE__ */Object.freeze([]);function uh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return ah;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),i=e.replace(/\s+/g," ").toLowerCase();if(!(i.length===0||r.has(i))&&(r.add(i),n.push(e),n.length===sh))break}/* @__PURE__ */
56
- return Object.freeze(n)}var ch=5;function dh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function fh(e,t){if(t===void 0)return uh(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return ah;let n=Math.max(1,Math.min(ch,Math.floor(t.count??sh))),i=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){i=r.text;break}}let l=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(i===null?[]:[l(i)]),s=[],a=e=>{let r=e.trim(),i=l(r);s.length>=n||i.length===0||o.has(i)||dh(t.exclude,r)||(o.add(i),s.push(r))};for(let t of e.suggestedPrompts)a(t);let u=[];try{u=typeof t.fill=="function"?t.fill(i):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&a(e);/* @__PURE__ */
57
- return Object.freeze(s)}function hh(e){return e.sender?.displayName??Yd.senderVet}function ph(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var gh=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function mh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function bh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,i=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&i===sh&&!n)return;if(i<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let l=e?.exclude,o=n?e=>gh.test(e)||mh(l,e):l;return{...e??{},count:i,...o!==void 0?{exclude:o}:{}}}var yh="pet_not_registered";function vh(e){return e!=null&&e.reasonCode===yh}var xh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function wh(e,r,n){let{runtime:i,userRef:l,scopeEpoch:o}=Lc(),s=t.useCallback((e,t)=>{let r=i.registry.services.authFor(l);return ll(il(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,l,o]),a=t.useMemo(()=>r===void 0?null:ol(r),[r]),[u,c]=t.useState({key:null,status:"idle",error:null,registered:null}),d=t.useRef(0),f=t.useRef(n);f.current=n;let h=e===null||a===null?null:`${String(l)}|${o}|${e}|${a}`,p=t.useCallback(()=>{if(e===null||r===void 0||h===null)return;let t=++d.current;c({key:h,status:"registering",error:null,registered:null}),s(e,r).then(e=>{t===d.current&&(e.ok?(c({key:h,status:"registered",error:null,registered:e.value}),f.current?.()):c({key:h,status:"failed",error:e.error,registered:null}))})},[s,e,h]);t.useEffect(()=>{if(h===null){d.current+=1;return}return p(),()=>{d.current+=1}},[h,p]);let g=t.useCallback(()=>{u.status==="failed"&&p()},[u.status,p]);return t.useMemo(()=>h===null?xh:u.key!==h?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[h,u,g])}var kh=/* @__PURE__ */Object.freeze({});function Ch(e){let[r,n]=t.useState(kh),i=t.useRef(null),l=t.useRef([]);l.current=e.map(e=>e.id),t.useEffect(()=>{if(e.length===0){i.current=null,n(e=>e===kh?e:kh);return}let t=i.current;if(t===null)return;let r=e.find(e=>e.role==="user"&&!t.known.has(e.id));r!==void 0&&(i.current=null,n(e=>({...e,[r.id]:t.images})))},[e]);let o=t.useCallback(e=>{i.current=e.length===0?null:{images:e,known:new Set(l.current)}},[]);return t.useMemo(()=>({byMessage:r,stage:o}),[r,o])}var Sh=/* @__PURE__ */new WeakSet;function jh(){let e=makeEverfurError("internalError",{retryable:true});return Sh.add(e),err(e)}function _h(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Sh.has(t)}var Rh=500;function Th(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,Rh):null}function Ih(e,r,n,i){let l=Th(n),o=l===null?null:i!==void 0?`key:${String(i)}`:`prompt:${l}`,s=t.useRef(e);s.current=e;let a=t.useRef(null),u=t.useRef(null),c=t.useRef(o);c.current=o,t.useEffect(()=>{if(l===null||o===null||r||a.current===o||u.current===o)return;let e=s.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!_h(e)&&c.current===o&&(a.current=o)};Promise.resolve(e(l)).then(t,()=>t(void 0))},[l,o,r,e])}var Ph=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),zh=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Eh=/* @__PURE__ */Object.freeze({...Ph,markRead:true}),Oh=/* @__PURE__ */Object.freeze({...zh,markRead:true});function Ah(e,t){return e?t?Eh:Ph:t?Oh:zh}function Mh(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Hf(()=>r()!==!1)===true}function Fh(e,r){let n=t.useRef({target:e,isVisible:r});n.current={target:e,isVisible:r};let i=t.useRef(e.isStreaming);t.useEffect(()=>{let t=i.current;if(i.current=e.isStreaming,!t||e.isStreaming)return;let{target:r,isVisible:l}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!l()||r.markRead()},[e.isStreaming])}var Dh=3e5;function Lh(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function Bh(e,r,n){let i=t.useRef(r);i.current=r;let l=t.useRef(null),o=t.useRef(null),s=t.useRef(false),a=t.useRef(0),u=t.useRef(0),c=t.useRef(3e4),d=()=>e?.isOffline===void 0?false:Hf(()=>e.isOffline?.()===!0)===true,f=d(),h=t.useRef(()=>{});h.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=i.current,p=pr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:l.current,now:Date.now()});if(p.action==="skip")return;if(p.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(s.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,l.current={conversationId:p.conversationId,at:Date.now()},n===void 0)return;s.current=true;let g=e=>{s.current=false,Lh(e)?(a.current=Math.min(a.current===0?c.current*2:a.current*2,Dh),u.current=Date.now()+a.current):(a.current=0,u.current=0);let t=o.current;t!==null&&h.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},t.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&h.current(e)},[r.isTurnInFlight,f]),t.useEffect(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=Hf(()=>e(()=>{h.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)Hf(e)}},[e]);let p=n?.intervalMs??null,g=n?.isVisibleFallback;t.useEffect(()=>{if(e===void 0||p===null||!Number.isFinite(p)||p<=0)return;c.current=p;let t=setInterval(()=>{Date.now()<u.current||Mh(e,g)&&h.current("poll")},p);return()=>clearInterval(t)},[e,p,g])}var Vh=/^efch_[A-Za-z0-9_-]{43}$/,Hh="efch";function Uh(e){return typeof e=="string"&&Vh.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${Hh}=`))continue;let e=r.slice(Hh.length+1);return Uh(e)?e:null}return null}var Nh=128,$h=/[\u0000-\u001f\u007f]/;function Wh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function qh(e){return typeof e!="string"||e.length===0||e.length>Nh||$h.test(e)||e.includes("://")?null:e}function Gh(e){if(e===null)return null;let t=e.conversation_id,r=qh(e.pet_ref);return typeof t!="string"||!Zr(t)||r===null?null:{conversationId:t,petRef:r}}function Kh(e,t,r){return Uh(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(Gh(Wh(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(_r("internalError",false))):Promise.resolve(ok(null))}function Yh(e,r){let n=r?.runtime??null,i=r?.userRef??null,l=Uh(e)?e:null,o=l===null||i===null?null:`${String(i)}|${l}`,[s,a]=t.useState(null);return t.useEffect(()=>{if(o===null||l===null||i===null||n===null)return;let e=true,t=n.registry.services;return Kh(t.authFor(i),l,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||a({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,l,i]),s!==null&&s.key===o?s.target:void 0}function Qh(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function Xh(e,r,n){let i=Qh(r),l=r?.kind==="chat",o=r?.petRef??null,s=l&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,a=t.useRef({openCheckin:e,target:r,selectPet:n.selectPet});a.current={openCheckin:e,target:r,selectPet:n.selectPet};let u=t.useRef(null),c=t.useRef(null),d=n.petRef;t.useEffect(()=>{if(i===null||u.current===i)return;let{openCheckin:e,target:t,selectPet:r}=a.current;if(s&&o!==null){if(c.current?.key!==i){c.current={key:i,from:d},r(o);return}d!==c.current.from&&(u.current=i);return}l&&!n.ready||(u.current=i,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[i,l,s,o,d,n.ready])}var Zh=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function Jh(e){let t=e?.replace(/\s+/g," ").trim();return t||Zh.untitled}function ep(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function tp(e){let t=ep(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Zh.newReply.replace("{date}",t):t}function rp(e,t){return t?`${Zh.countLabel}${Zh.countSeparator}${e}`:Zh.countLabel}function np(e){return`${e.unreadCount!==null&&e.unreadCount>0?Zh.unreadPrefix:""}${Zh.openConversation} ${Jh(e.title)}`}function ip(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function lp(e,t){let r=ip(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=ip(Jh(t.title)),i=e.indexOf(r);if(i<0)continue;let l=i===0?0:e.charAt(i-1)===" "?1:2;n[l]?.push(t)}return n.flat()}function op(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function sp(e){let[r,n]=t.useState(false),[i,l]=t.useState(""),o=e.listConversations,s=t.useRef(0),[a,u]=t.useState(()=>op(o)),c=a.scope===o?a:op(o);t.useEffect(()=>(s.current+=1,n(false),l(""),u(op(o)),()=>{s.current+=1}),[o]);let d=t.useCallback(async t=>{let r=++s.current,n=t!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let i=await e.listConversations(t?{cursor:t}:void 0);if(r===s.current){if(!i.ok){u(e=>({...e,loading:false,loadingMore:false,error:i.error.displayMessage}));return}u(e=>{let r=t&&e.scope===o?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...i.value.conversations.filter(e=>!n.has(e.id))],cursor:i.value.nextCursor===t?null:i.value.nextCursor}})}},[e.listConversations,o]),f=()=>{n(true),l(""),d()},h=()=>{s.current+=1,n(false)},p=async t=>{let r=++s.current;u(e=>({...e,loading:true,error:null}));let i=await e.resumeConversation(t);r===s.current&&(u(e=>({...e,loading:false,error:i.ok?null:i.error.displayMessage})),i.ok&&n(false))},g=async()=>{let t=s.current,r=await e.loadOlderMessages();t===s.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{e.newConversation(),s.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||i.trim().length>0||d(c.cursor)},y=t.useMemo(()=>lp(c.rows,i),[c.rows,i]),v=i.trim().length>0;return{...c,open:r,show:f,close:h,load:d,resume:p,earlier:g,newConversation:m,loadMore:b,query:i,setQuery:l,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var ap="#111111",up="#FFFFFF",cp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ap,pillColor:up,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ap,pillColor:up,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ap,pillColor:up,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ap,pillColor:up,showsVetAction:false})});function dp(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function fp(e){return Qd(Yd.urgencyGeneralReason,{petName:e?.trim()||Yd.emptyTitlePetFallback})}function hp(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 i=n.urgencyLevel;return i?{messageId:n.id,level:i,reason:pp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:fp(t)}:null}return null}function pp(e){return typeof e=="string"&&e.trim().length>0?e:null}function gp(e){let r=e===null?null:dp(e),[n,i]=t.useState(null),[l,o]=t.useState(false);t.useEffect(()=>o(false),[r]);let s=e!==null&&(l||!(n!==null&&n===r)),a=e===null?null:cp[e.level],u=e!==null&&!s&&e.level!=="general",c=t.useCallback(()=>{r!==null&&i(r),o(false)},[r]),d=t.useCallback(()=>o(true),[]);return t.useMemo(()=>({source:e,tier:a,signature:r,showBanner:s,showCompactIcon:u,showVetAction:s&&a!==null&&a.showsVetAction,dismissLabel:a===null?null:Qd(Yd.dismissBanner,{label:a.label}),dismiss:c,expand:d}),[e,a,r,s,u,c,d])}var mp="everfur.com",bp=2048,yp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function vp(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&yp.test(e)&&t.add(e)}/* @__PURE__ */
58
- return Object.freeze([...t])}function xp(e,t){if(e===mp||e.endsWith(`.${mp}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function wp(e,t){if(typeof e!="string"||e.length===0||e.length>bp||!/^https:\/\//i.test(e))return null;let r=U(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:xp(r.hostname,t)?r.href:null}function kp(e){try{Promise.resolve(r.Linking.openURL(e)).catch(()=>{})}catch{}}var Cp=t.createContext(null);function Sp(){return t.useContext(Cp)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:r,children:n}){let i=e===false?null:Array.isArray(e)?e.join(`\n`):"",l=t.useMemo(()=>{if(i===null)return null;let e=vp(i===""?[]:i.split(`\n`));/* @__PURE__ */
59
- return Object.freeze({hosts:e,open:r!==void 0?e=>{Hf(r,e,"message")}:kp})},[i,r]);return t.createElement(Cp.Provider,{value:l},n)}var jp={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function _p(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function Rp(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o={width:e*.82,height:i,borderRadius:i,backgroundColor:t};/* @__PURE__ */
60
- return l.jsxs(r.View,{style:[_p(e),{gap:e*.22}],...jp,children:[
39
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function tl(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function rl(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,nl)}catch(e){nl(e)}}function nl(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var il=/* @__PURE__ */new WeakMap,ll=/* @__PURE__ */new Map;function ol(e,t){il.set(e,t)}function sl(e,t,r,n){let i=il.get(e);if(i===void 0)return null;let l;if(t.mode==="personalized"&&typeof t.userRef=="string")l=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")l=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${i}|${l}|${r}|${ul(n)}`}function al(e,t){if(e===null)return t();let r=ll.get(e);if(r!==void 0)return r;let n=t().finally(()=>{ll.get(e)===n&&ll.delete(e)});return ll.set(e,n),n}function ul(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ul).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${ul(t)}`).join(",")}}`}var cl=/* @__PURE__ */new WeakMap;function dl(e,t){let r=cl.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,cl.set(e,r)),r.add(t),()=>{r?.delete(t)}}function fl(e){let t=cl.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var hl=/* @__PURE__ */new Map;function pl(e,t){return()=>{let r=hl.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let i=n.finally(()=>{hl.get(e)===i&&hl.delete(e)});return hl.set(e,i),i}}function parseColor(e){let t=gl(e);return t===null?null:kl(t)}function gl(e){if(typeof e=="number")return yl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return ml(t.slice(1));if(t.toLowerCase().startsWith("0x"))return ml(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return bl(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=ml(t);if(e!==null)return e}return/^\d+$/.test(t)?yl(Number.parseInt(t,10)):null}function ml(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:xl(t[0]),g:xl(t[1]),b:xl(t[2]),a:1};if(t.length===6)return{r:vl(t,0),g:vl(t,2),b:vl(t,4),a:1};if(t.length===8){let e=vl(t,0);return{r:vl(t,2),g:vl(t,4),b:vl(t,6),a:e/255}}return null}function bl(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(e=>e.trim());if(n.length<3)return null;let i=wl(Number(n[0])),l=wl(Number(n[1])),o=wl(Number(n[2]));if(i===null||l===null||o===null)return null;let s=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;s=Math.min(1,Math.max(0,e))}return{r:i,g:l,b:o,a:s}}function yl(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}}function vl(e,t){return Number.parseInt(e.slice(t,t+2),16)}function xl(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function wl(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function kl(e){if(e.a>=1)return Cl(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function Cl(e,t,r){return`#${Sl(e)}${Sl(t)}${Sl(r)}`.toUpperCase()}function Sl(e){return e.toString(16).padStart(2,"0")}var jl="#111111",_l="#FFFFFF",Rl="#000000";function readableOn(e){let t=gl(e);if(t===null)return _l;let r=Pl(t),n=Pl({r:17,g:17,b:17}),i=Pl({r:255,g:255,b:255});return El(r,i)>=El(r,n)?_l:jl}function Tl(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(_l,e)>=contrastRatio(Rl,e)?_l:Rl}function Il(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(_l)>=t(Rl)?_l:Rl}function Pl(e){let t=zl(e.r/255),r=zl(e.g/255),n=zl(e.b/255);return.2126*t+.7152*r+.0722*n}function zl(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function El(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=gl(e),n=gl(t);if(r===null||n===null)return 1;let i=n.a>=1?n:{...n},l=r.a>=1?r:Ol(r,i);return El(Pl(l),Pl(i))}function Ol(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function Al(e,t){let r=gl(e),n=gl(t);if(r===null||n===null)return null;let i=r.a>=1?r:Ol(r,{...n});return Cl(i.r,i.g,i.b)}function Ml(e,t){let r=gl(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var Fl=.05;function Dl(e,t,r,n){let i=t[0];if(i===void 0)return r;let l=e=>t.every(t=>contrastRatio(e,t)>=n);if(gl(e)===null)return r;if(l(e))return e;let o=Al(e,i),s=o===null?null:gl(o),a=gl(r);if(s===null||a===null)return r;for(let e=1;e<1/Fl;e+=1){let t=e*Fl,r=(e,r)=>Math.round(e+(r-e)*t),n=Cl(r(s.r,a.r),r(s.g,a.g),r(s.b,a.b));if(l(n))return n}return r}function Ll(e,t,r){let n=e/255,i=t/255,l=r/255,o=Math.max(n,i,l),s=Math.min(n,i,l),a=(o+s)/2;if(o===s)return{h:0,s:0,l:a};let u=o-s,c=u/(1-Math.abs(2*a-1)),d;return o===n?(d=(i-l)/u*60,d<0&&(d=d+360)):o===i?d=((l-n)/u+2)*60:d=((n-i)/u+4)*60,{h:d,s:c,l:a}}function Bl(e){let{h:t,s:r,l:n}=e,i=(1-Math.abs(2*n-1))*r,l=t/60,o=i*(1-Math.abs(l%2-1)),s=n-i/2,a=Math.floor(l)%6,u=[[i,o,0],[o,i,0],[0,i,o],[0,o,i],[o,0,i],[i,0,o]],[c,d,f]=u[a];return{r:Vl(c+s),g:Vl(d+s),b:Vl(f+s)}}function Vl(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var Hl=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),Ul=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Nl=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return Nl[e]??Ul}var $l=4.5,Wl=/* @__PURE__ */Object.freeze({});function ql(e){return Hl.includes(e)}function Gl(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,i]of Object.entries(e)){if(!ql(n)||i===null||typeof i!="object")continue;let e=Ql(i);if(e===null)continue;let l=Kl(n,e);l!==null&&(t[n]=l,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function Kl(e,t){let r=Nl[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function Yl(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Ql(e){let t={},r=parseColor(Yl(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(Yl(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let i=Gl(Yl(e,"border_radius","borderRadius"));i!==null&&(t.borderRadius=i);let l=parseColor(Yl(e,"text_color","textColor"));return l!==null&&(t.textColor=l),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Wl:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Xl(e){let t=gl(e);return t!==null&&t.a>=1}var Zl=3,Jl=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function eo(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function to(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>Al(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=Zl))return null;let i=[...t,...n,...r];return Dl(n[0],i,Il(i),Zl)}function ro(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>Al(e,t)??t)}function no(e,t){let r=Il(e);return e.every(e=>contrastRatio(r,e)>=t)}function io(e,t){let r=t[0];return r===void 0?null:Al(e,r)}function lo(e){let t=Tl(e[0],$l);return e.every(e=>contrastRatio(t,e)>=$l)?t:Il(e)}function oo(e,t,r,n,i){return Jl.has(e)?false:i?true:r!==void 0&&eo(t,r)?false:!(n!==void 0&&r!==void 0&&Xl(r))}function guardSlotContrast(e,t,r){let n=false,i={};for(let l of Hl){let o=e[l];if(o===void 0)continue;let s=o.backgroundColor,a=t?.[l]??[],u=ro(s,a),c={...o},d=false;if(s!==void 0&&u.length>1&&!no(u,$l)){let e=io(s,a);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[l],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Xl(h)&&to(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(s!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<$l))&&(c.textColor=lo(u),d=true);else if(e!==void 0){let t=Dl(e,u,Il(u),$l);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&oo(l,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=Dl(o.borderColor,e,Il(e),Zl);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=to(h,f,u);e!==null&&(c.borderColor=e,d=true)}i[l]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(i):e}var so=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),ao=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var uo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){uo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var co=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),fo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),ho={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},po={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},go={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},mo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},bo={regular:"400",medium:"500",bold:"700"},yo={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},vo=0,xo="System",wo="monospace",ko=["content","heading","control","compact","badge"];function Co(e){let t={};for(let r of ko)t[r]=e;return t}var So=[];function jo(){return{family:xo,mono:wo,fontUrl:null,families:{regular:xo,medium:xo,bold:xo,mono:wo,monoMedium:wo,monoBold:wo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:go,tierSizes:Co(go),lineHeight:mo,weight:bo,letterSpacing:yo,scale:1,maxScale:vo,scaleCaps:co,headingFamily:null,headingWeight:null,fontSources:So,roles:ao,typeScale:1}}var _o={},Ro=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var To={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(Ro.standard),emphasized:cssCubicBezier(Ro.emphasized),exit:cssCubicBezier(Ro.exit)},reducedMotion:false},Io={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},Po=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:Io,space:ho,radius:po,type:jo(),motion:To,slots:_o}),zo={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},Eo=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:zo,space:ho,radius:po,type:jo(),motion:To,slots:_o});function Oo(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Ao(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function Mo(e){return Ao(e).every(t=>contrastRatio(e.brand,t)>=Zl)}function Fo(e){return[e.chatGround,e.surface,e.surfaceCream]}function Do(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...Lo(e,t)]}function Lo(e,t){return[Al(t,e.surface)??e.surface,Al(t,e.surfaceCream)??e.surfaceCream]}function Bo(e){return[e.composerFill,e.chatGround]}var Vo=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Ho(e,t){let r=new Set(Oo(t));return Oo(e).every(e=>r.has(e))}function Uo(e){let t=e.color,r=(e.brightness==="dark"?Eo:Po).color,n=(e.brightness==="dark"?Po:Eo).color,i=Oo(t),l=Il(i)!==Il(Oo(r)),o=Ho(t,r),s=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,a=(e,t,r,n,i,a)=>{let u=t===r&&(e!=="errorRed"||s);return u&&o&&Vo.has(e)?t:Dl(u&&l?n:t,i,Il(i),a)},u=(e,i,l)=>a(`text.${e}`,t.text[e],r.text[e],n.text[e],i,l),c=(e,t,i,l)=>a(e,t,r[e],n[e],i,l),d=e=>l&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=Tl(f,$l),p=c("danger",t.danger,[...i,...Lo(t,t.badgeBgCritical)],$l),g={...t,onPrimary:h,onAccent:Tl(t.accent,$l),onDanger:contrastRatio(h,p)>=$l?h:Tl(p,$l),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,i,$l),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,Fo(t),$l),text:{...t.text,primary:u("primary",i,$l),secondary:u("secondary",i,$l),muted:u("muted",i,$l),metaCool:u("metaCool",i,$l),timestamp:u("timestamp",i,$l),placeholder:u("placeholder",Ao(t),Zl)},danger:p,errorRed:c("errorRed",t.errorRed,Do(t,t.badgeBgCritical),$l),warningStrong:c("warningStrong",t.warningStrong,Do(t,t.badgeBgCaution),$l),composerBorder:c("composerBorder",t.composerBorder,Bo(t),Zl),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,Ao(t),Zl)},m={...g,...Qo(g,r,o)};return{...m,...No(t,m,r)}}function No(e,t,r){let n={},i=(e,t,r)=>Dl(e,t,Il(t),r);if((!Go(e.success,r.success)||!Go(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=i(e.success,Do(t,e.badgeBgPositive),$l)),(!Go(e.cautionAccent,r.cautionAccent)||!Go(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=i(e.cautionAccent,Do(t,e.badgeBgCaution),$l)),$o(e,r)){n.info=i(e.info,Do(t,e.badgeBgInfo),$l);let r=[t.surface,t.chatGround,...Lo(t,e.badgeBgInfo)];n.infoEdge=i(e.infoEdge,r,Zl)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function $o(e,t){return!Go(e.info,t.info)||!Go(e.badgeBgInfo,t.badgeBgInfo)}var Wo=.24,qo=.3;function Go(e,t){return parseColor(e)===parseColor(t)}function Ko(e,t){return Go(e.accent,t.accent)?Go(e.brand,t.brand)?null:e.brand:e.accent}function Yo(e,t,r){let n=Ml(e,r);return(n===null?null:Al(n,t))??t}function Qo(e,t,r){let n=Ko(e,t),i=Ao(e),l=Il(i),o=Il([e.surface])===_l,s=n===null&&r,a;s?a=t.highlight:n===null?a=o?Yo(Po.color.highlight,e.surface,qo):Po.color.highlight:a=Yo(n,e.surface,o?qo:Wo);let u=s?t.onHighlight:Dl(e.text.primary,[a],Il([a]),$l),c=n===null?t.mark:Dl(n,i,l,Zl),d=Mo(e)?e.brand:l,f=(e,t,n)=>r&&Go(e,t)?n:Dl(e,i,d,Zl),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=Zl)?e.primary:Dl(e.primary,h,Il(h),Zl);return{highlight:a,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Xo=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Zo(e,t){let r=(e.brightness==="dark"?Eo:Po).color,n=e.color,i=t.color,l=[],o=(e,t,r,n)=>{l.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},s=(e,t)=>!Xo(e,t);s(n.text.primary,r.text.primary)&&!Xo(i.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,i.text.primary),s(n.brand,r.brand)&&(Xo(i.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,i.brandInk),Xo(i.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,i.primaryEdge),!Xo(i.controlEdge,n.brandBorder)&&!Mo({...i,brand:n.brand})&&o("primary_color","control outline",n.brand,i.controlEdge)),s(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Xo(i.linkInk,n.accent)&&o("accent_color","link text",n.accent,i.linkInk),s(n.danger,r.danger)&&!Xo(i.danger,n.danger)&&o("danger_color","error text",n.danger,i.danger),s(n.success,r.success)&&!Xo(i.success,n.success)&&o("success_color","positive status",n.success,i.success),s(n.warningStrong,r.warningStrong)&&!Xo(i.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,i.warningStrong),s(n.cautionAccent,r.cautionAccent)&&!Xo(i.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,i.cautionAccent),(s(n.info,r.info)||s(n.badgeBgInfo,r.badgeBgInfo))&&(Xo(i.info,n.info)||o("info_color","information text",n.info,i.info),Xo(i.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,i.infoEdge));for(let r of Hl){let n=e.slots[r],i=t.slots[r];n===void 0||i===void 0||n===i||(i.backgroundColor!==void 0&&!Xo(i.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,i.backgroundColor),n.textColor!==void 0&&i.textColor!==void 0&&!Xo(i.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,i.textColor),i.borderColor!==void 0&&!Xo(i.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,i.borderColor))}/* @__PURE__ */
40
+ return Object.freeze(l)}var Jo=/* @__PURE__ */new Set;function es(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(Jo.has(t))return;Jo.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var ts="#23272C",rs=4.5,ns=.6,is=.9,ls=.02,os="#FFFFFF",ss="#111111";function as(e){return contrastRatio(e,ts)>=rs&&Math.max(contrastRatio(e,os),contrastRatio(e,ss))>=rs}function deriveDarkVariant(e){let t=gl(e);if(t===null)return null;let{h:r,s:n,l:i}=Ll(t.r,t.g,t.b),l=Math.min(Math.max(i,ns),is);for(let e=0;;e+=1){let t=l+e*ls;if(t>is)break;let i=Bl({h:r,s:n,l:t}),o=Cl(i.r,i.g,i.b);if(as(o))return o}let o=Bl({h:r,s:n,l:is});return Cl(o.r,o.g,o.b)}var us=7,cs=.05,ds="#000000",fs="#FFFFFF";function hs(e,t,r,n){let i=Al(e,t);if(i===null)return r;if(contrastRatio(i,t)>=n)return i;let l=gl(i),o=gl(r);if(l===null||o===null)return r;for(let e=1;e<1/cs;e+=1){let r=e*cs,i=(e,t)=>Math.round(e+(t-e)*r),s=Cl(i(l.r,o.r),i(l.g,o.g),i(l.b,o.b));if(contrastRatio(s,t)>=n)return s}return r}function ps(e,t){let r=Oo(e),n=r[0],i=gs(n);for(let e of r){let r=gs(e);(t?r>i:r<i)&&(n=e,i=r)}return n}function gs(e){let t=gl(e);return t===null?0:Pl(t)}function ms(e,t){return Al(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=Il(Oo(t))===fs,n=r?fs:ds,i=ps(t,r),l=e=>hs(e,i,n,us),o={...t,brandSoft:ms(t.brandSoft,t.surface),brandSofter:ms(t.brandSofter,t.surface),brandBorder:l(t.brandBorder),borderHairlineGreen:l(t.borderHairlineGreen),brandBorderStrong:l(t.brandBorderStrong),controlEdge:l(t.controlEdge),structureEdge:l(t.structureEdge),brandInk:l(t.brandInk),linkInk:l(t.linkInk),borderRingCream:l(t.borderRingCream),composerBorder:l(t.composerBorder),text:{primary:l(t.text.primary),secondary:l(t.text.secondary),muted:l(t.text.muted),placeholder:l(t.text.placeholder),onBrand:t.text.onBrand,metaCool:l(t.text.metaCool),timestamp:l(t.text.timestamp)},badgeBgPositive:ms(t.badgeBgPositive,t.surface),badgeBgCaution:ms(t.badgeBgCaution,t.surface),badgeBgCritical:ms(t.badgeBgCritical,t.surface),badgeBgNeutral:ms(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:ms(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:ms(t.checkupCardConcernBg,t.surface),info:l(t.info),infoEdge:l(t.infoEdge),badgeBgInfo:ms(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var bs=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),ys=bs.cream,vs=bs.subtle,xs=bs.ring,ws=10;function ks(e,t,r){let n=gl(e),i=gl(t);if(n===null||i===null)return null;let l=(e,t)=>Math.round(e+(t-e)*r);return Cl(l(n.r,i.r),l(n.g,i.g),l(n.b,i.b))}function Cs(e){if(e===null)return{};let t=Il([e]),r=ks(e,t,ys),n=ks(e,t,vs),i=ks(e,t,xs);return r===null||n===null||i===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:i}}function Ss(e){if(e===null)return{};let t=gl(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function js(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let i={};for(let[e,t]of Object.entries(r.type.size))i[e]=Math.max(ws,Math.round(t*n*10)/10);return i}function _s(e,t,r){if(e===null)return t;let n=e/r.space.xs,i=e=>Math.round(e*n),l=r.space;return{xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),xxl:i(l.xxl)}}function Rs(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),i=t.radius;return{tile:n(i.tile),xs:n(i.xs),sm:n(i.sm),md:n(i.md),lg:n(i.lg),xl:n(i.xl),pill:i.pill}}var Ts=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function Is(e,t){let r=gl(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function Ps(e,t){if(e===null)return{};let r=Is(e,t?Ts.success.dark:Ts.success.light),n=Is(e,t?Ts.successCard.dark:Ts.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function zs(e,t){if(e===null)return{};let r=Is(e,t?Ts.warning.dark:Ts.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function Es(e,t){if(e===null)return{};let r=Is(e,t?Ts.info.dark:Ts.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function Os(e,t,r){if(e===null)return t;let n=r.type.lineHeight,i=e/n.normal;if(i===1)return n;let l=e=>Math.round(e*i*100)/100;return{tight:l(n.tight),snug:l(n.snug),normal:l(n.normal),relaxed:l(n.relaxed)}}function As(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Fo(e),header:[e.surface,e.background,e.chatGround],banner:[Al(e.badgeBgInfo,e.surface)??e.surface,Al(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function Ms(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function Fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ds=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),Ls=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),Bs=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function Vs(e){return typeof e=="string"&&Ds.includes(e.trim().toLowerCase())}function Hs(e,t){let r=e[t];return r??void 0}var Us=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Us)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Ns=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],$s=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Ws=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],qs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Gs=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!Fs(e))return null;let t=Vs(e.theme)?Ls[e.theme.trim().toLowerCase()]:{},r=Fs(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let i={},l=Hs(n,"colorScheme"),o=typeof l=="string"?l.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(i.color_scheme=o);let s=o==="dark"?"_dark":"";for(let[e,t]of Ns){let r=Hs(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of $s){let r=Hs(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of qs){let r=Hs(n,e);typeof r=="string"&&r.trim().length>0&&(i[t]=r.trim())}for(let[e,t]of Gs){let r=parsePx(Hs(n,e));r!==void 0&&(i[t]=r)}for(let[e,t]of Ws){let r=Hs(n,e);(typeof r=="number"||typeof r=="string")&&(i[t]=r)}let a=e.fonts;Array.isArray(a)&&a.length>0&&(i.font_sources=a);let u=e.rules;if(Fs(u)){let e={};for(let t of Hl){let r=u[t];Fs(r)&&(e[t]=r)}Object.keys(e).length>0&&(i.slots=e)}return Object.keys(i).length===0?null:/* @__PURE__ */Object.freeze(i)}var Ks="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function Ys(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var Qs=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?Ys(__EVERFUR_BRAND_CDN_ORIGIN__):Ks;var Xs=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Zs=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),Js=Object.keys(Zs),ea="presentation",ta="presentation.";function isPresentationLockName(e){if(e===ea)return true;if(!e.startsWith(ta))return false;let t=e.slice(ta.length);return Object.values(Zs).includes(t)}var ra={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},na=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function ia(e,t){if(t==null)return;let r=ra[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:na.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Js){let n=Zs[e],i=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],l=ia(e,i);l!==void 0&&(r[e]=l)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${ta}${Zs[e]}`;for(let e of t)if(e===ea||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,i=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},l=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,s={};for(let e of Js){let t=i[e],r=isPresentationFieldLocked(e,o)?void 0:l[e];s[e]=r??t??Xs[e]}/* @__PURE__ */
41
+ return Object.freeze(s)}var la=4,oa=/* @__PURE__ */Object.freeze({min:1,max:2}),sa=100,aa=2048,ua=["100","200","300","400","500","600","700","800","900"];function ca(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function da(e){let t=ca(e);if(t===null)return null;let r=String(t);return ua.includes(r)?r:null}function fa(e){let t=ca(e);return t===null?null:Math.min(oa.max,Math.max(oa.min,t))}function ha(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>aa?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function pa(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>sa||/[\u0000-\u001F\u007F]/.test(t)?null:t}function ga(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function ma(e){if(!Fs(e))return null;let t=pa(e.family);if(t===null)return null;let r=ga(e,"src"),n=ga(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=ha(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let i=ha(r);if(i===null)return null;let l={family:t,src:i},o=da(e.weight);o!==null&&(l.weight=o);let s=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(s==="normal"||s==="italic")&&(l.style=s),/* @__PURE__ */Object.freeze(l)}function ba(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=la)break;let e=ma(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var ya=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),va=["content","heading","control","compact","badge"],xa=["sans","heading","mono"],wa=/* @__PURE__ */Object.freeze({min:1,max:3.1});function ka(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function Ca(e,t){return Math.min(t.max,Math.max(t.min,e))}function Sa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ja(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function _a(e){let t=ka(e);return t===null?null:Ca(t,ya.typeScale)}function Ra(e){if(!Sa(e))return null;let t={};for(let r of va){let n=ka(ja(e,r));n!==null&&(t[r]=n<=0?0:Ca(n,wa))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function Ta(e){if(!Sa(e))return null;let t={},r=ka(ja(e,"size","fontSize","font_size"));r!==null&&(t.size=Ca(r,ya.size));let n=fa(ja(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let i=da(ja(e,"weight","fontWeight","font_weight"));i!==null&&(t.weight=i);let l=ja(e,"face");typeof l=="string"&&xa.includes(l.trim())&&(t.face=l.trim());let o=ka(ja(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=Ca(o,ya.letterSpacing));let s=ja(e,"uppercase");return typeof s=="boolean"&&(t.uppercase=s),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function Ia(e){if(!Sa(e))return null;let t={};for(let r of so){let n=Ta(ja(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var Pa=e=>Math.round(e*10)/10,za=e=>Math.round(e*100)/100;function Ea(e,t,r,n){if(t===null&&r===null&&n===null)return e;let i=t===null?null:t/ao.body.size,l=r===null?null:r/ao.body.lineHeight,o={};for(let t of so){let r=e[t],s=ao[t];o[t]=/* @__PURE__ */Object.freeze({...r,...i===null?{}:{size:Pa(s.size*i)},...l===null?{}:{lineHeight:za(s.lineHeight*l)},...n?.[t]??{}})}/* @__PURE__ */
42
+ return Object.freeze(o)}function Oa(e,t){let r=false,n={};for(let i of so){let l=e[i],o=t(l);o===1?n[i]=l:(r=true,n[i]=/* @__PURE__ */Object.freeze({...l,size:Pa(l.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function Aa(e,t,r){return{nano:Pa(e.nano*r),small:Pa(e.small*r),micro:Pa(e.micro*r),tiny:Pa(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:Pa(e.verdict*r)}}var Ma=/* @__PURE__ */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","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),Fa="slots.",Da=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||Da.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
43
+ return new Set(["hide_powered_by",...e?.lockedFields??[]])}function La(e){return e==="hide_powered_by"||Ma.includes(e)||isPresentationLockName(e)?true:e.startsWith(Fa)&&Hl.includes(e.slice(Fa.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=Va(t),n=expandAppearance(Na(t,"appearance")),i=n===null?r:Ba(Va(n),r);return isEmptyBranding(i)?null:/* @__PURE__ */Object.freeze(i)}function Ba(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function Va(e){return{displayName:$a(Na(e,"display_name","displayName")),logoUrl:$a(Na(e,"logo_url","logoUrl")),primaryColor:parseColor(Na(e,"primary_color","primaryColor")),accentColor:parseColor(Na(e,"accent_color","accentColor")),brightness:Qa(Na(e,"brightness","color_scheme","colorScheme")),fontFamily:$a(Na(e,"font_family","fontFamily")),fontUrl:$a(Na(e,"font_url","fontUrl")),fonts:qa(Na(e,"fonts")),fontUrls:qa(Na(e,"font_urls","fontUrls")),placeholder:$a(Na(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ua(Na(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Na(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Na(e,"accent_color_dark","accentColorDark")),surfaceStyle:Ya(Na(e,"surface_style","surfaceStyle"),Ga),radiusScale:Ya(Na(e,"radius_scale","radiusScale"),Ka),logoUrlDark:$a(Na(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Na(e,"slots")),accessibilityMaxFontScale:eu(Na(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:nu(Na(e,"locked_fields","lockedFields")),presentation:parsePresentation(Na(e,"presentation")),schemaVersion:tu(Na(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Na(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Na(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Na(e,"text_color","textColor")),textColorDark:parseColor(Na(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Na(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Na(e,"danger_color_dark","dangerColorDark")),fontSizeBase:Ha(Na(e,"font_size_base","fontSizeBase"),Bs.fontSizeBase),borderRadius:Ha(Na(e,"border_radius","borderRadius"),Bs.borderRadius),spacingUnit:Ha(Na(e,"spacing_unit","spacingUnit"),Bs.spacingUnit),successColor:parseColor(Na(e,"success_color","successColor")),successColorDark:parseColor(Na(e,"success_color_dark","successColorDark")),warningColor:parseColor(Na(e,"warning_color","warningColor")),warningColorDark:parseColor(Na(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Na(e,"info_color","infoColor")),infoColorDark:parseColor(Na(e,"info_color_dark","infoColorDark")),headingFontFamily:$a(Na(e,"heading_font_family","headingFontFamily")),fontWeightBody:da(Na(e,"font_weight_body","fontWeightBody")),fontWeightHeading:da(Na(e,"font_weight_heading","fontWeightHeading")),lineHeight:fa(Na(e,"line_height","lineHeight")),fontSources:ba(Na(e,"font_sources","fontSources")),assistantAvatarUrl:$a(Na(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Ra(Na(e,"text_scale_caps","textScaleCaps")),typeScale:_a(Na(e,"type_scale","typeScale")),typeRoles:Ia(Na(e,"type_roles","typeRoles"))}}function Ha(e,t){let r=Xa(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Ua(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}function Na(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function $a(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Wa=["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 e of Wa){let n=$a(Na(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Ga=["white","cream","subtle"],Ka=["sharp","default","round"];function Ya(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Qa(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Xa(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}var Za=1,Ja=3.1;function eu(e){let t=Xa(e);return t===null?null:t<=0?0:Math.min(Ja,Math.max(Za,t))}function tu(e){if(e==null)return null;let t=Xa(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function ru(e){let t=e.trim();return t.startsWith(Fa)?t:t.startsWith(ta)?ta+t.slice(ta.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function nu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=ru(r);La(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var iu=/* @__PURE__ */new RegExp(`^${Qs}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&iu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Eo:Po:e,n=r.brightness==="dark"?Eo:Po,i=r.brightness==="dark",l=i?t.primaryColorDark??uu(t.primaryColor):t.primaryColor,o=i?t.accentColorDark??uu(t.accentColor):t.accentColor,s=l??r.color.primary,a=o??r.color.accent,u=l!==null&&fu(t,s,n,i),c=u?n.color.primary:s,d=l!==null&&!u?gl(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?hu(n,r.color.text):{},p=(i?t.backgroundColorDark:t.backgroundColor)??null,g=Cs(p),m={...r.color,...g},b=(i?t.textColorDark:t.textColor)??null,y=(e,t)=>(i?t??uu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(i?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...Ss(y(t.dangerColor,t.dangerColorDark)),...Ps(y(t.successColor,t.successColorDark),i),...zs(y(t.warningColor,t.warningColorDark),i),...Es(y(t.infoColor,t.infoColorDark),i),...b!==null?{text:{...h.text??r.color.text,primary:b}}:{},...cu(t.surfaceStyle??null,m),primary:c,accent:a,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:_s(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Rs(t.borderRadius,n):gu(t.radiusScale??null,r.radius,n),type:{...r.type,...au(r.type,t),size:js(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:Os(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:Ea(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var lu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},ou=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function su(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function au(e,t){let r=t.fonts??{},n=t.fontUrls??{},i={...e.families},l={...e.namedFaces},o={...e.fontUrls};for(let e of Wa){let s=lu[e].map(e=>r[e]).find(e=>e!==void 0),a=su(e)?null:t.fontFamily;s!==void 0?(i[e]=s,l[e]=true):a!==null&&(i[e]=a,l[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:s!==void 0&&delete o[e]}for(let e of ou)for(let t of e)l[t]&&e.some(e=>e!==t&&i[e]===i[t])&&(l[t]=false);return{family:i.regular,mono:i.mono,fontUrl:o.regular??null,families:i,namedFaces:l,fontUrls:o}}function uu(e){return e===null?null:deriveDarkVariant(e)}function cu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function du(e,t){return e==null?false:parseColor(e)===parseColor(t)}function fu(e,t,r,n){return du(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&du(e.primaryColor,Po.color.primary)}function hu(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}}var pu={sharp:.5,default:1,round:1.5};function gu(e,t,r){if(e===null)return t;let n=pu[e],i=r.radius,l=e=>Math.round(e*n);return{tile:l(i.tile),xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),pill:i.pill}}var mu="Everfur",bu=.5;function resolveTheme(e){return Ou(yu(e),e)}function themeAdjustments(e){let t=yu(e);return Zo(t,Ou(t,{...e,highContrast:false}))}function yu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=ku(e?.clientOverride??null,lockedFieldsOf(r)),i=e?.colorScheme==="dark"?"dark":"light",l=n?.brightness??r?.brightness??"light",o=Su((l==="auto"?i:l)==="dark"?Eo:Po,e?.typeProfile),s=withServerBranding(o,Cu(r));return withServerBranding(s,Cu(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function vu(e){return e==="placeholder"?"chat_placeholder":ru(e)}var xu={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function wu(e,t){return t.has(vu(e))?true:(xu[e]??[]).some(e=>t.has(e))}function ku(e,t){if(e===null)return null;let r=false,n={...e};for(let i of Object.keys(e))(e[i]??null)!==null&&(wu(i,t)||i==="lockedFields")&&(n[i]=null,r=true);let i=n.slots??null;if(i!==null){let e={},l=false;for(let r of Hl){let n=i[r];n!==void 0&&(t.has(`${Fa}${r}`)?l=true:e[r]=n)}l&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let l=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(l)?null:l}function Cu(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Su(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:fo}})}function ju(e,t){if(t===1)return e;let r={};for(let[n,i]of Object.entries(e))r[n]=Math.round(i*t*10)/10;return r}function _u(e){return e===void 0||!Number.isFinite(e)?1:Math.max(bu,e)}var Ru=["content","heading","control","compact","badge"];function Tu(e,t){let r={};for(let n of Ru){let i=e[n],l=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:co[n];n==="content"||!(t>0)?r[n]=l:r[n]=l===0?t:Math.min(l,t)}return Ru.every(e=>r[e]===co[e])?co:r}function Iu(e,t){return t>0?Math.min(e,t):e}function Pu(e,t,r,n){let i={};for(let l of Ru)i[l]=n?ju(e,Iu(t,r[l])):e;return i}function zu(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function Eu(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,headingFamily:e.headingFamily};let i=e.headingFamily!==null&&r!==void 0&&zu(r,e.headingFamily)===false?null:e.headingFamily,l={...e.families},o={...e.namedFaces};for(let e of Wa)!(l[e]===xo||l[e]===wo)&&r!==void 0&&zu(r,l[e])===false&&(l[e]=su(e)?wo:xo,o[e]=false),n!==null&&su(e)&&l[e]===wo&&(l[e]=n);return{family:l.regular,mono:l.mono,families:l,namedFaces:o,headingFamily:i}}function Ou(e,t){let r=e.meta.displayName.trim().length===0?mu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),i={};for(let t of Wa){let r=e.type.fontUrls[t];r!==void 0&&(i[t]=hardenHttpsUrl(r))}let l=i.regular??null,o=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,s=Number.isFinite(e.type.maxScale)?e.type.maxScale:vo,a=_u(t?.textScale),u=Tu(e.type.scaleCaps,s),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=Oa(e.type.roles,()=>d),h=c?Oa(f,e=>Iu(a,u[e.tier])):f,p=t?.typeProfile==="phone"?Aa(e.type.size,f,d):ju(e.type.size,d),g=Pu(p,a,u,c),m=Uo(e),b={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:m,space:e.space,radius:e.radius,type:{...e.type,...Eu(e.type,t),fontUrl:l,fontUrls:i,size:g.content,tierSizes:g,scale:a,maxScale:s,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,As(m),Ms(m))};return t?.highContrast===true?deriveHighContrast(deepFreeze(b)):deepFreeze(b)}var Au="/widget/v1/entitlements",Mu=304,Fu=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",Lu(t));return n.ok?Bu(n.value):n.error.httpStatus===Mu?Fu:{kind:"failed",error:n.error}}var Du=64;function Lu(e){let t={};return Wu(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Du?{method:"GET",path:Au,headers:t,query:{region:e.region}}:{method:"GET",path:Au,headers:t}}function Bu(e){if(e===null||typeof e!="object"||!Wu(e.revision))return $u();let t=typeof e.region=="string"?e.region:"",r=Wu(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
44
+ return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Uu(e.capabilities),branding:Hu(e),livemode:e.livemode!==false,...Vu(e)})}function Vu(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function Hu(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function Uu(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Nu(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
45
+ return Object.freeze(t)}function Nu(e){return typeof e=="object"&&e!==null&&e.enabled===true}function $u(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function Wu(e){return typeof e=="number"&&Number.isFinite(e)}var qu=30;function createEntitlementPoller(e){let t=e.scheduler??Gu,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??qu),i=e.rng??Math.random,l=()=>n+i()*n,o=false,s=false,a=null,u=null,c=n,d=0,f=()=>{a!==null&&(t.clear(a),a=null)},h=e=>{s||!o||(c=Math.max(n,e),a=t.set(()=>{a=null,m()},c*1e3))},p=null,g=async()=>{if(s)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},i;try{i=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Ku(r)}),!s&&t===d&&(e.onSettled?.(),h(l())),null}if(s||t!==d)return null;switch(i.kind){case"updated":u=i.revision,i.smsProfilePublic!==void 0?e.update(i.decisions,i.branding??null,i.livemode!==false,i.smsProfilePublic):e.update(i.decisions,i.branding??null,i.livemode!==false),h(i.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:i.error.code}),h(l());break;default:h(l())}return e.onSettled?.(),i},m=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||s||(o=true,m())},prime(){return s?Promise.resolve(null):p??m()},stop(){s||(s=true,d++,f())},refresh(){s||!o||(d++,u=null,f(),m())}}}var Gu={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function Ku(e){return e instanceof Error?e.message:"poll failed"}var Yu=20;function Qu(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},i=/* @__PURE__ */new Map,l=/* @__PURE__ */new Set,o=0,s=/* @__PURE__ */new Map,a=(r,i)=>{let o=r??"",s=t.get(o)??n(r);if(!(s.hasUnread===i.hasUnread&&s.unreadCount===i.unreadCount&&s.conversationId===i.conversationId)){t.set(o,i);for(let e of[...l])e();l.size>0&&i.hasUnread!==null&&i.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:i.conversationId,unreadCount:i.unreadCount,hasUnread:i.hasUnread})}},u=(e,t)=>{s.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}a(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){s.delete(e??""),a(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,Yu).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let i=new Set(n.map(e=>e.id)),l=(s.get(e??"")??[]).filter(e=>!i.has(e.id));u(e,[...n,...l].slice(0,Yu))};return{subscribe(e){return l.add(e),()=>{l.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=i.get(r);if(n!==void 0)return n;let l=e.read(t);if(l===null)return Promise.resolve();let s=o,a=l.then(e=>{s!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{i.get(r)===a&&i.delete(r)});return i.set(r,a),a},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=s.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,i.clear(),s.clear(),t.size!==0){t.clear();for(let e of[...l])e()}}}}function Xu(e,t,r){let n=en({...t===null?{}:{petRef:t},limit:Yu},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?on(e.value):err(e.error)):Promise.resolve(err(n.error))}var Zu="everfur.notifications.device";var Ju="everfur.slots.v2",ec="everfur.slots.installId.v2";var tc=3e3,rc=/* @__PURE__ */Object.freeze([Zu,Ju,ec]);function nc(e){let{leaving:t,identity:r,hooks:n,telemetry:i}=e;if(t===null||r===null||n.size===0)return null;let l=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(l))}catch(e){return Promise.reject(e)}}),s=(e,t)=>{try{i.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},a=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&s("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||s("timeout",o.length),r()},tc);a.then(r,r)})}function ic(e){let{leaving:t,identity:r,transport:n,sessionId:i}=e,l=r.currentToken();l.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>l,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:i}}async function lc(e,t){if(rc.length===0)return;let r=await Promise.allSettled(rc.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function oc(){/* @__PURE__ */
46
+ return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function sc(e=oc){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var ac="everfur.branding.v1.";function uc(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function cc(e){let t=3421674724,r=2216829733;for(let n of uc(e)){r=(r^n)>>>0;let e=r*435,i=Math.floor(e/4294967296),l=e>>>0;t=t*435+i+r*256>>>0,r=l}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function dc(e){return`${ac}${cc(e)}`}function fc(e){return e?JSON.stringify(e):null}async function hc(e,t){try{let r=await e.getItem(dc(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function pc(e,t,r){try{r===null?await e.removeItem(dc(t)):await e.setItem(dc(t),r)}catch{}}function gc(e,t){let r;return{restore(r){hc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let i=fc(n);i!==r&&(r=i,pc(e,t,i))}}}function mc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function bc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:mc(),store:null,disposed:false}}function yc(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function vc(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}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function xc(e,t){/* @__PURE__ */
47
+ return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:wc(r,n,t))}catch{}}})}function wc(e,t,r){let n=e.indexOf("."),i=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",l=typeof t?.requestId=="string"?t.requestId:null;return{...Ke(r,i,l),...t}}function kc(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(i,l)=>n.call(e,i,l??Ke(t,r,i.requestId))}:{}}}var Cc=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${tt} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Sc(e,t,r=Je){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+Cc[r])}function jc(e){/* @__PURE__ */
48
+ return Object.freeze({request(){return Promise.resolve(err(yc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var _c=/* @__PURE__ */new WeakSet;function Rc(){let e=/* @__PURE__ */new Map,t={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(e=>e.startsWith(t))}};return _c.add(t),t}var Tc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Pc(e,t)}var Ic=6e4,Pc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new b("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Ze,platform:t?.platform??Je,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Xe(r?.appVersion)}),this.telemetry=r.telemetry?xc(r.telemetry,this.errorContext):ue,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",i=checkPublishableKey(r?.publishableKey),l=r.transport!==void 0,o,s=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(i!==null)o=jc(i);else if(r.transport!==void 0)o=r.transport;else{let e=vc(r,t?.platform);e.ok?(s=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(i=e.failure,o=jc(e.failure))}if(this.configFailure=i,this.publishableKey=i===null?n:"",this.mintScope=`${this.publishableKey}|${s??""}`,ol(this,this.mintScope),this.transport=o,i!==null&&(Sc(i,this.telemetry,t?.platform),this.emit({type:"error",code:yc(i).code,requestId:null,context:Ke(this.errorContext,"runtime",null)})),this.errorPolicy=kc(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??de,this.upload=r.upload??mr,this.uploadTransport=r.uploadTransport??On,this.imageCache=r.imageCache??Tc,this.kv=r.storage??Rc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=i===null?sc():sc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:s},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",zc(e),()=>this.buildChatController(e),Ec),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${zc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=Qu({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Xu(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),i===null){this.brandingCache=gc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=i===null?bc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let a=i===null&&(t?.startEntitlementPolling??!l);this.poller=i===null?this.buildPoller(t?.pollScheduler):null,a&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=pl(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Ic,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||rl(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let i=this.store.getSnapshot().branding??null,l=i!==null&&t!=null&&fc(i)===fc(t)?i:t;this.updateEntitlements({decisions:e,isPending:false,branding:l,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(l??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,i=false){let l=`${this.epoch}|${e}|${t}`,o=this.entries.get(l);if(o)return i||(o.warm?o.warm=false:o.refCount+=1),o.controller;let s=r();return this.entries.set(l,{controller:s,refCount:1,warm:i}),this.destroyers.set(s,n),s}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:kc(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await lc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return nc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>ic({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>al(sl(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(Oc(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&fl(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let i={key:r,result:null,promise:this.runPrepare(t).then(e=>(i.result=e,e))};return this.prepared=i,i.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?Oc("prepare"):r===null?null:yc(r),i=this.identity,[l,o,s]=await Promise.all([n?err(n):i===null?ok(void 0):i.currentToken().then(()=>ok(void 0),e=>(i.reportRejected?.(),err(xe(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),a=l.ok?o.ok&&(s?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:a})}catch{}if(a==="ready")this.emit({type:"ready"});else if(a==="failed"&&!l.ok&&r===null&&!this.disposed){let e=l.error.requestId??null;this.emit({type:"error",code:l.error.code,requestId:e,context:Ke(this.errorContext,"runtime",e)})}/* @__PURE__ */
49
+ return Object.freeze({status:a,durationMs:u,session:l,entitlements:o,...s?{chat:s}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",zc(t),()=>this.buildChatController(t),Ec,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function zc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function Ec(e){e.dispose()}function Oc(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function Ac(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function Mc(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function Fc(e){return e.ok?e:err(Mc(e.error))}function Dc(e){return{send:async(...t)=>Fc(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Lc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),Bc=globalThis,Vc=Bc[Lc]??(Bc[Lc]=t.createContext(null));Vc.displayName??="EverfurContext";function Hc(){let e=t.useContext(Vc);if(e===null)throw new b("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return Hc().handle}var Uc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Nc=globalThis,$c=Nc[Uc]??(Nc[Uc]=t.createContext(Po));$c.displayName??="EverfurThemeContext";function useEverfurTheme(){return t.useContext($c)}var Wc=()=>()=>{},qc=()=>null;function Gc(e,r){return t.useSyncExternalStore(r?.subscribe??Wc,r?.get??qc,r?.get??qc)??e}function EverfurThemeProviderCore(e){let{runtime:r}=Hc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot),l=e.seams.useColorScheme(),o=e.seams.useReducedMotion(),s=e.seams.useTextScale(),a=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,c=e.seams.typeProfile,d=e.seams.platformMonoFamily?.(),f=e.seams.isFontRegistered,h=e.clientTheme?Kc(e.clientTheme):"",p=t.useMemo(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[h]),g=Gc(i.branding??null,r.sdkConfigHost?.branding),m=t.useMemo(()=>resolveTheme({branding:g,clientOverride:p,colorScheme:l,reducedMotion:o,textScale:s,scaleTypeSizes:u,highContrast:a,...c===void 0?{}:{typeProfile:c},...d===void 0?{}:{platformMonoFamily:d},...f===void 0?{}:{isFontRegistered:f}}),[g,p,l,o,s,u,c,a,d,f]);e.seams.useResolvedTheme?.(m);let b=e.seams.isDevelopment;return t.useEffect(()=>{b===void 0||!Yc(b)||es(themeAdjustments({branding:g,clientOverride:p,colorScheme:l}))},[b,g,p,l]),t.createElement($c.Provider,{value:m},e.children)}function Kc(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function Yc(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:r,user:n,activePet:i,theme:l,warmUp:o,children:s,seams:a}=e,u=`${r?.publishableKey??""}|${r?.apiBaseUrl??""}|${r?.contractVersion??""}`,c=t.useRef(null),d=t.useRef(null),f=t.useRef(r?.onEvent);f.current=r?.onEvent;let h=t.useRef(e=>{f.current?.(e)}),[p,g]=t.useReducer(e=>e+1,0),m=t.useRef(null),b=t.useRef(void 0),y=n?.userRef??null;b.current!==y&&(b.current!==void 0&&(m.current=null),b.current=y);let v=m.current!==null?m.current.user:n??null,x=t.useRef(null),w=t.useRef(void 0),k=i??null;w.current!==k&&(w.current!==void 0&&(x.current=null),w.current=k);let C=x.current!==null?x.current.pet:i??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:createEverfurRuntime({config:Qc(a.withDefaults?a.withDefaults(r):r,h.current),user:v,activePet:C,theme:l??null},{platform:a.platform,...a.eventSourceFactory?{eventSourceFactory:a.eventSourceFactory}:{}})});let S=c.current.runtime,j=t.useRef(null);t.useEffect(()=>{let e=c.current?.runtime;e===void 0||!e.isDisposed||j.current!==e&&(j.current=e,g())}),t.useEffect(()=>{let e=d.current;e!==null&&(d.current=null,e.dispose())});let _=v?.userRef??null;t.useLayoutEffect(()=>{S.setUser(v)},[S,_]),t.useLayoutEffect(()=>{S.setActivePet(C)},[S,C]);let R=t.useRef(null);t.useEffect(()=>(R.current===S&&(R.current=null),()=>{R.current=S,Xc(()=>{R.current===S&&(R.current=null,S.dispose())})}),[S]),t.useEffect(()=>{o==="onMount"&&S.prepare(C===null?{}:{petRef:C})},[S,o,_,C]);let T=t.useMemo(()=>({setUser:e=>{m.current={user:e},S.setUser(e),g()},setActivePet:e=>{x.current={pet:e},S.setActivePet(e),g()},open:e=>S.open(e),prepare:e=>S.prepare(e),registerPet:(e,t)=>S.registerPet(e,t),updatePet:(e,t)=>S.updatePet(e,t),deletePet:e=>S.deletePet(e),eraseUserData:()=>S.eraseUserData(),logout:()=>{m.current={user:null};let e=S.logout();return g(),e}}),[S,g]),I=t.useMemo(()=>({runtime:S,handle:T,userRef:_,activePet:C,scopeEpoch:S.scopeEpoch,publishableKey:Zc(r)}),[S,T,_,C,p,u]),P=t.createElement(EverfurThemeProviderCore,{clientTheme:l??null,seams:a.theme,children:s});return t.createElement(Vc.Provider,{value:I},a.wrap?a.wrap(P):P)}function Qc(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Xc(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Zc(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Jc=2;function ed(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Jc)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function td(){let e=d.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:e=>ed(n,e)})}}function rd(){let e=r.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}function nd(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function id(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,t=r.AccessibilityInfo?.isReduceMotionEnabled;if(typeof t=="function"){let i=t.call(r.AccessibilityInfo);i!=null&&typeof i.then=="function"&&i.then(t=>{e&&n(t===true)},()=>{})}let i=r.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",e=>n(e===true));return()=>{e=false,i?.remove?.()}},[]),e}function ld(){let e=r.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(r.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function od(e){let t=r.Dimensions?.addEventListener;if(typeof t!="function")return()=>{};let n=t.call(r.Dimensions,"change",e);return()=>n?.remove?.()}function sd(){return t.useSyncExternalStore(od,ld,ld)}function ad(){try{let e=r.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}function ud(){return ad()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function cd(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,{query:t,event:i}=ud(),l=r.AccessibilityInfo?.[t];if(typeof l!="function")return()=>{};try{let t=l.call(r.AccessibilityInfo);nd(t)&&Promise.resolve(t).then(t=>{e&&n(t===!0)},()=>{})}catch{}let o=r.AccessibilityInfo?.addEventListener,s=typeof o=="function"?o.call(r.AccessibilityInfo,i,e=>n(e===true)):void 0;return()=>{e=false,s?.remove?.()}},[]),e}function dd(){return ad()==="ios"?"Menlo":wo}function fd(){return globalThis.__DEV__!==false}var hd=/* @__PURE__ */new Set;function pd(e){if(!fd()||hd.has(e))return;hd.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{}}function gd(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 i=n.includes(e);return i||pd(e),i}var md=/* @__PURE__ */new Set;function bd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var yd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function vd(e){if(!fd())return;let t=bd(e).filter(e=>!md.has(e));if(t.length===0)return;for(let e of t)md.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>yd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function xd(e){t.useEffect(()=>{try{vd(e)}catch{}},[e])}var wd=/* @__PURE__ */Object.freeze({useColorScheme:rd,useReducedMotion:id,useTextScale:sd,useHighContrast:cd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:dd,isFontRegistered:gd,useResolvedTheme:xd,isDevelopment:fd});function kd(e){return t.createElement(n.SafeAreaProvider,null,e)}var Cd=/* @__PURE__ */Object.freeze({platform:"react-native",...r.Platform.OS==="web"?{}:{eventSourceFactory:td()},wrap:kd,theme:wd});function EverfurProvider(e){return t.createElement(EverfurProviderCore,{...e,seams:Cd})}function useCapability(e){let{runtime:r}=Hc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return t.useMemo(()=>decideCapability(e,i.decisions,{isPending:i.isPending}),[e,i])}function Sd(e){let{runtime:r}=Hc(),n=r.entitlements,i=t.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),l=t.useCallback(()=>{if(n===void 0)return false;let t=n.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[n,e]);return t.useSyncExternalStore(i,l,l)}var jd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[jd[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[jd[t]]};let i=face(e,t);return i.fontWeight===void 0||n===null?i:{fontFamily:i.fontFamily,fontWeight:n}}function _d(e){return e<=450?"regular":e<=650?"medium":"bold"}var Rd={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Td.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Td.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=Id(e,t);return r.set(t,i),i}var Td=/* @__PURE__ */new WeakMap;function Id(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,i=_d(Number(n)),l=r.face==="mono"?face(e,Rd[i]):r.face==="heading"?headingFace(e,i):face(e,i),o=r.face==="heading"?e.type.headingWeight??n:n,s=l.fontWeight===void 0?l:{fontFamily:l.fontFamily,fontWeight:o},a=r.size,u={...s,fontSize:a,lineHeight:Math.round(a*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(a*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Pd(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:n,...i}){let l=useEverfurTheme(),o=n===void 0?void 0:l.type.roles[n],s=Pd(l.type,e??o?.tier??"content"),a=n===void 0?i:{...i,style:[{...textRole(l,n),color:l.color.text.primary,flexShrink:1},i.style]};return t.createElement(r.Text,s===void 0?a:{maxFontSizeMultiplier:s,...a})}var zd=t.forwardRef(function(e,n){return t.createElement(r.TextInput,{...e,...n===null?{}:{ref:n}})});var Ed=class extends t.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:r,resetKey:n}){return t.createElement(Ed,{fallback:r,resetKey:n,children:t.createElement(RenderHost,{render:e})})}var Od=48;function Ad(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:r,children:n,renderDisabled:i,renderPending:o,style:s}=e,a=useCapability(r),u=t.useMemo(()=>Ad(a),[a]);switch(u){case"enabled":return n;case"pending":return o?/* @__PURE__ */l.jsx(HostRender,{render:o,fallback:/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s})}):/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s});case"disabled":return i?/* @__PURE__ */l.jsx(HostRender,{render:()=>i(a),fallback:/* @__PURE__ */l.jsx(OffState,{decision:a,style:s}),resetKey:a}):/* @__PURE__ */l.jsx(OffState,{decision:a,style:s});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Md(i),[i]);/* @__PURE__ */
50
+ return l.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */l.jsx(r.View,{style:o.skeletonBar})})}function OffState({decision:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Md(i),[i]),s=e.disabled?.reason??"";/* @__PURE__ */
51
+ return l.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityRole:"text",accessibilityLabel:s,children:s.length>0?/* @__PURE__ */l.jsx(Text,{style:o.offstateText,children:s}):null})}function Md(e){let{color:t,space:n,radius:i,type:l}=e;return r.StyleSheet.create({offstate:{minHeight:Od,justifyContent:"center",paddingHorizontal:n.lg,paddingVertical:n.md,backgroundColor:t.surfaceCream,borderRadius:i.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:n.md,borderRadius:i.xs,backgroundColor:t.brandSofter}})}var Fd=t.createContext(null);function TelevetHostOutlet(){let e=t.useContext(Fd);return e===null?null:/* @__PURE__ */l.jsx(e,{})}var Dd=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function Ld(){let e=globalThis,t=e[Dd];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[Dd]=r,r}function Bd(e){let t=Ld();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function Vd(e){let t=Ld().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function Hd(e){let t=Ld();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function Ud(){return Ld().snapshot}function Nd(){return Ld().hosts.length>0}function $d(e){if(!Nd())return false;let t=/* @__PURE__ */Object.freeze({...e});return Bd({request:t,serial:Ld().snapshot.serial+1}),true}function Wd(){Ld().snapshot.request!==null&&Bd({request:null})}function qd(){let e=Ld(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Bd({activeHost:e.hosts[0]??null}),t}function Gd(e){let t=Ld();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;Bd(r===null?{activeHost:r,request:null}:{activeHost:r})}function Kd(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}}function Yd(e){let[r,n]=t.useState(null);t.useEffect(()=>{let e=qd();return n(e),()=>{Gd(e)}},[]);let i=t.useSyncExternalStore(Hd,Ud,Ud),l=r!==null&&i.activeHost===r?i.request:null,[o,s]=t.useState(null),a=l!==null&&o===null;return t.useEffect(()=>{if(!a)return;let t=true;return e().then(e=>{t&&s(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),Wd())}),()=>{t=false}},[a,e]),l===null||o===null?null:{module:o,request:l,serial:i.serial,dismiss:Wd}}var Qd=Kd(()=>Promise.resolve(f));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let i=Yd(Qd);if(i===null)return null;let{EverfurTelevetModal:o}=i.module;/* @__PURE__ */
52
+ return l.jsx(o,{request:i.request,onClose:i.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},i.serial)}var Xd=640,Zd=600,Jd=/* @__PURE__ */Object.freeze({width:0,height:0}),ef="useWindowDimensions"in c&&typeof c.useWindowDimensions=="function"?c.useWindowDimensions:()=>Jd,tf=/* @__PURE__ */Object.freeze({width:"100%",maxWidth:Xd,alignSelf:"center"});/* @__PURE__ */Object.freeze({...tf,flex:1});var rf=/* @__PURE__ */Object.freeze({...tf,flexGrow:1,flexShrink:1});function nf(){return ef().width>=Zd}function lf(e="flow"){let{width:t}=ef();if(t<Zd)return null;if(e==="flow")return tf;let r=Math.max(0,Math.round((t-Xd)/2));return{left:r,right:r}}function of(e,t){return t===null?e:[e,t]}var sf=/* @__PURE__ */Symbol.for("@everfur/sdk#InSdkColumn@v1"),af=globalThis,uf=af[sf]??(af[sf]=t.createContext(false));uf.displayName??="EverfurInSdkColumn";function SdkTabletColumn({children:e,style:n,testID:i}){let o=nf(),s=t.useContext(uf);return!o||s?e:/* @__PURE__ */l.jsx(r.View,{style:n===void 0?rf:[rf,n],testID:i??"everfur-tablet-column",children:/* @__PURE__ */l.jsx(uf.Provider,{value:true,children:e})})}var cf="Go to the nearest emergency vet now.";var df=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",sourcesHeading:"Sources",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:cf,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",capReached:"You've used your {cap} free messages this month.",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 ff(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function hf(e){return e?.trim()||df.emptyTitlePetFallback}function pf(e,t){return ff(e,{petName:hf(t)})}var gf="tel:+18884264435";var mf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function bf(e){let t=mf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var yf=6;function vf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function xf(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let i of e){if(n.length>=r)break;if(i===null||typeof i!="object"||Array.isArray(i))continue;let e=t(i);e!==null&&n.push(e)}/* @__PURE__ */
53
+ return Object.freeze(n)}function wf(e){let t=mf(e.title,80),r=mf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function kf(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=bf(e);t!==null&&r.length<yf&&r.push(t)}let n=xf(t.doses,e=>{let t=mf(e.label,60),r=mf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:vf(e.minLb??e.min_lb),maxLb:vf(e.maxLb??e.max_lb)})},yf),i=xf(t.details,wf,yf),l=t.fit,o=l!==null&&typeof l=="object"&&!Array.isArray(l)?wf(l):null,s=o!==null&&l.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,a=/* @__PURE__ */Object.freeze({kicker:mf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:i,fine:mf(t.fine,300),fit:s});return a.kicker===null&&r.length===0&&n.length===0&&i.length===0&&a.fine===null&&s===null?void 0:a}var Cf=128;var Sf=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),jf=/* @__PURE__ */new Set(["y","c","g","r"]),_f=/* @__PURE__ */new Set(["done","now","next"]),Rf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Tf=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,If=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,Pf=e=>typeof e=="string"&&Sf.has(e)?e:null;function zf(e){let t=Tf(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var Ef=e=>typeof e=="number"&&Number.isInteger(e)?String(e):Tf(e,Cf);function Of(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Af(e){/* @__PURE__ */
54
+ return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function Mf(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let i of e){if(n.length>=r)break;let e=t(i);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var Ff=(e,t=12,r=300)=>Mf(e,e=>Tf(e,r),t);function Df(e){let t=Rf(e),r=Tf(t?.kicker,120),n=Tf(t?.title,300);if(t===null||r===null||n===null)return null;let i=Rf(t.risk),l=Rf(t.odds),o=Rf(t.quote),s=Rf(t.jump);return Af({kicker:r,title:n,sources:Mf(t.sources,e=>{let t=Tf(Rf(e)?.label,60);return t===null?null:Af({label:t,kind:If(Rf(e)?.kind)})},6),risk:Tf(i?.lead,300)===null?null:Af({lead:Tf(i?.lead,300),body:Tf(i?.body),kind:If(i?.kind)}),odds:Tf(l?.label,120)===null||Tf(l?.from,20)===null||Tf(l?.to,20)===null?null:Af({label:Tf(l?.label,120),tag:Tf(l?.tag,40),from:Tf(l?.from,20),to:Tf(l?.to,20),toLabel:Tf(l?.toLabel,120)}),quote:Tf(o?.text)===null?null:Af({kicker:Tf(o?.kicker,120),tag:Tf(o?.tag,40),text:Tf(o?.text)}),jump:Tf(s?.title,300)===null||Tf(s?.go,60)===null?null:Af({title:Tf(s?.title,300),go:Tf(s?.go,60)}),report:Lf(t.report)})}function Lf(e){let t=Rf(e),r=Tf(t?.label,120),n=Tf(t?.text,1200);return r===null||n===null?null:Af({label:r,text:n,actions:Ff(t?.actions,5,300)})}function Bf(e){let t=Rf(e),r=Tf(t?.title,300),n=Mf(t?.steps,e=>{let t=Rf(e),r=Tf(t?.title,300),n=t?.tone;return r===null?null:Af({title:r,body:Tf(t?.body),source:Tf(t?.source,200),tone:typeof n=="string"&&jf.has(n)?n:null,icon:Pf(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:Af({title:r,label:Tf(t?.label,60),steps:n})}function Vf(e){let t=Rf(e),r=Tf(t?.title,300);if(t===null||r===null)return null;let n=Rf(t.rating),i=Rf(t.reviews),l=Rf(t.why),o=Rf(l?.score),s=Rf(t.dose),a=Rf(t.ingredients),u=Mf(i?.items,e=>{let t=Rf(e),r=t?.stars,n=Tf(t?.text),i=Tf(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||i===null?null:Af({stars:Math.round(r),text:n,by:i})},5),c=Mf(l?.rows,e=>{let t=Rf(e),r=Tf(t?.chip,40),n=Tf(t?.title,300);return r===null||n===null?null:Af({chip:r,kind:If(t?.kind),title:n,body:Tf(t?.body)})}),d=Mf(s?.stats,e=>{let t=Rf(e),r=Tf(t?.value,40),n=Tf(t?.label,120),i=t?.kind;return r===null||n===null?null:Af({value:r,label:n,kind:i==="weight"||i==="dose"||i==="days"?i:null})},6),f=Ff(a?.items,12,80);return Af({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:Ef(t.productId),partnerSku:Tf(t.partnerSku,200),rating:Tf(n?.value,20)===null?null:Af({value:Tf(n?.value,20),label:Tf(n?.label,120)}),line:Tf(t.line),reviews:Tf(i?.label,200)===null||u===null?null:Af({label:Tf(i?.label,200),items:u}),checkoutLine:Tf(t.checkoutLine,300),why:Tf(l?.title,200)===null||c===null?null:Af({title:Tf(l?.title,200),rows:c,score:Tf(o?.text,200)===null||Tf(o?.value,20)===null?null:Af({text:Tf(o?.text,200),value:Tf(o?.value,20)})}),dose:Tf(s?.title,200)===null||d===null?null:Af({title:Tf(s?.title,200),stats:d,note:Tf(s?.note)}),doseLabel:Tf(t.doseLabel,120),ingredients:f===null?null:Af({label:Tf(a?.label,200),items:f}),proof:Tf(t.proof,300),trust:Mf(t.trust,e=>{let t=Rf(e),r=Pf(t?.icon),n=Tf(t?.label,120);return r===null||n===null?null:Af({icon:r,label:n})},6),more:Tf(t.more,120),fine:Tf(t.fine),checkin:Tf(t.checkin,200),detail:kf(t.detail)??null})}function Hf(e){let t=Rf(e),r=Tf(t?.title,200),n=Mf(t?.items,e=>{let t=Rf(e),r=Tf(t?.title,300),n=Tf(t?.body);return r===null||n===null?null:Af({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:Af({title:r,items:n})}function Uf(e){let t=Rf(e),r=Tf(t?.title,200),n=Ff(t?.questions,12,300),i=Tf(t?.add,80),l=Tf(t?.added,80);return r===null||n===null||i===null||l===null?null:Af({title:r,questions:n,add:i,added:l})}function Nf(e){let t=Rf(e),r=Tf(t?.title,200),n=Mf(t?.items,e=>{let t=Rf(e),r=Tf(t?.key,Cf),n=Tf(t?.title,300),i=Tf(t?.action,80),l=Ef(t?.productId),o=Tf(t?.added,80)??(l!==null?i:null);return r===null||n===null||i===null||o===null?null:Af({key:r,productId:l,title:n,body:Tf(t?.body),price:Tf(t?.price,40),was:Tf(t?.was,40),tag:Tf(t?.tag,40),imageUrl:zf(t?.imageUrl),icon:Pf(t?.icon),kind:If(t?.kind),action:i,added:o,owned:t?.owned===true?true:null,detail:kf(t?.detail)??null})},6);return r===null||n===null?null:Af({title:r,items:n})}function $f(e){let t=Rf(e),r=Tf(t?.kicker,120),n=Tf(t?.title,120);return t===null||r===null||n===null?null:Af({kicker:r,title:n,icon:Pf(t.icon),track:Mf(t.track,e=>{let t=Rf(e),r=Tf(t?.title,120),n=t?.state;return r===null?null:Af({title:r,detail:Tf(t?.detail,120),state:typeof n=="string"&&_f.has(n)?n:null,tag:Tf(t?.tag,40)})},6),heading:Tf(t.heading,200),rows:Mf(t.rows,e=>{let t=Rf(e),r=Pf(t?.icon),n=Tf(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return Af({icon:r,label:n,text:"",fromVet:true});let i=Tf(t?.text,300);return i===null?null:Af({icon:r,label:n,text:i})},6),note:Tf(t.note,300),action:Tf(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=Rf(e),r=Tf(t?.title,300),n=Vf(t?.pick);if(t===null||r===null||n===null)return null;let i=Rf(t.byline);return Af({eyebrow:Tf(t.eyebrow,120),title:r,subtitle:Tf(t.subtitle,300),subtitleNoRecords:Tf(t.subtitleNoRecords,300),headImageUrl:zf(t.headImageUrl),byline:Tf(i?.name,120)===null?null:Af({name:Tf(i?.name,120),role:Tf(i?.role,120),imageUrl:zf(i?.imageUrl),shortName:Tf(i?.shortName,60)}),focus:Df(t.focus),routine:Bf(t.routine),pick:n,signs:Hf(t.signs),checkup:Uf(t.checkup),extras:Nf(t.extras),wait:$f(t.wait),fine:Tf(t.fine),checkoutRows:Mf(t.checkoutRows,e=>{let t=Rf(e),r=Pf(t?.icon),n=Tf(t?.label,60),i=Tf(t?.value,200);return r===null||n===null||i===null?null:Af({icon:r,label:n,value:i})},6)})}function healthPlanPageFromWire(e,t){let r=Rf(e);if(r===null||!("page"in r))return null;let n=Rf(r.pet),i=n?.sex;/* @__PURE__ */
55
+ return Object.freeze({petRef:Tf(r.pet_ref,Cf)??t,pet:/* @__PURE__ */Object.freeze({name:Tf(n?.name,120),species:Tf(n?.species,60),sex:i==="female"||i==="male"?i:null,breed:Tf(n?.breed,120),weightKg:Of(n?.weight_kg),weightLb:Of(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function Wf(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function qf(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function Gf(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var Kf=e=>typeof e=="string"&&e.length>0&&e.length<=Cf;function Yf(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function Qf(e,t,r){if(!Kf(t))return err(Wf("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${Yf(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let i=healthPlanPageFromWire(n.value,t);return i===null?err(qf("healthPlan.page.read")):ok(i)}var Xf=/* @__PURE__ */new WeakMap;function Zf(e){let t=Xf.get(e);if(t!==void 0)return t;let r=Jf(e);return Xf.set(e,r),r}function Jf(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(Gf("getPage")));let{services:n}=e.registry,i=Dc(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return Qf(i,t,r)}}}function eh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function th(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function rh(e,...t){if(typeof e=="function")try{let r=e(...t);return th(r)&&Promise.resolve(r).then(void 0,eh),r}catch(e){eh(e);return}}var nh=/* @__PURE__ */new WeakMap;function ih(e){if(typeof e!="function")return;let t=nh.get(e);if(t!==void 0)return t;let r=(...t)=>{rh(e,...t)};return nh.set(e,r),r}function lh(e,...t){let r;try{r=e(...t)}catch(e){return eh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var oh=6e4;function sh({lifecycle:e,refreshKey:r,readyAt:n,revalidate:i,refresh:l,now:o=Date.now}){let s=t.useRef({readyAt:n,revalidate:i,refresh:l??i,now:o});s.current={readyAt:n,revalidate:i,refresh:l??i,now:o},t.useEffect(()=>{if(e==null)return;let t=rh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=s.current;e!==null&&r()-e>=oh&&t()}));return()=>{typeof t=="function"&&rh(t)}},[e]);let a=t.useRef(r);t.useEffect(()=>{Object.is(a.current,r)||(a.current=r,s.current.refresh())},[r])}var ah=oh,uh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function ch(){let e=globalThis,t=e[uh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[uh]=r,r}function dh(e,t,r,n,i){let l=ch(),o=l.get(t);o===void 0&&(o=/* @__PURE__ */new Map,l.set(t,o));let s=o,a=`${r}\0${n}`,u=s.get(a);if(!i&&u!==void 0&&(u.at===null||Date.now()-u.at<ah))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(s.get(a)===c&&(e.ok||Ac(e.error)?c.at=Date.now():s.delete(a)),e))};return s.set(a,c),c.promise}function useHealthPlanPage(e){let{userRef:r,runtime:n}=Hc(),i=t.useMemo(()=>Zf(n),[n]),l=e.repository,o=l??i,s=t.useCallback((e,t)=>l!==void 0||r==null?o.getPage(e):dh(i,n,r,e,t),[l,o,i,n,r]),{petRef:a}=e,u=e.enabled!==false&&r!=null&&a!==null,[c,d]=t.useState({phase:"idle",petRef:null,page:null,error:null}),f=t.useRef(0),h=t.useRef(0),p=t.useCallback(async e=>{let t=++f.current;if(!u||a===null){d(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}d(e=>({phase:"loading",petRef:a,page:e.petRef===a?e.page:null,error:null}));let r=await s(a,e);t===f.current&&(r.ok?d({phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}):Ac(r.error)?d({phase:"ready",petRef:a,page:null,error:null,missing:true,readyAt:Date.now()}):d({phase:"failed",petRef:a,page:null,error:r.error}))},[u,a,s]),g=t.useCallback(()=>p(true),[p]),m=c.phase==="ready"&&c.petRef===a,b=t.useCallback(async()=>{if(!u||a===null||!m)return;let e=f.current,t=++h.current,r=await s(a,true);e!==f.current||t!==h.current||!r.ok||d(e=>e.phase==="ready"&&e.petRef===a?{phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}:e)},[u,a,m,s]);sh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:m?c.readyAt??null:null,revalidate:()=>{b()},refresh:()=>{m?b():g()}}),t.useEffect(()=>(p(false),()=>{f.current+=1}),[p]);let y=u&&c.petRef!==a;return t.useMemo(()=>({phase:y?"loading":c.phase,page:y?null:c.page,error:y?null:c.error,missing:!y&&c.missing===true,refresh:g}),[y,c,g])}var fh=/* @__PURE__ */Object.freeze({branding:null}),hh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>fh});function ph(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function gh(e){let{runtime:r}=Hc(),n=r?.entitlements??hh,i=t.useCallback(()=>n.getSnapshot()?.branding??null,[n]),l=Gc(t.useSyncExternalStore(n.subscribe,i,i),r?.sdkConfigHost?.branding),o=ph(e);return t.useMemo(()=>{let t=l?.lockedFields??null;return{presentation:resolvePresentation({server:l?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[l,o])}function mh(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function bh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function yh(e){let t=Ee(e);return t===null?null:{reached:df.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function vh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function xh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=vh(r),n=t==="web",i=yh(r);return{tone:"error",title:i!==null?i.reached:e?df.turnUnreachableTitle:n?df.turnFailedTitleWeb:df.turnFailedTitle,body:r.displayMessage,actionLabel:e?df.turnStartNewChat:n?df.retry:df.turnRetry,action:e?"startNew":"retry",...i!==null&&i.guidance!==null?{guidance:i.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:df.turnStoppedTitle,body:df.turnStoppedBody,actionLabel:df.turnRetry,action:"retry"}:null}function wh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var kh=3,Ch=/* @__PURE__ */Object.freeze([]);function Sh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Ch;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),i=e.replace(/\s+/g," ").toLowerCase();if(!(i.length===0||r.has(i))&&(r.add(i),n.push(e),n.length===kh))break}/* @__PURE__ */
56
+ return Object.freeze(n)}var jh=5;function _h(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Rh(e,t){if(t===void 0)return Sh(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return Ch;let n=Math.max(1,Math.min(jh,Math.floor(t.count??kh))),i=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){i=r.text;break}}let l=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(i===null?[]:[l(i)]),s=[],a=e=>{let r=e.trim(),i=l(r);s.length>=n||i.length===0||o.has(i)||_h(t.exclude,r)||(o.add(i),s.push(r))};for(let t of e.suggestedPrompts)a(t);let u=[];try{u=typeof t.fill=="function"?t.fill(i):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&a(e);/* @__PURE__ */
57
+ return Object.freeze(s)}function Th(e){return e.sender?.displayName??df.senderVet}function Ih(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Ph=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function zh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Eh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,i=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&i===kh&&!n)return;if(i<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let l=e?.exclude,o=n?e=>Ph.test(e)||zh(l,e):l;return{...e??{},count:i,...o!==void 0?{exclude:o}:{}}}var Oh="pet_not_registered";function Ah(e){return e!=null&&e.reasonCode===Oh}var Mh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function Fh(e,r,n){let{runtime:i,userRef:l,scopeEpoch:o}=Hc(),s=t.useCallback((e,t)=>{let r=i.registry.services.authFor(l);return al(sl(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,l,o]),a=t.useMemo(()=>r===void 0?null:ul(r),[r]),[u,c]=t.useState({key:null,status:"idle",error:null,registered:null}),d=t.useRef(0),f=t.useRef(n);f.current=n;let h=e===null||a===null?null:`${String(l)}|${o}|${e}|${a}`,p=t.useCallback(()=>{if(e===null||r===void 0||h===null)return;let t=++d.current;c({key:h,status:"registering",error:null,registered:null}),s(e,r).then(e=>{t===d.current&&(e.ok?(c({key:h,status:"registered",error:null,registered:e.value}),f.current?.()):c({key:h,status:"failed",error:e.error,registered:null}))})},[s,e,h]);t.useEffect(()=>{if(h===null){d.current+=1;return}return p(),()=>{d.current+=1}},[h,p]);let g=t.useCallback(()=>{u.status==="failed"&&p()},[u.status,p]);return t.useMemo(()=>h===null?Mh:u.key!==h?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[h,u,g])}var Dh=/* @__PURE__ */Object.freeze({});function Lh(e){let[r,n]=t.useState(Dh),i=t.useRef(null),l=t.useRef([]);l.current=e.map(e=>e.id),t.useEffect(()=>{if(e.length===0){i.current=null,n(e=>e===Dh?e:Dh);return}let t=i.current;if(t===null)return;let r=e.find(e=>e.role==="user"&&!t.known.has(e.id));r!==void 0&&(i.current=null,n(e=>({...e,[r.id]:t.images})))},[e]);let o=t.useCallback(e=>{i.current=e.length===0?null:{images:e,known:new Set(l.current)}},[]);return t.useMemo(()=>({byMessage:r,stage:o}),[r,o])}var Bh=/* @__PURE__ */new WeakSet;function Vh(){let e=makeEverfurError("internalError",{retryable:true});return Bh.add(e),err(e)}function Hh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Bh.has(t)}var Uh=500;function Nh(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,Uh):null}function $h(e,r,n,i){let l=Nh(n),o=l===null?null:i!==void 0?`key:${String(i)}`:`prompt:${l}`,s=t.useRef(e);s.current=e;let a=t.useRef(null),u=t.useRef(null),c=t.useRef(o);c.current=o,t.useEffect(()=>{if(l===null||o===null||r||a.current===o||u.current===o)return;let e=s.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!Hh(e)&&c.current===o&&(a.current=o)};Promise.resolve(e(l)).then(t,()=>t(void 0))},[l,o,r,e])}var Wh=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),qh=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Gh=/* @__PURE__ */Object.freeze({...Wh,markRead:true}),Kh=/* @__PURE__ */Object.freeze({...qh,markRead:true});function Yh(e,t){return e?t?Gh:Wh:t?Kh:qh}function Qh(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:rh(()=>r()!==!1)===true}function Xh(e,r){let n=t.useRef({target:e,isVisible:r});n.current={target:e,isVisible:r};let i=t.useRef(e.isStreaming);t.useEffect(()=>{let t=i.current;if(i.current=e.isStreaming,!t||e.isStreaming)return;let{target:r,isVisible:l}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!l()||r.markRead()},[e.isStreaming])}var Zh=3e5;function Jh(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function ep(e,r,n){let i=t.useRef(r);i.current=r;let l=t.useRef(null),o=t.useRef(null),s=t.useRef(false),a=t.useRef(0),u=t.useRef(0),c=t.useRef(3e4),d=()=>e?.isOffline===void 0?false:rh(()=>e.isOffline?.()===!0)===true,f=d(),h=t.useRef(()=>{});h.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=i.current,p=gr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:l.current,now:Date.now()});if(p.action==="skip")return;if(p.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(s.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,l.current={conversationId:p.conversationId,at:Date.now()},n===void 0)return;s.current=true;let g=e=>{s.current=false,Jh(e)?(a.current=Math.min(a.current===0?c.current*2:a.current*2,Zh),u.current=Date.now()+a.current):(a.current=0,u.current=0);let t=o.current;t!==null&&h.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},t.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&h.current(e)},[r.isTurnInFlight,f]),t.useEffect(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=rh(()=>e(()=>{h.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)rh(e)}},[e]);let p=n?.intervalMs??null,g=n?.isVisibleFallback;t.useEffect(()=>{if(e===void 0||p===null||!Number.isFinite(p)||p<=0)return;c.current=p;let t=setInterval(()=>{Date.now()<u.current||Qh(e,g)&&h.current("poll")},p);return()=>clearInterval(t)},[e,p,g])}var tp=/^efch_[A-Za-z0-9_-]{43}$/,rp="efch";function np(e){return typeof e=="string"&&tp.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${rp}=`))continue;let e=r.slice(rp.length+1);return np(e)?e:null}return null}var ip=128,lp=/[\u0000-\u001f\u007f]/;function op(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function sp(e){return typeof e!="string"||e.length===0||e.length>ip||lp.test(e)||e.includes("://")?null:e}function ap(e){if(e===null)return null;let t=e.conversation_id,r=sp(e.pet_ref);return typeof t!="string"||!tn(t)||r===null?null:{conversationId:t,petRef:r}}function up(e,t,r){return np(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(ap(op(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(Rr("internalError",false))):Promise.resolve(ok(null))}function cp(e,r){let n=r?.runtime??null,i=r?.userRef??null,l=np(e)?e:null,o=l===null||i===null?null:`${String(i)}|${l}`,[s,a]=t.useState(null);return t.useEffect(()=>{if(o===null||l===null||i===null||n===null)return;let e=true,t=n.registry.services;return up(t.authFor(i),l,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||a({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,l,i]),s!==null&&s.key===o?s.target:void 0}function dp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function fp(e,r,n){let i=dp(r),l=r?.kind==="chat",o=r?.petRef??null,s=l&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,a=t.useRef({openCheckin:e,target:r,selectPet:n.selectPet});a.current={openCheckin:e,target:r,selectPet:n.selectPet};let u=t.useRef(null),c=t.useRef(null),d=n.petRef;t.useEffect(()=>{if(i===null||u.current===i)return;let{openCheckin:e,target:t,selectPet:r}=a.current;if(s&&o!==null){if(c.current?.key!==i){c.current={key:i,from:d},r(o);return}d!==c.current.from&&(u.current=i);return}l&&!n.ready||(u.current=i,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[i,l,s,o,d,n.ready])}var hp=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function pp(e){let t=e?.replace(/\s+/g," ").trim();return t||hp.untitled}function gp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function mp(e){let t=gp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?hp.newReply.replace("{date}",t):t}function bp(e,t){return t?`${hp.countLabel}${hp.countSeparator}${e}`:hp.countLabel}function yp(e){return`${e.unreadCount!==null&&e.unreadCount>0?hp.unreadPrefix:""}${hp.openConversation} ${pp(e.title)}`}function vp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function xp(e,t){let r=vp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=vp(pp(t.title)),i=e.indexOf(r);if(i<0)continue;let l=i===0?0:e.charAt(i-1)===" "?1:2;n[l]?.push(t)}return n.flat()}function wp(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function kp(e){let[r,n]=t.useState(false),[i,l]=t.useState(""),o=e.listConversations,s=t.useRef(0),[a,u]=t.useState(()=>wp(o)),c=a.scope===o?a:wp(o);t.useEffect(()=>(s.current+=1,n(false),l(""),u(wp(o)),()=>{s.current+=1}),[o]);let d=t.useCallback(async t=>{let r=++s.current,n=t!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let i=await e.listConversations(t?{cursor:t}:void 0);if(r===s.current){if(!i.ok){u(e=>({...e,loading:false,loadingMore:false,error:i.error.displayMessage}));return}u(e=>{let r=t&&e.scope===o?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...i.value.conversations.filter(e=>!n.has(e.id))],cursor:i.value.nextCursor===t?null:i.value.nextCursor}})}},[e.listConversations,o]),f=()=>{n(true),l(""),d()},h=()=>{s.current+=1,n(false)},p=async t=>{let r=++s.current;u(e=>({...e,loading:true,error:null}));let i=await e.resumeConversation(t);r===s.current&&(u(e=>({...e,loading:false,error:i.ok?null:i.error.displayMessage})),i.ok&&n(false))},g=async()=>{let t=s.current,r=await e.loadOlderMessages();t===s.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{e.newConversation(),s.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||i.trim().length>0||d(c.cursor)},y=t.useMemo(()=>xp(c.rows,i),[c.rows,i]),v=i.trim().length>0;return{...c,open:r,show:f,close:h,load:d,resume:p,earlier:g,newConversation:m,loadMore:b,query:i,setQuery:l,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var Cp="#111111",Sp="#FFFFFF",jp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Cp,pillColor:Sp,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Cp,pillColor:Sp,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Cp,pillColor:Sp,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Cp,pillColor:Sp,showsVetAction:false})});function _p(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Rp(e){return ff(df.urgencyGeneralReason,{petName:e?.trim()||df.emptyTitlePetFallback})}function Tp(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 i=n.urgencyLevel;return i?{messageId:n.id,level:i,reason:Ip(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Rp(t)}:null}return null}function Ip(e){return typeof e=="string"&&e.trim().length>0?e:null}function Pp(e){let r=e===null?null:_p(e),[n,i]=t.useState(null),[l,o]=t.useState(false);t.useEffect(()=>o(false),[r]);let s=e!==null&&(l||!(n!==null&&n===r)),a=e===null?null:jp[e.level],u=e!==null&&!s&&e.level!=="general",c=t.useCallback(()=>{r!==null&&i(r),o(false)},[r]),d=t.useCallback(()=>o(true),[]);return t.useMemo(()=>({source:e,tier:a,signature:r,showBanner:s,showCompactIcon:u,showVetAction:s&&a!==null&&a.showsVetAction,dismissLabel:a===null?null:ff(df.dismissBanner,{label:a.label}),dismiss:c,expand:d}),[e,a,r,s,u,c,d])}var zp="everfur.com",Ep=2048,Op=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Ap(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&Op.test(e)&&t.add(e)}/* @__PURE__ */
58
+ return Object.freeze([...t])}function Mp(e,t){if(e===zp||e.endsWith(`.${zp}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function Fp(e,t){if(typeof e!="string"||e.length===0||e.length>Ep||!/^https:\/\//i.test(e))return null;let r=N(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:Mp(r.hostname,t)?r.href:null}function Dp(e){try{Promise.resolve(r.Linking.openURL(e)).catch(()=>{})}catch{}}var Lp=t.createContext(null);function Bp(){return t.useContext(Lp)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:r,children:n}){let i=e===false?null:Array.isArray(e)?e.join(`\n`):"",l=t.useMemo(()=>{if(i===null)return null;let e=Ap(i===""?[]:i.split(`\n`));/* @__PURE__ */
59
+ return Object.freeze({hosts:e,open:r!==void 0?e=>{rh(r,e,"message")}:Dp})},[i,r]);return t.createElement(Lp.Provider,{value:l},n)}var Vp={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function Hp(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function Up(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o={width:e*.82,height:i,borderRadius:i,backgroundColor:t};/* @__PURE__ */
60
+ return l.jsxs(r.View,{style:[Hp(e),{gap:e*.22}],...Vp,children:[
61
61
  /* @__PURE__ */l.jsx(r.View,{style:o}),
62
62
  /* @__PURE__ */l.jsx(r.View,{style:o}),
63
- /* @__PURE__ */l.jsx(r.View,{style:o})]})}function Cross({size:e,color:t,strokeWidth:n,rotate:i}){let o=Rp(e,n),s=e*.78;/* @__PURE__ */
64
- return l.jsxs(r.View,{style:[_p(e),{transform:[{rotate:i}]}],...jp,children:[
63
+ /* @__PURE__ */l.jsx(r.View,{style:o})]})}function Cross({size:e,color:t,strokeWidth:n,rotate:i}){let o=Up(e,n),s=e*.78;/* @__PURE__ */
64
+ return l.jsxs(r.View,{style:[Hp(e),{transform:[{rotate:i}]}],...Vp,children:[
65
65
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),
66
66
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
67
67
  return l.jsx(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
68
- return l.jsx(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
69
- return l.jsx(r.View,{style:_p(e),...jp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:i,borderRightWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}})})}var Tp={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:n,direction:i}){let o=Rp(e,n),s=e*.46,a=Tp[i];/* @__PURE__ */
70
- return l.jsx(r.View,{style:_p(e),...jp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o={width:e*.42,height:e*.7,borderWidth:i,borderColor:t,borderRadius:i};/* @__PURE__ */
71
- return l.jsxs(r.View,{style:[_p(e),{flexDirection:"row",gap:1}],...jp,children:[
68
+ return l.jsx(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
69
+ return l.jsx(r.View,{style:Hp(e),...Vp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:i,borderRightWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}})})}var Np={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:n,direction:i}){let o=Up(e,n),s=e*.46,a=Np[i];/* @__PURE__ */
70
+ return l.jsx(r.View,{style:Hp(e),...Vp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o={width:e*.42,height:e*.7,borderWidth:i,borderColor:t,borderRadius:i};/* @__PURE__ */
71
+ return l.jsxs(r.View,{style:[Hp(e),{flexDirection:"row",gap:1}],...Vp,children:[
72
72
  /* @__PURE__ */l.jsx(r.View,{style:[o,{borderTopLeftRadius:e*.2}]}),
73
- /* @__PURE__ */l.jsx(r.View,{style:[o,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e*.5;/* @__PURE__ */
74
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
73
+ /* @__PURE__ */l.jsx(r.View,{style:[o,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e*.5;/* @__PURE__ */
74
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
75
75
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",width:e*.78,height:i,borderRadius:i,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
76
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:i,borderRightWidth:i,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:i,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
77
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
76
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:i,borderRightWidth:i,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:i,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
77
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
78
78
  /* @__PURE__ */l.jsx(r.View,{style:[s,{top:0,left:0}]}),
79
- /* @__PURE__ */l.jsx(r.View,{style:[s,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:n,active:i,rotate:o}){let s=Rp(e,n),a=i?t:"transparent";/* @__PURE__ */
80
- return l.jsxs(r.View,{style:[_p(e),{transform:[{rotate:o}]}],...jp,children:[
79
+ /* @__PURE__ */l.jsx(r.View,{style:[s,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:n,active:i,rotate:o}){let s=Up(e,n),a=i?t:"transparent";/* @__PURE__ */
80
+ return l.jsxs(r.View,{style:[Hp(e),{transform:[{rotate:o}]}],...Vp,children:[
81
81
  /* @__PURE__ */l.jsx(r.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}}),
82
82
  /* @__PURE__ */l.jsx(r.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"}]}}),
83
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
84
- return l.jsxs(r.View,{style:[_p(e),{borderRadius:e/2,borderWidth:i,borderColor:t}],...jp,children:[
83
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
84
+ return l.jsxs(r.View,{style:[Hp(e),{borderRadius:e/2,borderWidth:i,borderColor:t}],...Vp,children:[
85
85
  /* @__PURE__ */l.jsx(r.View,{style:{width:i,height:i,borderRadius:i,backgroundColor:t,marginBottom:e*.1}}),
86
- /* @__PURE__ */l.jsx(r.View,{style:{width:i,height:e*.34,borderRadius:i,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e*.34;/* @__PURE__ */
87
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
86
+ /* @__PURE__ */l.jsx(r.View,{style:{width:i,height:e*.34,borderRadius:i,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e*.34;/* @__PURE__ */
87
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
88
88
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:i,borderLeftWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}}),
89
89
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.1,width:i,height:e*.56,borderRadius:i,backgroundColor:t}}),
90
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:i,borderLeftWidth:i,borderRightWidth:i,borderColor:t,borderBottomLeftRadius:i,borderBottomRightRadius:i}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
91
- return l.jsxs(r.View,{style:[_p(e),{borderWidth:i,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...jp,children:[
90
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:i,borderLeftWidth:i,borderRightWidth:i,borderColor:t,borderBottomLeftRadius:i,borderBottomRightRadius:i}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
91
+ return l.jsxs(r.View,{style:[Hp(e),{borderWidth:i,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...Vp,children:[
92
92
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
93
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:i,borderLeftWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
94
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
93
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:i,borderLeftWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
94
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
95
95
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:i,borderLeftWidth:i,borderRightWidth:i,borderColor:t,borderTopLeftRadius:i,borderTopRightRadius:i}}),
96
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:i,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:i,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e/24,s=16*o+i,a=11*o-s/2,u=11+8/Math.SQRT2,c=(21-u)*Math.SQRT2*o,d=(u+21)/2*o;/* @__PURE__ */
97
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
96
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:i,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:i,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e/24,s=16*o+i,a=11*o-s/2,u=11+8/Math.SQRT2,c=(21-u)*Math.SQRT2*o,d=(u+21)/2*o;/* @__PURE__ */
97
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
98
98
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:a,left:a,width:s,height:s,borderRadius:s,borderWidth:i,borderColor:t}}),
99
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:d-i/2,left:d-(c+i)/2,width:c+i,height:i,borderRadius:i,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
100
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
99
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:d-i/2,left:d-(c+i)/2,width:c+i,height:i,borderRadius:i,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
100
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
101
101
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:i,borderColor:t,borderRadius:i,transform:[{rotate:"45deg"}]}}),
102
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:i,borderRadius:i,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e*.62;/* @__PURE__ */
103
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
102
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:i,borderRadius:i,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e*.62;/* @__PURE__ */
103
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
104
104
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:i,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */l.jsx(r.View,{style:{width:i*1.4,height:i*1.4,borderRadius:i,backgroundColor:t}})}),
105
105
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:i,borderBottomWidth:i,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:n}){let i=e*.36;/* @__PURE__ */
106
- return l.jsx(r.View,{style:_p(e),testID:n,...jp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:i,borderBottomWidth:i,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:n}){/* @__PURE__ */
107
- return l.jsx(r.View,{style:_p(e),testID:n,...jp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:n,testID:i}){let o=Rp(e,n);/* @__PURE__ */
108
- return l.jsxs(r.View,{style:_p(e),testID:i,...jp,children:[
106
+ return l.jsx(r.View,{style:Hp(e),testID:n,...Vp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:i,borderBottomWidth:i,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:n}){/* @__PURE__ */
107
+ return l.jsx(r.View,{style:Hp(e),testID:n,...Vp,children:/* @__PURE__ */l.jsx(r.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:n,testID:i}){let o=Up(e,n);/* @__PURE__ */
108
+ return l.jsxs(r.View,{style:Hp(e),testID:i,...Vp,children:[
109
109
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:o,borderColor:t,borderRadius:e*.13}}),
110
110
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:o,borderLeftWidth:o,borderRightWidth:o,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
111
111
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.74,width:o,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:n,children:i}){/* @__PURE__ */
112
- return l.jsx(r.View,{style:[_p(e),{borderRadius:e/2,borderWidth:t??r.StyleSheet.hairlineWidth,borderColor:n}],children:i})}function ArrowUpGlyph({size:e,color:t,strokeWidth:n,testID:i}){let o=Rp(e,n),s=e*.46;/* @__PURE__ */
113
- return l.jsxs(r.View,{style:_p(e),testID:i,...jp,children:[
112
+ return l.jsx(r.View,{style:[Hp(e),{borderRadius:e/2,borderWidth:t??r.StyleSheet.hairlineWidth,borderColor:n}],children:i})}function ArrowUpGlyph({size:e,color:t,strokeWidth:n,testID:i}){let o=Up(e,n),s=e*.46;/* @__PURE__ */
113
+ return l.jsxs(r.View,{style:Hp(e),testID:i,...Vp,children:[
114
114
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:o,borderRadius:o,backgroundColor:t}}),
115
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16+o/2,width:s,height:s,borderLeftWidth:o,borderTopWidth:o,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n);/* @__PURE__ */
116
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
115
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16+o/2,width:s,height:s,borderLeftWidth:o,borderTopWidth:o,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n);/* @__PURE__ */
116
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
117
117
  /* @__PURE__ */l.jsx(r.View,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:i,borderColor:t,borderRadius:e*.14}}),
118
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:i,borderBottomWidth:i,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:n}){let i=Rp(e,n),o=e*.72,s=e/2;/* @__PURE__ */
119
- return l.jsxs(r.View,{style:_p(e),...jp,children:[
118
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:i,borderBottomWidth:i,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:n}){let i=Up(e,n),o=e*.72,s=e/2;/* @__PURE__ */
119
+ return l.jsxs(r.View,{style:Hp(e),...Vp,children:[
120
120
  /* @__PURE__ */l.jsx(r.View,{style:{width:o,height:o,borderRadius:o/2,borderWidth:i,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
121
121
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:i,borderBottomWidth:i,borderColor:t}}),
122
122
  /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:s-e*.2,left:s-i/2,width:i,height:e*.2+i/2,borderRadius:i,backgroundColor:t}}),
123
- /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:s-i/2,left:s-i/2,width:e*.15+i/2,height:i,borderRadius:i,backgroundColor:t}})]})}var Ip=/* @__PURE__ */Object.freeze({standard:So.standard,emphasized:So.emphasized,exit:So.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var Pp=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),zp=/* @__PURE__ */Object.freeze({...Pp,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function Ep(e){return e.motion.reducedMotion?zp:Pp}function Op(e,t){return Math.max(0,t)*e.followUpStaggerMs}function Ap(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)}function Mp(){let e=useEverfurTheme();return Ep(e)}var Fp=8;function Dp(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function Lp(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function Bp(e){let[t,r,n,i]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let l=e;for(let r=0;r<Fp;r+=1){let r=Lp(l,t,n);if(r===0)break;l-=(Dp(l,t,n)-e)/r}return Dp(Math.min(1,Math.max(0,l)),r,i)}}var Vp=Bp(Ip.standard),Hp=Bp(Ip.outQuad),Up=Bp(Ip.out);function Np(e){let n=t.useRef(null);return n.current===null&&(n.current=new r.Animated.Value(e)),n.current}function $p(e,n={}){let i=n.risePx??0,l=n.delayMs??0,o=Np(e>0?0:1);return t.useEffect(()=>{if(e<=0){o.setValue(1);return}let t=r.Animated.timing(o,{toValue:1,duration:e,easing:Hp,useNativeDriver:true}),n=l>0?r.Animated.sequence([r.Animated.delay(l),t]):t;return n.start(),()=>n.stop()},[o,e,l]),t.useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[i,0]})}]}),[o,i])}function FadePresence({visible:e,inMs:n,outMs:i,style:o,children:s}){let[a,u]=t.useState(e),c=Np(e&&n<=0?1:0);return t.useEffect(()=>{if(e){u(true);let e=r.Animated.timing(c,{toValue:1,duration:Math.max(0,n),easing:Vp,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(i<=0){u(false);return}let t=r.Animated.timing(c,{toValue:0,duration:i,easing:Vp,useNativeDriver:true});return t.start(({finished:e})=>{e&&u(false)}),()=>t.stop()},[e,a,n,i,c]),!a&&!e?null:/* @__PURE__ */l.jsx(r.Animated.View,{style:[o,{opacity:c}],children:s})}var Wp=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function qp(e,n){let[i]=t.useState(()=>e?n.bubbleInMs:0),l=i>0,o=Np(l?0:1);t.useEffect(()=>{if(i<=0)return;let e=r.Animated.timing(o,{toValue:1,duration:i,easing:Up,useNativeDriver:true});return e.start(),()=>e.stop()},[i,o]);let s=n.bubbleFromScale,a=n.bubbleRisePx;return t.useMemo(()=>l?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[a,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Wp,[l,o,a,s])}function Gp(e){let r=t.useRef(null),n=t.useRef(null),i=e[0]?.id??null;if(r.current===null||n.current!==i){let t=r.current===null;r.current=new Map(e.map(e=>[e.id,t&&e.pending===true])),n.current=i}let l=r.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return t.useCallback(e=>l.get(e)===true,[l])}var Kp=12;function PressScale({style:e,containerStyle:n,children:i,onPressIn:o,onPressOut:s,hitSlop:a,...u}){let c=Mp(),d=Np(1),f=t.useCallback(e=>{c.pressMs<=0||c.pressScale===1||r.Animated.timing(d,{toValue:e,duration:c.pressMs,easing:Vp,useNativeDriver:true}).start()},[d,c.pressMs,c.pressScale]);/* @__PURE__ */
124
- return l.jsx(r.Pressable,{...u,hitSlop:a??Kp,style:n,onPressIn:e=>{f(c.pressScale),o?.(e)},onPressOut:e=>{f(1),s?.(e)},children:/* @__PURE__ */l.jsx(r.Animated.View,{style:[e,{transform:[{scale:d}]}],children:i})})}function Yp(e,r,n){let i=r&&n.revealTickMs>0,[l,o]=t.useState(0),s=t.useRef(e);return s.current=e,t.useEffect(()=>{if(!i)return;let e=setInterval(()=>{o(e=>Ap(n,e,s.current.length))},n.revealTickMs);return()=>clearInterval(e)},[i,n]),i?e.slice(0,Math.min(l,e.length)):e}var Qp=false;function Xp(e){e.layoutMs<=0||(Qp||(Qp=true,r.Platform.OS==="android"&&typeof r.UIManager.setLayoutAnimationEnabledExperimental=="function"&&r.UIManager.setLayoutAnimationEnabledExperimental(true)),r.LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function Zp(e,r){let n=t.useRef(e);n.current!==e&&(n.current=e,Xp(r))}var Jp=36,eg=22,tg=12,rg=12,ng=16,ig="#000",lg="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:i}){let o=useEverfurTheme(),s=n.useSafeAreaInsets();return e===null?null:/* @__PURE__ */l.jsxs(r.Modal,{visible:true,animationType:o.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:i,children:[
125
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Yd.closePreview,style:og.backdrop,onPress:i,children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e},style:og.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
126
- /* @__PURE__ */l.jsx(r.View,{pointerEvents:"box-none",style:[og.closeWrap,{top:s.top+rg}],children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.closePreview,hitSlop:tg,style:og.closeButton,onPress:i,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:eg,color:o.color.surface,strokeWidth:2})})})]})}var og=r.StyleSheet.create({backdrop:{flex:1,backgroundColor:ig,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:ng},closeButton:{width:Jp,height:Jp,borderRadius:Jp/2,backgroundColor:lg,alignItems:"center",justifyContent:"center"}});var sg=()=>{};function ag(){try{return r.AppState.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let n=r.AppState.currentState==="background";t=r.AppState.addEventListener("change",t=>{t==="background"?n=!0:t==="active"&&n&&(n=!1,e())})}catch{return sg}return()=>t.remove()},isVisible:ag}}function ug(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}function cg(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function dg(e){return e?.textColor===void 0?{}:{color:e.textColor}}function fg(e){switch(e.code){case"too_large":return Qd(Yd.attachmentTooLarge,{max:formatBytes(On),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return Qd(Yd.attachmentTooMany,{max:An});case"unsupported_type":return Qd(Yd.attachmentUnsupported,{filename:e.filename});case"network":return Yd.attachmentNetwork;case"server":return Qd(Yd.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case"cancelled":return Yd.attachmentCancelled;case"rate_limited":return Yd.attachmentRateLimited;case"quota_exceeded":return Yd.attachmentQuota;case"idempotency_conflict":return Yd.attachmentConflict;case"unknown":return Yd.attachmentUnknown}}function hg(e,t){return Qd(e>=t?Yd.attachmentsFull:Yd.addAttachment,{used:e,total:t})}var pg=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:r,userRef:n,scopeEpoch:i}=Lc(),l=e.maxPerMessage??An,o=t.useCallback(()=>{let{services:t}=r.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:t.authFor(n),...t.errorPolicy?{errorPolicy:t.errorPolicy}:{}}),transport:e.transport??t.uploadTransport,maxPerMessage:l})},[r,n,i,l,e.transport]),s=t.useMemo(()=>e.queue??o(),[e.queue,o]),a=t.useRef(/* @__PURE__ */new WeakSet),[u,c]=t.useState(null),d=u!==null&&u.of===s?u.queue:s;t.useEffect(()=>{if(d!==e.queue){if(a.current.has(d)){c({of:s,queue:o()});return}return()=>{d.dispose(),a.current.add(d)}}},[d,s,o,e.queue]);let f=t.useSyncExternalStore(d.subscribe,d.getSnapshot,()=>pg),[h,p]=t.useState(null),g=t.useCallback(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>d.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&p(r.error),t},[d,p]),m=t.useCallback(e=>d.retry(e),[d]),b=t.useCallback(e=>d.remove(e),[d]),y=t.useCallback(()=>d.clear(),[d]),v=t.useCallback(()=>p(null),[p]),x=f.attachments.some(e=>e.status==="uploading"),w=f.attachments.some(e=>e.status==="failed");return t.useMemo(()=>({available:d.available,attachments:f.attachments,maxPerMessage:l,uploading:x,failed:w,blocked:x||w,s3Keys:f.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:h,add:g,retry:m,remove:b,clear:y,dismissRejected:v}),[d.available,f,l,x,w,h,g,m,b,y,v])}var gg=6e3;function mg(e,t,r){let n=t.trim();if(!n)return e;let i=e===""||/\s$/.test(e)?"":" ",l=`${e}${i}${n}`;return typeof r=="number"&&r>0?l.slice(0,r):l}function bg(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function yg(e){switch(e){case"permissionDenied":return Yd.micBlocked;case"noSpeech":return Yd.noSpeech;case"unavailable":return Yd.dictationUnavailable}}function vg(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var xg=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function wg(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...xg]){let e=(n??"").trim();if(!e)continue;let i=e.toLowerCase();if(!t.has(i)&&(t.add(i),r.push(e),r.length>=100))break}return r}function kg(e,r,n){let[i,l]=t.useState({send:e,conversationId:r,text:n??"",seeded:n??null}),o=i.send===e&&(i.conversationId===null||i.conversationId===r);t.useEffect(()=>{l(t=>{let i=t.send===e&&(t.conversationId===null||t.conversationId===r),l=i?t.text:"",o=i?t.seeded:null,s=n!=null&&n!==o&&l.length===0;return{send:e,conversationId:r,text:s?n:l,seeded:s?n:o}})},[e,r,n]);let s=t.useCallback(t=>l(n=>({send:e,conversationId:r,text:t,seeded:n.seeded})),[e,r]);return[o?i.text:"",s]}function Cg(e,r,n,i,l=false){let o=t.useRef({draft:n,setDraft:i});o.current={draft:n,setDraft:i};let s=t.useRef(null),[a,u]=t.useState(null);t.useEffect(()=>{if(e===void 0)return;let t=`${r??""}`;if(s.current===t)return;s.current=t;let n=true;return(async()=>{let i=await $f(()=>e.read(r));if(!n)return;let l=i.ok&&typeof i.value=="string"?i.value:"";l.length>0&&o.current.draft.length===0&&o.current.setDraft(l),u(t)})(),()=>{n=false}},[e,r]),t.useEffect(()=>{e===void 0||l||a!==`${r??""}`||Hf(()=>e.write(r,n))},[e,r,n,a,l])}function Sg(e){if(!(r.Platform.OS!=="ios"||e===""))try{let t=r.AccessibilityInfo?.announceForAccessibility;typeof t=="function"&&t.call(r.AccessibilityInfo,e)}catch{}}function AnnounceLine({line:e}){return t.useEffect(()=>{Sg(e)},[e]),null}var jg=12,_g=80,Rg=44,Tg=22,Ig=.14,Pg=18,zg=8,Eg=/* @__PURE__ */Object.freeze({photo:Yd.attachmentPhoto,camera:Yd.attachmentCamera});function AttachmentPickerPopover({sources:e,full:n,onPick:i,onClose:o}){let s=useEverfurTheme(),a=t.useMemo(()=>Og(s),[s]);/* @__PURE__ */
123
+ /* @__PURE__ */l.jsx(r.View,{style:{position:"absolute",top:s-i/2,left:s-i/2,width:e*.15+i/2,height:i,borderRadius:i,backgroundColor:t}})]})}var $p=/* @__PURE__ */Object.freeze({standard:Ro.standard,emphasized:Ro.emphasized,exit:Ro.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var Wp=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),qp=/* @__PURE__ */Object.freeze({...Wp,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function Gp(e){return e.motion.reducedMotion?qp:Wp}function Kp(e,t){return Math.max(0,t)*e.followUpStaggerMs}function Yp(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)}function Qp(){let e=useEverfurTheme();return Gp(e)}var Xp=8;function Zp(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function Jp(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function eg(e){let[t,r,n,i]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let l=e;for(let r=0;r<Xp;r+=1){let r=Jp(l,t,n);if(r===0)break;l-=(Zp(l,t,n)-e)/r}return Zp(Math.min(1,Math.max(0,l)),r,i)}}var tg=eg($p.standard),rg=eg($p.outQuad),ng=eg($p.out);function ig(e){let n=t.useRef(null);return n.current===null&&(n.current=new r.Animated.Value(e)),n.current}function lg(e,n={}){let i=n.risePx??0,l=n.delayMs??0,o=ig(e>0?0:1);return t.useEffect(()=>{if(e<=0){o.setValue(1);return}let t=r.Animated.timing(o,{toValue:1,duration:e,easing:rg,useNativeDriver:true}),n=l>0?r.Animated.sequence([r.Animated.delay(l),t]):t;return n.start(),()=>n.stop()},[o,e,l]),t.useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[i,0]})}]}),[o,i])}function FadePresence({visible:e,inMs:n,outMs:i,style:o,children:s}){let[a,u]=t.useState(e),c=ig(e&&n<=0?1:0);return t.useEffect(()=>{if(e){u(true);let e=r.Animated.timing(c,{toValue:1,duration:Math.max(0,n),easing:tg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(i<=0){u(false);return}let t=r.Animated.timing(c,{toValue:0,duration:i,easing:tg,useNativeDriver:true});return t.start(({finished:e})=>{e&&u(false)}),()=>t.stop()},[e,a,n,i,c]),!a&&!e?null:/* @__PURE__ */l.jsx(r.Animated.View,{style:[o,{opacity:c}],children:s})}var og=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function sg(e,n){let[i]=t.useState(()=>e?n.bubbleInMs:0),l=i>0,o=ig(l?0:1);t.useEffect(()=>{if(i<=0)return;let e=r.Animated.timing(o,{toValue:1,duration:i,easing:ng,useNativeDriver:true});return e.start(),()=>e.stop()},[i,o]);let s=n.bubbleFromScale,a=n.bubbleRisePx;return t.useMemo(()=>l?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[a,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:og,[l,o,a,s])}function ag(e){let r=t.useRef(null),n=t.useRef(null),i=e[0]?.id??null;if(r.current===null||n.current!==i){let t=r.current===null;r.current=new Map(e.map(e=>[e.id,t&&e.pending===true])),n.current=i}let l=r.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return t.useCallback(e=>l.get(e)===true,[l])}var ug=12;function PressScale({style:e,containerStyle:n,children:i,onPressIn:o,onPressOut:s,hitSlop:a,...u}){let c=Qp(),d=ig(1),f=t.useCallback(e=>{c.pressMs<=0||c.pressScale===1||r.Animated.timing(d,{toValue:e,duration:c.pressMs,easing:tg,useNativeDriver:true}).start()},[d,c.pressMs,c.pressScale]);/* @__PURE__ */
124
+ return l.jsx(r.Pressable,{...u,hitSlop:a??ug,style:n,onPressIn:e=>{f(c.pressScale),o?.(e)},onPressOut:e=>{f(1),s?.(e)},children:/* @__PURE__ */l.jsx(r.Animated.View,{style:[e,{transform:[{scale:d}]}],children:i})})}function cg(e,r,n){let i=r&&n.revealTickMs>0,[l,o]=t.useState(0),s=t.useRef(e);return s.current=e,t.useEffect(()=>{if(!i)return;let e=setInterval(()=>{o(e=>Yp(n,e,s.current.length))},n.revealTickMs);return()=>clearInterval(e)},[i,n]),i?e.slice(0,Math.min(l,e.length)):e}var dg=false;function fg(e){e.layoutMs<=0||(dg||(dg=true,r.Platform.OS==="android"&&typeof r.UIManager.setLayoutAnimationEnabledExperimental=="function"&&r.UIManager.setLayoutAnimationEnabledExperimental(true)),r.LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function hg(e,r){let n=t.useRef(e);n.current!==e&&(n.current=e,fg(r))}var pg=36,gg=22,mg=12,bg=12,yg=16,vg="#000",xg="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:i}){let o=useEverfurTheme(),s=n.useSafeAreaInsets();return e===null?null:/* @__PURE__ */l.jsxs(r.Modal,{visible:true,animationType:o.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:i,children:[
125
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:df.closePreview,style:wg.backdrop,onPress:i,children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e},style:wg.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
126
+ /* @__PURE__ */l.jsx(r.View,{pointerEvents:"box-none",style:[wg.closeWrap,{top:s.top+bg}],children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:df.closePreview,hitSlop:mg,style:wg.closeButton,onPress:i,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:gg,color:o.color.surface,strokeWidth:2})})})]})}var wg=r.StyleSheet.create({backdrop:{flex:1,backgroundColor:vg,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:yg},closeButton:{width:pg,height:pg,borderRadius:pg/2,backgroundColor:xg,alignItems:"center",justifyContent:"center"}});var kg=()=>{};function Cg(){try{return r.AppState.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let n=r.AppState.currentState==="background";t=r.AppState.addEventListener("change",t=>{t==="background"?n=!0:t==="active"&&n&&(n=!1,e())})}catch{return kg}return()=>t.remove()},isVisible:Cg}}function Sg(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}function jg(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function _g(e){return e?.textColor===void 0?{}:{color:e.textColor}}function Rg(e){switch(e.code){case"too_large":return ff(df.attachmentTooLarge,{max:formatBytes(Fn),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return ff(df.attachmentTooMany,{max:Dn});case"unsupported_type":return ff(df.attachmentUnsupported,{filename:e.filename});case"network":return df.attachmentNetwork;case"server":return ff(df.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case"cancelled":return df.attachmentCancelled;case"rate_limited":return df.attachmentRateLimited;case"quota_exceeded":return df.attachmentQuota;case"idempotency_conflict":return df.attachmentConflict;case"unknown":return df.attachmentUnknown}}function Tg(e,t){return ff(e>=t?df.attachmentsFull:df.addAttachment,{used:e,total:t})}var Ig=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:r,userRef:n,scopeEpoch:i}=Hc(),l=e.maxPerMessage??Dn,o=t.useCallback(()=>{let{services:t}=r.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:t.authFor(n),...t.errorPolicy?{errorPolicy:t.errorPolicy}:{}}),transport:e.transport??t.uploadTransport,maxPerMessage:l})},[r,n,i,l,e.transport]),s=t.useMemo(()=>e.queue??o(),[e.queue,o]),a=t.useRef(/* @__PURE__ */new WeakSet),[u,c]=t.useState(null),d=u!==null&&u.of===s?u.queue:s;t.useEffect(()=>{if(d!==e.queue){if(a.current.has(d)){c({of:s,queue:o()});return}return()=>{d.dispose(),a.current.add(d)}}},[d,s,o,e.queue]);let f=t.useSyncExternalStore(d.subscribe,d.getSnapshot,()=>Ig),[h,p]=t.useState(null),g=t.useCallback(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>d.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&p(r.error),t},[d,p]),m=t.useCallback(e=>d.retry(e),[d]),b=t.useCallback(e=>d.remove(e),[d]),y=t.useCallback(()=>d.clear(),[d]),v=t.useCallback(()=>p(null),[p]),x=f.attachments.some(e=>e.status==="uploading"),w=f.attachments.some(e=>e.status==="failed");return t.useMemo(()=>({available:d.available,attachments:f.attachments,maxPerMessage:l,uploading:x,failed:w,blocked:x||w,s3Keys:f.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:h,add:g,retry:m,remove:b,clear:y,dismissRejected:v}),[d.available,f,l,x,w,h,g,m,b,y,v])}var Pg=6e3;function zg(e,t,r){let n=t.trim();if(!n)return e;let i=e===""||/\s$/.test(e)?"":" ",l=`${e}${i}${n}`;return typeof r=="number"&&r>0?l.slice(0,r):l}function Eg(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function Og(e){switch(e){case"permissionDenied":return df.micBlocked;case"noSpeech":return df.noSpeech;case"unavailable":return df.dictationUnavailable}}function Ag(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var Mg=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function Fg(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...Mg]){let e=(n??"").trim();if(!e)continue;let i=e.toLowerCase();if(!t.has(i)&&(t.add(i),r.push(e),r.length>=100))break}return r}function Dg(e,r,n){let[i,l]=t.useState({send:e,conversationId:r,text:n??"",seeded:n??null}),o=i.send===e&&(i.conversationId===null||i.conversationId===r);t.useEffect(()=>{l(t=>{let i=t.send===e&&(t.conversationId===null||t.conversationId===r),l=i?t.text:"",o=i?t.seeded:null,s=n!=null&&n!==o&&l.length===0;return{send:e,conversationId:r,text:s?n:l,seeded:s?n:o}})},[e,r,n]);let s=t.useCallback(t=>l(n=>({send:e,conversationId:r,text:t,seeded:n.seeded})),[e,r]);return[o?i.text:"",s]}function Lg(e,r,n,i,l=false){let o=t.useRef({draft:n,setDraft:i});o.current={draft:n,setDraft:i};let s=t.useRef(null),[a,u]=t.useState(null);t.useEffect(()=>{if(e===void 0)return;let t=`${r??""}`;if(s.current===t)return;s.current=t;let n=true;return(async()=>{let i=await lh(()=>e.read(r));if(!n)return;let l=i.ok&&typeof i.value=="string"?i.value:"";l.length>0&&o.current.draft.length===0&&o.current.setDraft(l),u(t)})(),()=>{n=false}},[e,r]),t.useEffect(()=>{e===void 0||l||a!==`${r??""}`||rh(()=>e.write(r,n))},[e,r,n,a,l])}function Bg(e){if(!(r.Platform.OS!=="ios"||e===""))try{let t=r.AccessibilityInfo?.announceForAccessibility;typeof t=="function"&&t.call(r.AccessibilityInfo,e)}catch{}}function AnnounceLine({line:e}){return t.useEffect(()=>{Bg(e)},[e]),null}var Vg=12,Hg=80,Ug=44,Ng=22,$g=.14,Wg=18,qg=8,Gg=/* @__PURE__ */Object.freeze({photo:df.attachmentPhoto,camera:df.attachmentCamera});function AttachmentPickerPopover({sources:e,full:n,onPick:i,onClose:o}){let s=useEverfurTheme(),a=t.useMemo(()=>Kg(s),[s]);/* @__PURE__ */
127
127
  return l.jsxs(r.View,{style:a.anchor,pointerEvents:"box-none",children:[
128
- /* @__PURE__ */l.jsx(r.Pressable,{style:a.dismissLayer,accessibilityRole:"button",accessibilityLabel:Yd.closeAttachmentPicker,onPress:o}),
128
+ /* @__PURE__ */l.jsx(r.Pressable,{style:a.dismissLayer,accessibilityRole:"button",accessibilityLabel:df.closeAttachmentPicker,onPress:o}),
129
129
  /* @__PURE__ */l.jsxs(r.View,{style:a.bubble,children:[
130
- /* @__PURE__ */l.jsx(r.View,{style:a.tilesRow,children:e.map(e=>/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Eg[e],accessibilityState:{disabled:n},disabled:n,containerStyle:a.tile,style:a.tileInner,onPress:()=>i(e),children:[
131
- /* @__PURE__ */l.jsx(r.View,{style:a.tileIconWrap,children:e==="photo"?/* @__PURE__ */l.jsx(PhotoGlyph,{size:Tg,color:s.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */l.jsx(CameraGlyph,{size:Tg,color:s.color.brandInk,strokeWidth:1.5})}),
132
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.tileLabel,children:Eg[e]})]},e))}),
130
+ /* @__PURE__ */l.jsx(r.View,{style:a.tilesRow,children:e.map(e=>/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Gg[e],accessibilityState:{disabled:n},disabled:n,containerStyle:a.tile,style:a.tileInner,onPress:()=>i(e),children:[
131
+ /* @__PURE__ */l.jsx(r.View,{style:a.tileIconWrap,children:e==="photo"?/* @__PURE__ */l.jsx(PhotoGlyph,{size:Ng,color:s.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */l.jsx(CameraGlyph,{size:Ng,color:s.color.brandInk,strokeWidth:1.5})}),
132
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.tileLabel,children:Gg[e]})]},e))}),
133
133
  /* @__PURE__ */l.jsx(r.View,{style:a.tail}),
134
- /* @__PURE__ */l.jsx(r.View,{style:a.tailFill})]})]})}function Og(e){let t=e.color,n=e.radius;return r.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:n.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:Ig,shadowRadius:Pg,shadowOffset:{width:0,height:zg},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:_g,borderRadius:n.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Rg,height:Rg,borderRadius:Rg/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-jg/2,width:jg,height:jg,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:jg+4,height:2,backgroundColor:t.surfaceCream}})}var Ag=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Mg=56,Fg=12,Dg=14,Lg=10,Bg=.45,Vg="rgba(7,193,104,0.55)",Hg="rgba(185,28,28,0.55)",Ug=200,Ng=300,$g=20,Wg=22,qg=12,Gg="rgba(0,0,0,0.78)",Kg=220,Yg=100,Qg="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:n,uploadFailed:i=false,onRetry:o,onRemove:s,onPreview:a,style:u}){let c=useEverfurTheme(),d=t.useMemo(()=>Xg(c),[c]);return e.length===0&&n===null?null:/* @__PURE__ */l.jsxs(r.View,{style:[d.strip,u],children:[e.length>0?/* @__PURE__ */l.jsx(r.View,{style:d.cards,children:e.map(e=>/* @__PURE__ */l.jsx(PreviewCard,{row:e,styles:d,onRetry:o,onRemove:s,onPreview:a},e.id))}):null,i?/* @__PURE__ */l.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:Yd.attachmentsFailedBlocked}):null,n!==null?/* @__PURE__ */l.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:fg(n)}):null]})}function PreviewCard({row:e,styles:n,onRetry:i,onRemove:o,onPreview:s}){let a=useEverfurTheme(),u=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=t.useRef(e.status),[h,p]=t.useState(false);return t.useEffect(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */l.jsxs(r.View,{style:n.card,children:[
135
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:d?"button":"image",accessibilityLabel:d?Qd(Yd.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:u,disabled:!d},disabled:!d,style:n.thumbHit,onPress:()=>s(e),children:/* @__PURE__ */l.jsxs(r.View,{style:n.thumb,children:[
136
- /* @__PURE__ */l.jsx(r.Image,{source:{uri:e.previewUri},style:n.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),u?/* @__PURE__ */l.jsx(r.View,{style:n.uploadingOverlay,children:/* @__PURE__ */l.jsx(r.ActivityIndicator,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */l.jsx(SuccessFlash,{styles:n,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Qd(Yd.retryUpload,{filename:e.filename}),style:n.failedOverlay,onPress:()=>i(e.id),children:/* @__PURE__ */l.jsx(r.View,{style:n.failedInner,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:$g,color:a.color.surface,strokeWidth:2})})}):null,
137
- /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Qd(Yd.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:n.removeSlot,style:n.removeButton,onPress:()=>o(e.id),children:/* @__PURE__ */l.jsx(CloseGlyph,{size:qg,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:n}){let i=useEverfurTheme(),o=Mp(),s=t.useRef(null);s.current===null&&(s.current=new r.Animated.Value(0));let a=s.current;return t.useEffect(()=>{let e=r.Animated.sequence([r.Animated.timing(a,{toValue:1,duration:Ug,useNativeDriver:true}),r.Animated.delay(o.uploadFlashMs),r.Animated.timing(a,{toValue:0,duration:Ng,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&n()}),()=>e.stop()},[a,o.uploadFlashMs,n]),/* @__PURE__ */l.jsx(r.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:a}],children:/* @__PURE__ */l.jsx(CheckGlyph,{size:$g,color:i.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Xg(i),[i]);if(e.length===0)return null;let s=e.length===1;/* @__PURE__ */
138
- return l.jsx(r.View,{style:s?o.sentSingle:o.sentGrid,children:e.map((e,t)=>/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Qd(Yd.attachedImage,{filename:e.filename}),onPress:()=>n(e),children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e.uri},style:s?o.singleImage:o.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${t}`))})}function Xg(e){let t=e.color,n=e.type;return r.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Mg,height:Mg,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Fg,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Ag,alignItems:"center",justifyContent:"center",backgroundColor:El(e.color.brandInk,Bg)??e.color.brandSofter},successOverlay:{...Ag,alignItems:"center",justifyContent:"center",backgroundColor:Vg},failedOverlay:{...Ag,borderRadius:Fg,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Hg},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Wg,height:Wg,borderRadius:Wg/2,backgroundColor:Gg,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Kg,height:Kg,borderRadius:Dg,backgroundColor:Qg},gridImage:{width:Yg,height:Yg,borderRadius:Lg,backgroundColor:Qg}})}var Zg="chat attachment upload: the file handle has no uri",Jg="chat attachment upload failed";function em(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
139
- return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Zg));let{signal:i,onProgress:l}=n,o=()=>Promise.reject(new Error(Jg));return i?.aborted===true?o():te({url:t.upload_url,fields:t.upload_fields,file:em(r),signal:i,fetch:e.fetch}).then(e=>{if(!e)return o();l?.(1)},o)}})}var tm=300,rm=3e3,nm=120,im=44,lm=120,om="88%",sm=520,am=2,um=.5,cm=1.5,dm=1.6,fm=.6,hm=56,pm=1.5,gm=5,mm=5,bm=36,ym=20,vm=14,xm=im,wm=4,km=24,Cm=22,Sm=.4,jm=im,_m=20,Rm=.4,Tm=480,Im=12,Pm=.72,zm=48,Em=1.5,Om=1.3,Am=1,Mm=1,Fm="12%",Dm=14,Lm=16,Bm=28,Vm=18,Hm="84%",Um=10,Nm=15,$m=1.42,Wm=4,qm=3,Gm=14,Km=20;function Ym(){let e=useEverfurTheme(),r=t.useMemo(()=>Qm(e),[e]);return{theme:e,styles:r}}function Qm(e){let t=e.color,n=e.space,i=e.radius,l=e.type,o=Math.round(l.size.body*cm),s=Math.round(l.size.body*dm),a=Math.round(ym*l.size.body/vm),u=t.borderRingCream,c=e.slots;return r.StyleSheet.create({container:{flex:1,minHeight:nm,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:nm,flexGrow:1,alignItems:"center",justifyContent:"center",padding:n.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:Fm,paddingHorizontal:n.lg,paddingBottom:n.lg,minHeight:Tm,gap:n.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:n.md},retryButton:{minHeight:im,minWidth:im,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:i.pill,backgroundColor:t.brand,...ug(c.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...dg(c.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:n.xs,padding:n.md,borderRadius:i.md,backgroundColor:t.surfaceCream,borderWidth:Mm,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal},turnNoticeAction:{minHeight:im,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:l.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:n.xs,paddingVertical:n.md,paddingHorizontal:n.md+n.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:i.md},readingDot:{width:6,height:6,borderRadius:i.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:qm,minHeight:Gm},readingDotInline:{width:Wm,height:Wm,borderRadius:i.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:im,justifyContent:"center",paddingHorizontal:n.md+n.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:n.lg,gap:n.xl},listContentCards:{paddingTop:Dm,paddingHorizontal:Lm,paddingBottom:Bm,gap:Vm},rowBlock:{gap:n.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:n.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:om,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:sm,paddingVertical:n.md,paddingHorizontal:n.lg+am,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:um,borderColor:t.primaryEdge}:{},borderRadius:i.lg,borderBottomRightRadius:i.xs,...ug(c.userBubble,um)},bubbleAssistant:c.assistantBubble?.backgroundColor===void 0?{...ug(c.assistantBubble,um)}:{paddingVertical:n.md,paddingHorizontal:n.lg+am,borderRadius:i.lg,...ug(c.assistantBubble,um)},bubbleVet:{maxWidth:sm,paddingVertical:n.md,paddingHorizontal:n.lg+am,backgroundColor:t.bubbleVet,borderRadius:i.lg,borderTopLeftRadius:i.xs,...ug(c.vetBubble,um)},bubbleCards:{maxWidth:Hm},bubbleUserCards:{paddingVertical:Um,paddingHorizontal:Nm},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*$m)},bubblePending:{opacity:fm},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:o,...dg(c.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:s,...dg(c.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:o,...dg(c.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:n.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:n.sm,marginBottom:n.xs},assistantAvatar:{width:Km,height:Km,borderRadius:Km/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:n.sm,marginBottom:n.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:n.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:Im,textTransform:"uppercase",letterSpacing:Pm,paddingBottom:n.sm,borderBottomWidth:Am,borderBottomColor:u},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Am,borderTopColor:u},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.md,minHeight:zm,paddingVertical:n.sm+am,...c.chip?.backgroundColor!==void 0||c.chip?.borderColor!==void 0?{paddingHorizontal:n.md}:{},...ug(c.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...dg(c.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,marginTop:n.md},askChip:{minHeight:im,maxWidth:"100%",justifyContent:"center",paddingVertical:n.sm,paddingHorizontal:n.lg,borderRadius:i.pill,borderWidth:Em,borderColor:t.brandInk,backgroundColor:t.chatGround,...ug(c.chip,Em)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*Om),...dg(c.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:n.md,marginTop:n.xs},composer:{marginHorizontal:n.md,marginTop:n.xs,minHeight:hm,justifyContent:"center",paddingLeft:n.sm,paddingRight:gm,paddingVertical:mm,backgroundColor:t.composerFill,borderWidth:pm,borderColor:t.composerBorder,borderRadius:i.pill,...ug(c.composerInput,pm)},composerRow:{flexDirection:"row",alignItems:"center",gap:n.xs,minHeight:bm},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:n.xs},attachControl:{width:jm,height:jm,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:Rm},input:{flex:1,minHeight:bm,maxHeight:lm,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...dg(c.composerInput)},sendControl:{minHeight:xm,minWidth:xm,alignItems:"center",justifyContent:"center"},sendDisc:{width:xm,height:xm,borderRadius:xm/2,alignItems:"center",justifyContent:"center",...ug(c.sendButton)},sendControlDisabled:{opacity:Sm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:n.xs}})}var Xm=18,Zm=28,Jm=6,eb=1200,tb=.4,rb=.4;function DictationButton({active:e,listening:n,elapsedMs:i,disabled:o=false,onToggle:s}){let a=useEverfurTheme(),u=t.useMemo(()=>nb(a),[a]);return t.useEffect(()=>{if(n)try{r.AccessibilityInfo.announceForAccessibility(Yd.listening)}catch{}},[n]),/* @__PURE__ */l.jsxs(r.View,{style:u.wrap,children:[n?/* @__PURE__ */l.jsx(Text,{style:u.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:bg(i)}):null,
140
- /* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>s(),disabled:o,accessibilityRole:"button",accessibilityLabel:e?Yd.stopDictation:Yd.dictate,accessibilityState:{selected:e,disabled:o},style:[u.button,o?u.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */l.jsxs(l.Fragment,{children:[
134
+ /* @__PURE__ */l.jsx(r.View,{style:a.tailFill})]})]})}function Kg(e){let t=e.color,n=e.radius;return r.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:n.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:$g,shadowRadius:Wg,shadowOffset:{width:0,height:qg},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Hg,borderRadius:n.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Ug,height:Ug,borderRadius:Ug/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-Vg/2,width:Vg,height:Vg,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Vg+4,height:2,backgroundColor:t.surfaceCream}})}var Yg=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Qg=56,Xg=12,Zg=14,Jg=10,em=.45,tm="rgba(7,193,104,0.55)",rm="rgba(185,28,28,0.55)",nm=200,im=300,lm=20,om=22,sm=12,am="rgba(0,0,0,0.78)",um=220,cm=100,dm="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:n,uploadFailed:i=false,onRetry:o,onRemove:s,onPreview:a,style:u}){let c=useEverfurTheme(),d=t.useMemo(()=>fm(c),[c]);return e.length===0&&n===null?null:/* @__PURE__ */l.jsxs(r.View,{style:[d.strip,u],children:[e.length>0?/* @__PURE__ */l.jsx(r.View,{style:d.cards,children:e.map(e=>/* @__PURE__ */l.jsx(PreviewCard,{row:e,styles:d,onRetry:o,onRemove:s,onPreview:a},e.id))}):null,i?/* @__PURE__ */l.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:df.attachmentsFailedBlocked}):null,n!==null?/* @__PURE__ */l.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:Rg(n)}):null]})}function PreviewCard({row:e,styles:n,onRetry:i,onRemove:o,onPreview:s}){let a=useEverfurTheme(),u=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=t.useRef(e.status),[h,p]=t.useState(false);return t.useEffect(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */l.jsxs(r.View,{style:n.card,children:[
135
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:d?"button":"image",accessibilityLabel:d?ff(df.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:u,disabled:!d},disabled:!d,style:n.thumbHit,onPress:()=>s(e),children:/* @__PURE__ */l.jsxs(r.View,{style:n.thumb,children:[
136
+ /* @__PURE__ */l.jsx(r.Image,{source:{uri:e.previewUri},style:n.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),u?/* @__PURE__ */l.jsx(r.View,{style:n.uploadingOverlay,children:/* @__PURE__ */l.jsx(r.ActivityIndicator,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */l.jsx(SuccessFlash,{styles:n,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:ff(df.retryUpload,{filename:e.filename}),style:n.failedOverlay,onPress:()=>i(e.id),children:/* @__PURE__ */l.jsx(r.View,{style:n.failedInner,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:lm,color:a.color.surface,strokeWidth:2})})}):null,
137
+ /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:ff(df.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:n.removeSlot,style:n.removeButton,onPress:()=>o(e.id),children:/* @__PURE__ */l.jsx(CloseGlyph,{size:sm,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:n}){let i=useEverfurTheme(),o=Qp(),s=t.useRef(null);s.current===null&&(s.current=new r.Animated.Value(0));let a=s.current;return t.useEffect(()=>{let e=r.Animated.sequence([r.Animated.timing(a,{toValue:1,duration:nm,useNativeDriver:true}),r.Animated.delay(o.uploadFlashMs),r.Animated.timing(a,{toValue:0,duration:im,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&n()}),()=>e.stop()},[a,o.uploadFlashMs,n]),/* @__PURE__ */l.jsx(r.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:a}],children:/* @__PURE__ */l.jsx(CheckGlyph,{size:lm,color:i.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:n}){let i=useEverfurTheme(),o=t.useMemo(()=>fm(i),[i]);if(e.length===0)return null;let s=e.length===1;/* @__PURE__ */
138
+ return l.jsx(r.View,{style:s?o.sentSingle:o.sentGrid,children:e.map((e,t)=>/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:ff(df.attachedImage,{filename:e.filename}),onPress:()=>n(e),children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e.uri},style:s?o.singleImage:o.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${t}`))})}function fm(e){let t=e.color,n=e.type;return r.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Qg,height:Qg,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Xg,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Yg,alignItems:"center",justifyContent:"center",backgroundColor:Ml(e.color.brandInk,em)??e.color.brandSofter},successOverlay:{...Yg,alignItems:"center",justifyContent:"center",backgroundColor:tm},failedOverlay:{...Yg,borderRadius:Xg,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:rm},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:om,height:om,borderRadius:om/2,backgroundColor:am,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:um,height:um,borderRadius:Zg,backgroundColor:dm},gridImage:{width:cm,height:cm,borderRadius:Jg,backgroundColor:dm}})}var hm="chat attachment upload: the file handle has no uri",pm="chat attachment upload failed";function gm(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
139
+ return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(hm));let{signal:i,onProgress:l}=n,o=()=>Promise.reject(new Error(pm));return i?.aborted===true?o():re({url:t.upload_url,fields:t.upload_fields,file:gm(r),signal:i,fetch:e.fetch}).then(e=>{if(!e)return o();l?.(1)},o)}})}var mm=300,bm=3e3,ym=120,vm=44,xm=120,wm="88%",km=520,Cm=2,Sm=.5,jm=1.5,_m=1.6,Rm=.6,Tm=56,Im=1.5,Pm=5,zm=5,Em=36,Om=20,Am=14,Mm=vm,Fm=4,Dm=24,Lm=22,Bm=.4,Vm=vm,Hm=20,Um=.4,Nm=480,$m=12,Wm=.72,qm=48,Gm=1.5,Km=1.3,Ym=1,Qm=1,Xm="12%",Zm=14,Jm=16,eb=28,tb=18,rb="84%",nb=10,ib=15,lb=1.42,ob=4,sb=3,ab=14,ub=20;function cb(){let e=useEverfurTheme(),r=t.useMemo(()=>db(e),[e]);return{theme:e,styles:r}}function db(e){let t=e.color,n=e.space,i=e.radius,l=e.type,o=Math.round(l.size.body*jm),s=Math.round(l.size.body*_m),a=Math.round(Om*l.size.body/Am),u=t.borderRingCream,c=e.slots;return r.StyleSheet.create({container:{flex:1,minHeight:ym,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:ym,flexGrow:1,alignItems:"center",justifyContent:"center",padding:n.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:Xm,paddingHorizontal:n.lg,paddingBottom:n.lg,minHeight:Nm,gap:n.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:n.md},retryButton:{minHeight:vm,minWidth:vm,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:i.pill,backgroundColor:t.brand,...Sg(c.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,..._g(c.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:n.xs,padding:n.md,borderRadius:i.md,backgroundColor:t.surfaceCream,borderWidth:Qm,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal},turnNoticeAction:{minHeight:vm,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:l.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:n.xs,paddingVertical:n.md,paddingHorizontal:n.md+n.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:i.md},readingDot:{width:6,height:6,borderRadius:i.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:sb,minHeight:ab},readingDotInline:{width:ob,height:ob,borderRadius:i.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:vm,justifyContent:"center",paddingHorizontal:n.md+n.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:n.lg,gap:n.xl},listContentCards:{paddingTop:Zm,paddingHorizontal:Jm,paddingBottom:eb,gap:tb},rowBlock:{gap:n.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:n.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:wm,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:km,paddingVertical:n.md,paddingHorizontal:n.lg+Cm,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:Sm,borderColor:t.primaryEdge}:{},borderRadius:i.lg,borderBottomRightRadius:i.xs,...Sg(c.userBubble,Sm)},bubbleAssistant:c.assistantBubble?.backgroundColor===void 0?{...Sg(c.assistantBubble,Sm)}:{paddingVertical:n.md,paddingHorizontal:n.lg+Cm,borderRadius:i.lg,...Sg(c.assistantBubble,Sm)},bubbleVet:{maxWidth:km,paddingVertical:n.md,paddingHorizontal:n.lg+Cm,backgroundColor:t.bubbleVet,borderRadius:i.lg,borderTopLeftRadius:i.xs,...Sg(c.vetBubble,Sm)},bubbleCards:{maxWidth:rb},bubbleUserCards:{paddingVertical:nb,paddingHorizontal:ib},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*lb)},bubblePending:{opacity:Rm},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:o,..._g(c.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:s,..._g(c.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:o,..._g(c.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:n.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:n.sm,marginBottom:n.xs},assistantAvatar:{width:ub,height:ub,borderRadius:ub/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:n.sm,marginBottom:n.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:n.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:$m,textTransform:"uppercase",letterSpacing:Wm,paddingBottom:n.sm,borderBottomWidth:Ym,borderBottomColor:u},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Ym,borderTopColor:u},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.md,minHeight:qm,paddingVertical:n.sm+Cm,...c.chip?.backgroundColor!==void 0||c.chip?.borderColor!==void 0?{paddingHorizontal:n.md}:{},...Sg(c.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,..._g(c.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,marginTop:n.md},askChip:{minHeight:vm,maxWidth:"100%",justifyContent:"center",paddingVertical:n.sm,paddingHorizontal:n.lg,borderRadius:i.pill,borderWidth:Gm,borderColor:t.brandInk,backgroundColor:t.chatGround,...Sg(c.chip,Gm)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*Km),..._g(c.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:n.md,marginTop:n.xs},composer:{marginHorizontal:n.md,marginTop:n.xs,minHeight:Tm,justifyContent:"center",paddingLeft:n.sm,paddingRight:Pm,paddingVertical:zm,backgroundColor:t.composerFill,borderWidth:Im,borderColor:t.composerBorder,borderRadius:i.pill,...Sg(c.composerInput,Im)},composerRow:{flexDirection:"row",alignItems:"center",gap:n.xs,minHeight:Em},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:n.xs},attachControl:{width:Vm,height:Vm,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:Um},input:{flex:1,minHeight:Em,maxHeight:xm,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,..._g(c.composerInput)},sendControl:{minHeight:Mm,minWidth:Mm,alignItems:"center",justifyContent:"center"},sendDisc:{width:Mm,height:Mm,borderRadius:Mm/2,alignItems:"center",justifyContent:"center",...Sg(c.sendButton)},sendControlDisabled:{opacity:Bm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:n.xs}})}var fb=18,hb=28,pb=6,gb=1200,mb=.4,bb=.4;function DictationButton({active:e,listening:n,elapsedMs:i,disabled:o=false,onToggle:s}){let a=useEverfurTheme(),u=t.useMemo(()=>yb(a),[a]);return t.useEffect(()=>{if(n)try{r.AccessibilityInfo.announceForAccessibility(df.listening)}catch{}},[n]),/* @__PURE__ */l.jsxs(r.View,{style:u.wrap,children:[n?/* @__PURE__ */l.jsx(Text,{style:u.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:Eg(i)}):null,
140
+ /* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>s(),disabled:o,accessibilityRole:"button",accessibilityLabel:e?df.stopDictation:df.dictate,accessibilityState:{selected:e,disabled:o},style:[u.button,o?u.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */l.jsxs(l.Fragment,{children:[
141
141
  /* @__PURE__ */l.jsx(Pulse,{style:u.pulse,reduced:a.motion.reducedMotion}),
142
- /* @__PURE__ */l.jsx(StopGlyph,{size:Zm,color:a.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */l.jsx(MicGlyph,{size:Xm,color:a.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:n}){let i=t.useRef(new r.Animated.Value(1)).current;return t.useEffect(()=>{if(n)return;let e=r.Animated.loop(r.Animated.sequence([r.Animated.timing(i,{toValue:tb,duration:eb/2,useNativeDriver:true}),r.Animated.timing(i,{toValue:1,duration:eb/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[i,n]),/* @__PURE__ */l.jsx(r.Animated.View,{style:[e,{opacity:i}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function nb(e){let t=e.color,n=e.type.tierSizes.compact.micro;return r.StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:n,lineHeight:n+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:im,height:im,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:rb},pulse:{position:"absolute",top:Jm,right:Jm,bottom:Jm,left:Jm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var ib=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function lb(){let e=globalThis,t=e[ib];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[ib]=r,r}function registerEverfurDictation(e){let t=lb();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function ob(){return lb().version??0}function sb(e){let t=lb(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function ab(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function ub(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function cb(){let e=lb();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||r.Platform.OS!=="ios"&&r.Platform.OS!=="android")return e.memo;let n=optionalModule("expo-speech-recognition",()=>({box:ub(t())}),e=>typeof e=="object"&&e!==null&&ab(e.box));return n.available&&(e.memo=n.module.box),e.memo}function db(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function fb(){try{return Intl.DateTimeFormat().resolvedOptions().locale||pb}catch{return pb}}function hb(e){return e.replace(/_/g,"-").toLowerCase()}var pb="en-US";function gb(e=fb()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return pb;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:pb}function mb(e,t){if(t.length===0)return null;let r=e=>t.find(t=>hb(t)===hb(e));return r(e)??r(pb)??t.find(e=>hb(e).startsWith("en-"))??null}async function bb(e,t){if(r.Platform.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return mb(t,r??[])??t}catch{return t}}async function yb(e,t){let n=false;try{n=e.supportsOnDeviceRecognition()===!0}catch{n=false}if(!n)return"network";if(r.Platform.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=hb(t);return(r??[]).some(e=>hb(e)===n)?"on_device":"network"}catch{return"network"}}function vb(){return r.Platform.OS!=="android"?true:Number(r.Platform.Version)>=xb}var xb=33;function wb(e,t,r){return{lang:t,interimResults:true,continuous:vb(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var kb=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),Cb=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Sb(e){return Cb.has(e)}var jb=600,_b=3;function Rb(e,t,r){if(kb.has(r))return null;let n=Sb(r)?jb:0;return r==="language-not-supported"&&hb(t)!==hb(pb)?{mode:"network",lang:pb,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Tb(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Ib(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Pb=55e3,zb=3e3,Eb=1e3;function Ob(e){return Ab.has(e)||Sb(e)}var Ab=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),Mb=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function Fb(e){return e.replace(/\s+/g," ").trim()}function Db(e,t,r){let n=Fb(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Lb(e){return Fb([...e.committed,e.interim].join(" "))}function Bb(e,t,r,n=Date.now){let i=0,l=null,o=Number.NEGATIVE_INFINITY,s=e=>l!==null&&l.token===e?l:null;function a(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){a(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,l===e&&(l=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Lb(e.transcript)===""&&e.launchedAt-o<Eb}function d(e){return e.mode??"none"}function f(e,t){vg(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){vg(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(s(e.token)===null)return;u(e);let r=Lb(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Ob(n))){h(e,Tb(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(i){i.subscriptions=[e.addListener("start",()=>{s(i.token)!==null&&(i.sawStart=true,i.startedAt===null&&(i.startedAt=n()),vg(r(),"chat_dictation_started",{mode:d(i)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(s(i.token)===null)return;let r=e?.results?.[0]?.transcript??"";i.transcript=Db(i.transcript,r,e?.isFinal===true),t.onText(Lb(i.transcript))}),e.addListener("error",e=>{if(s(i.token)===null)return;let t=e?.error??"unknown";if(i.userStopped&&(t==="aborted"||Sb(t)))return;let r=Lb(i.transcript)==="",n=i.mode!==null&&!i.userStopped&&r&&i.retries<_b?Rb(i.mode,i.lang,t):null;if(n!==null){i.pendingRetry=n;return}i.errorCode===null&&(i.errorCode=t)}),e.addListener("end",()=>{if(s(i.token)!==null&&!c(i)){if(i.pendingRetry!==null){let e=i.pendingRetry;if(i.pendingRetry=null,i.retries+=1,i.lang=e.lang,e.delayMs<=0){m(i,e.mode);return}a(i),i.retryTimer=setTimeout(()=>{i.retryTimer=null,!(s(i.token)===null||i.userStopped)&&m(i,e.mode)},e.delayMs);return}p(i)}})]}function m(t,r){a(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=Mb,t.errorCode=null,g(t);try{e.start(wb(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function b(t){let r=await Ib(e);if(s(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await bb(e,t.lang),s(t.token)===null)return;let n=await yb(e,t.lang);s(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Pb),m(t,n))}function y(r){if(!(s(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),zb);try{e.stop()}catch{p(r)}}}return{start(e){if(l!==null)return;let r={token:++i,phrases:e,lang:gb(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:Mb,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};l=r,t.onStatus("starting"),b(r)},stop(){l!==null&&y(l)},cancel(){let r=l;if(r===null)return;let i=r.mode!==null&&r.retryTimer===null,s=Lb(r.transcript);if(u(r),t.onStatus("idle"),!!i){s&&f(r,s),o=n();try{e.abort()}catch{}}},isActive:()=>l!==null,isPreparing:()=>l!==null&&l.mode===null}}function Vb({enabled:e,input:n,setInput:i,phrases:l,maxLength:o,telemetry:s}){let a=t.useSyncExternalStore(sb,ob,ob),u=t.useMemo(()=>e?cb():null,[e,a]),c=t.useMemo(()=>db(u),[u]),[d,f]=t.useState("idle"),[h,p]=t.useState(null),[g,m]=t.useState(0),b=t.useRef(n);b.current=n;let y=t.useRef(i);y.current=i;let v=t.useRef(s);v.current=s;let x=t.useRef(""),w=t.useRef(o);w.current=o;let k=t.useRef(null);u!==null&&k.current?.mod!==u&&(k.current?.controller.cancel(),k.current={mod:u,controller:Bb(u,{onStatus:e=>{f(t=>e==="idle"&&t==="error"?t:e)},onText:e=>y.current(mg(x.current,e,w.current)),onError:e=>{p(e),f("error")}},()=>v.current)});let C=u===null?null:k.current?.controller??null,S=t.useCallback(()=>{C?.cancel()},[C]),j=t.useCallback(()=>{if(C!==null){if(C.isActive()){C.stop();return}p(null),m(0),x.current=b.current,C.start(l)}},[C,l]);t.useEffect(()=>{if(d!=="listening")return;let e=Date.now();m(0);let t=setInterval(()=>m(Date.now()-e),1e3);return()=>clearInterval(t)},[d]),t.useEffect(()=>{if(d!=="error")return;let e=setTimeout(()=>{p(null),f("idle")},gg);return()=>clearTimeout(e)},[d]),t.useEffect(()=>{if(C===null)return;let e=null;try{e=r.AppState.addEventListener("change",e=>{e==="background"&&!C.isPreparing()&&C.cancel()})}catch{}return()=>{e?.remove(),C.cancel()}},[C]);let _=e&&c;return t.useEffect(()=>{_||C?.cancel()},[_,C]),{supported:_,status:d,active:d==="starting"||d==="listening",error:h,elapsedMs:g,toggle:j,cancel:S}}var Hb=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function Ub(){let e=globalThis,r=e[Hb];if(r!==void 0)return r;let n=t.createContext(true);return e[Hb]=n,n}var Nb=Ub();function $b(){return t.useContext(Nb)}var Wb=/* @__PURE__ */Object.freeze(["photo"]),qb=52,Gb=1.5,Kb=10,Yb=14,Qb=10,Xb=40,Zb=20,Jb=.3,ey=2.5,ty=1,ry=1.5,ny=38,iy=22,ly=3;function oy(e,t,r,n="ask",i=false){let l=typeof t=="string"&&t.trim()!=="";return r&&l&&n!=="urgent"?Zd(Yd.placeholder,t):e!==null?!i||!e.includes("{pet}")?e:l?e.split("{pet}").join(t.trim()):Zd(Yd.placeholder,t):n==="urgent"?Yd.placeholderUrgentWeb:n==="followUp"?Yd.placeholderFollowUpWeb:Zd(Yd.placeholder,t)}function ComposerWithAttachments({attachments:e,...r}){let n=t.useMemo(()=>createRnChatAttachmentTransport(),[]),i=useChatAttachments({maxPerMessage:e.maxPerMessage??An,transport:n}),o=t.useMemo(()=>({state:i,sources:e.sources??Wb,pick:e.pick}),[i,e.sources,e.pick]);/* @__PURE__ */
143
- return l.jsx(Composer,{...r,attachments:o})}function Composer({send:e,stop:n,isStreaming:i,conversationId:o,attachments:s,seed:a,draftStore:u,onStage:c,onPreview:d,petName:f,petBreed:h=null,mood:p="ask",dictation:g=false,telemetry:m=null,compact:b=false,petPlaceholder:y=false,dimEmptySend:v=false}){let{theme:x,styles:w}=Ym(),k=t.useMemo(()=>fy(x),[x]),C=t.useMemo(()=>hy(x),[x]),S=Mp(),[j,_]=kg(e,o,a),[R,T]=t.useState(false),[I,P]=t.useState(false),z=t.useCallback(()=>P(true),[]),E=t.useCallback(()=>P(false),[]),[O,A]=t.useState(false);t.useEffect(()=>{A(false)},[o]);let M=oy(x.meta.placeholder,f,y,p,x.meta.placeholderFillsPet===true),F=t.useMemo(()=>wg({name:f,breed:h}),[f,h]),D=Vb({enabled:g,input:j,setInput:_,phrases:F,maxLength:fn,telemetry:m}),L=D.cancel,B=D.active;Cg(u,o===null?null:String(o),j,_,B);let V=t.useRef(o);t.useEffect(()=>{V.current!==o&&(V.current=o,L())},[o,L]);let H=$b();t.useEffect(()=>{H||L()},[H,L]);let U=s?.state.uploading??false,N=s?.state.failed??false,$=U||N,W=s?.state.attachments??sy;Zp(W.length,S);let q=t.useCallback(()=>{let t=j.trim();if(t.length===0||$||[...t].length>fn)return;B&&L();let r=s?.state.s3Keys??ay;s!==null&&r.length>0?(c(s.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),s.state.clear()):e(t),_(""),A(false)},[j,e,$,B,L,s,c]),G=t.useCallback(e=>{B&&L(),_(e)},[B,L,_]),K=t.useCallback(()=>{n()},[n]),Y=t.useCallback(e=>{T(false),s!==null&&(A(false),s.state.dismissRejected(),$f(s.pick,e).then(e=>{if(!e.ok){A(true);return}e.value!==null&&s.state.add(e.value)}))},[s]),Q=t.useMemo(()=>[...j.trim()].length>fn,[j]),X=Q||$||j.trim().length===0,Z=Q||$||v&&j.trim().length===0,J=s!==null&&W.length>=s.state.maxPerMessage,ee=x.slots.sendButton?.textColor??x.color.brandInk,te=x.slots.sendButton?.textColor??x.color.surface;/* @__PURE__ */
144
- return l.jsxs(r.View,{style:w.composerOuter,children:[s!==null&&R?/* @__PURE__ */l.jsx(AttachmentPickerPopover,{sources:s.sources,full:J,onPick:Y,onClose:()=>T(false)}):null,s!==null?/* @__PURE__ */l.jsx(AttachmentStrip,{attachments:W,rejected:O?dy:s.state.rejected,uploadFailed:N,onRetry:s.state.retry,onRemove:s.state.remove,onPreview:e=>d({uri:e.previewUri,label:e.filename}),style:b?k.tray:C.tray}):null,
142
+ /* @__PURE__ */l.jsx(StopGlyph,{size:hb,color:a.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */l.jsx(MicGlyph,{size:fb,color:a.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:n}){let i=t.useRef(new r.Animated.Value(1)).current;return t.useEffect(()=>{if(n)return;let e=r.Animated.loop(r.Animated.sequence([r.Animated.timing(i,{toValue:mb,duration:gb/2,useNativeDriver:true}),r.Animated.timing(i,{toValue:1,duration:gb/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[i,n]),/* @__PURE__ */l.jsx(r.Animated.View,{style:[e,{opacity:i}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function yb(e){let t=e.color,n=e.type.tierSizes.compact.micro;return r.StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:n,lineHeight:n+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:vm,height:vm,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:bb},pulse:{position:"absolute",top:pb,right:pb,bottom:pb,left:pb,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var vb=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function xb(){let e=globalThis,t=e[vb];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[vb]=r,r}function registerEverfurDictation(e){let t=xb();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function wb(){return xb().version??0}function kb(e){let t=xb(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Cb(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Sb(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function jb(){let e=xb();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||r.Platform.OS!=="ios"&&r.Platform.OS!=="android")return e.memo;let n=optionalModule("expo-speech-recognition",()=>({box:Sb(t())}),e=>typeof e=="object"&&e!==null&&Cb(e.box));return n.available&&(e.memo=n.module.box),e.memo}function _b(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Rb(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Ib}catch{return Ib}}function Tb(e){return e.replace(/_/g,"-").toLowerCase()}var Ib="en-US";function Pb(e=Rb()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Ib;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Ib}function zb(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Tb(t)===Tb(e));return r(e)??r(Ib)??t.find(e=>Tb(e).startsWith("en-"))??null}async function Eb(e,t){if(r.Platform.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return zb(t,r??[])??t}catch{return t}}async function Ob(e,t){let n=false;try{n=e.supportsOnDeviceRecognition()===!0}catch{n=false}if(!n)return"network";if(r.Platform.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Tb(t);return(r??[]).some(e=>Tb(e)===n)?"on_device":"network"}catch{return"network"}}function Ab(){return r.Platform.OS!=="android"?true:Number(r.Platform.Version)>=Mb}var Mb=33;function Fb(e,t,r){return{lang:t,interimResults:true,continuous:Ab(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Db=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),Lb=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Bb(e){return Lb.has(e)}var Vb=600,Hb=3;function Ub(e,t,r){if(Db.has(r))return null;let n=Bb(r)?Vb:0;return r==="language-not-supported"&&Tb(t)!==Tb(Ib)?{mode:"network",lang:Ib,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Nb(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function $b(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Wb=55e3,qb=3e3,Gb=1e3;function Kb(e){return Yb.has(e)||Bb(e)}var Yb=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),Qb=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function Xb(e){return e.replace(/\s+/g," ").trim()}function Zb(e,t,r){let n=Xb(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Jb(e){return Xb([...e.committed,e.interim].join(" "))}function ey(e,t,r,n=Date.now){let i=0,l=null,o=Number.NEGATIVE_INFINITY,s=e=>l!==null&&l.token===e?l:null;function a(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){a(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,l===e&&(l=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Jb(e.transcript)===""&&e.launchedAt-o<Gb}function d(e){return e.mode??"none"}function f(e,t){Ag(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Ag(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(s(e.token)===null)return;u(e);let r=Jb(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Kb(n))){h(e,Nb(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(i){i.subscriptions=[e.addListener("start",()=>{s(i.token)!==null&&(i.sawStart=true,i.startedAt===null&&(i.startedAt=n()),Ag(r(),"chat_dictation_started",{mode:d(i)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(s(i.token)===null)return;let r=e?.results?.[0]?.transcript??"";i.transcript=Zb(i.transcript,r,e?.isFinal===true),t.onText(Jb(i.transcript))}),e.addListener("error",e=>{if(s(i.token)===null)return;let t=e?.error??"unknown";if(i.userStopped&&(t==="aborted"||Bb(t)))return;let r=Jb(i.transcript)==="",n=i.mode!==null&&!i.userStopped&&r&&i.retries<Hb?Ub(i.mode,i.lang,t):null;if(n!==null){i.pendingRetry=n;return}i.errorCode===null&&(i.errorCode=t)}),e.addListener("end",()=>{if(s(i.token)!==null&&!c(i)){if(i.pendingRetry!==null){let e=i.pendingRetry;if(i.pendingRetry=null,i.retries+=1,i.lang=e.lang,e.delayMs<=0){m(i,e.mode);return}a(i),i.retryTimer=setTimeout(()=>{i.retryTimer=null,!(s(i.token)===null||i.userStopped)&&m(i,e.mode)},e.delayMs);return}p(i)}})]}function m(t,r){a(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=Qb,t.errorCode=null,g(t);try{e.start(Fb(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function b(t){let r=await $b(e);if(s(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Eb(e,t.lang),s(t.token)===null)return;let n=await Ob(e,t.lang);s(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Wb),m(t,n))}function y(r){if(!(s(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),qb);try{e.stop()}catch{p(r)}}}return{start(e){if(l!==null)return;let r={token:++i,phrases:e,lang:Pb(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:Qb,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};l=r,t.onStatus("starting"),b(r)},stop(){l!==null&&y(l)},cancel(){let r=l;if(r===null)return;let i=r.mode!==null&&r.retryTimer===null,s=Jb(r.transcript);if(u(r),t.onStatus("idle"),!!i){s&&f(r,s),o=n();try{e.abort()}catch{}}},isActive:()=>l!==null,isPreparing:()=>l!==null&&l.mode===null}}function ty({enabled:e,input:n,setInput:i,phrases:l,maxLength:o,telemetry:s}){let a=t.useSyncExternalStore(kb,wb,wb),u=t.useMemo(()=>e?jb():null,[e,a]),c=t.useMemo(()=>_b(u),[u]),[d,f]=t.useState("idle"),[h,p]=t.useState(null),[g,m]=t.useState(0),b=t.useRef(n);b.current=n;let y=t.useRef(i);y.current=i;let v=t.useRef(s);v.current=s;let x=t.useRef(""),w=t.useRef(o);w.current=o;let k=t.useRef(null);u!==null&&k.current?.mod!==u&&(k.current?.controller.cancel(),k.current={mod:u,controller:ey(u,{onStatus:e=>{f(t=>e==="idle"&&t==="error"?t:e)},onText:e=>y.current(zg(x.current,e,w.current)),onError:e=>{p(e),f("error")}},()=>v.current)});let C=u===null?null:k.current?.controller??null,S=t.useCallback(()=>{C?.cancel()},[C]),j=t.useCallback(()=>{if(C!==null){if(C.isActive()){C.stop();return}p(null),m(0),x.current=b.current,C.start(l)}},[C,l]);t.useEffect(()=>{if(d!=="listening")return;let e=Date.now();m(0);let t=setInterval(()=>m(Date.now()-e),1e3);return()=>clearInterval(t)},[d]),t.useEffect(()=>{if(d!=="error")return;let e=setTimeout(()=>{p(null),f("idle")},Pg);return()=>clearTimeout(e)},[d]),t.useEffect(()=>{if(C===null)return;let e=null;try{e=r.AppState.addEventListener("change",e=>{e==="background"&&!C.isPreparing()&&C.cancel()})}catch{}return()=>{e?.remove(),C.cancel()}},[C]);let _=e&&c;return t.useEffect(()=>{_||C?.cancel()},[_,C]),{supported:_,status:d,active:d==="starting"||d==="listening",error:h,elapsedMs:g,toggle:j,cancel:S}}var ry=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function ny(){let e=globalThis,r=e[ry];if(r!==void 0)return r;let n=t.createContext(true);return e[ry]=n,n}var iy=ny();function ly(){return t.useContext(iy)}var oy=/* @__PURE__ */Object.freeze(["photo"]),sy=52,ay=1.5,uy=10,cy=14,dy=10,fy=40,hy=20,py=.3,gy=2.5,my=1,by=1.5,yy=38,vy=22,xy=3;function wy(e,t,r,n="ask",i=false){let l=typeof t=="string"&&t.trim()!=="";return r&&l&&n!=="urgent"?pf(df.placeholder,t):e!==null?!i||!e.includes("{pet}")?e:l?e.split("{pet}").join(t.trim()):pf(df.placeholder,t):n==="urgent"?df.placeholderUrgentWeb:n==="followUp"?df.placeholderFollowUpWeb:pf(df.placeholder,t)}function ComposerWithAttachments({attachments:e,...r}){let n=t.useMemo(()=>createRnChatAttachmentTransport(),[]),i=useChatAttachments({maxPerMessage:e.maxPerMessage??Dn,transport:n}),o=t.useMemo(()=>({state:i,sources:e.sources??oy,pick:e.pick}),[i,e.sources,e.pick]);/* @__PURE__ */
143
+ return l.jsx(Composer,{...r,attachments:o})}function Composer({send:e,stop:n,isStreaming:i,conversationId:o,attachments:s,seed:a,draftStore:u,onStage:c,onPreview:d,petName:f,petBreed:h=null,mood:p="ask",dictation:g=false,telemetry:m=null,compact:b=false,petPlaceholder:y=false,dimEmptySend:v=false}){let{theme:x,styles:w}=cb(),k=t.useMemo(()=>Ry(x),[x]),C=t.useMemo(()=>Ty(x),[x]),S=Qp(),[j,_]=Dg(e,o,a),[R,T]=t.useState(false),[I,P]=t.useState(false),z=t.useCallback(()=>P(true),[]),E=t.useCallback(()=>P(false),[]),[O,A]=t.useState(false);t.useEffect(()=>{A(false)},[o]);let M=wy(x.meta.placeholder,f,y,p,x.meta.placeholderFillsPet===true),F=t.useMemo(()=>Fg({name:f,breed:h}),[f,h]),D=ty({enabled:g,input:j,setInput:_,phrases:F,maxLength:gn,telemetry:m}),L=D.cancel,B=D.active;Lg(u,o===null?null:String(o),j,_,B);let V=t.useRef(o);t.useEffect(()=>{V.current!==o&&(V.current=o,L())},[o,L]);let H=ly();t.useEffect(()=>{H||L()},[H,L]);let U=s?.state.uploading??false,N=s?.state.failed??false,$=U||N,W=s?.state.attachments??ky;hg(W.length,S);let q=t.useCallback(()=>{let t=j.trim();if(t.length===0||$||[...t].length>gn)return;B&&L();let r=s?.state.s3Keys??Cy;s!==null&&r.length>0?(c(s.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),s.state.clear()):e(t),_(""),A(false)},[j,e,$,B,L,s,c]),G=t.useCallback(e=>{B&&L(),_(e)},[B,L,_]),K=t.useCallback(()=>{n()},[n]),Y=t.useCallback(e=>{T(false),s!==null&&(A(false),s.state.dismissRejected(),lh(s.pick,e).then(e=>{if(!e.ok){A(true);return}e.value!==null&&s.state.add(e.value)}))},[s]),Q=t.useMemo(()=>[...j.trim()].length>gn,[j]),X=Q||$||j.trim().length===0,Z=Q||$||v&&j.trim().length===0,J=s!==null&&W.length>=s.state.maxPerMessage,ee=x.slots.sendButton?.textColor??x.color.brandInk,te=x.slots.sendButton?.textColor??x.color.surface;/* @__PURE__ */
144
+ return l.jsxs(r.View,{style:w.composerOuter,children:[s!==null&&R?/* @__PURE__ */l.jsx(AttachmentPickerPopover,{sources:s.sources,full:J,onPick:Y,onClose:()=>T(false)}):null,s!==null?/* @__PURE__ */l.jsx(AttachmentStrip,{attachments:W,rejected:O?_y:s.state.rejected,uploadFailed:N,onRetry:s.state.retry,onRemove:s.state.remove,onPreview:e=>d({uri:e.previewUri,label:e.filename}),style:b?k.tray:C.tray}):null,
145
145
  /* @__PURE__ */l.jsxs(r.View,{style:b?[w.composer,k.bar,I?k.barFocused:null]:w.composer,children:[D.supported&&D.error!==null?/* @__PURE__ */l.jsxs(l.Fragment,{children:[
146
- /* @__PURE__ */l.jsx(Text,{style:w.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:yg(D.error)}),
147
- /* @__PURE__ */l.jsx(AnnounceLine,{line:yg(D.error)})]}):null,
148
- /* @__PURE__ */l.jsxs(r.View,{style:w.composerRow,children:[s!==null?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:J?hg(W.length,s.state.maxPerMessage):Yd.attachPhotoOrFileNative,accessibilityState:{disabled:J,expanded:R},disabled:J,style:[w.attachControl,b?k.add:null,J?w.attachControlDisabled:null],hitSlop:b?ly:void 0,onPress:()=>T(e=>!e),children:/* @__PURE__ */l.jsx(UploadGlyph,{size:b?iy:_m,color:J?x.color.text.muted:b?x.color.text.primary:x.color.brandInk,strokeWidth:1.75})}):null,
149
- /* @__PURE__ */l.jsx(Td,{style:b?[w.input,k.input]:w.input,onFocus:z,onBlur:E,value:j,onChangeText:G,placeholder:M,placeholderTextColor:x.slots.composerInput?.textColor??x.color.text.placeholder,accessibilityLabel:Yd.composerLabel,onSubmitEditing:q,returnKeyType:"send",...uy,...b?cy:null,blurOnSubmit:false,multiline:true,editable:true}),D.supported?/* @__PURE__ */l.jsx(DictationButton,{active:D.active,listening:D.status==="listening",elapsedMs:D.elapsedMs,onToggle:D.toggle}):null,i?/* @__PURE__ */l.jsx(r.Pressable,{onPress:K,accessibilityRole:"button",accessibilityLabel:Yd.stop,style:w.sendControl,children:/* @__PURE__ */l.jsx(r.View,{style:b?k.disc:w.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */l.jsx(StopGlyph,{size:b?Zb:Cm,color:b?te:ee,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */l.jsx(r.Pressable,{onPress:q,disabled:X,accessibilityRole:"button",accessibilityLabel:Yd.send,accessibilityState:{disabled:X,busy:U},style:[w.sendControl,Z?b?k.dimmed:w.sendControlDisabled:null],children:b?/* @__PURE__ */l.jsx(r.View,{style:k.disc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(ArrowUpGlyph,{size:Zb,color:te,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */l.jsx(r.View,{style:w.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(SendGlyph,{size:km,color:ee,testID:"everfur-send-glyph"})})})]})]})]})}var sy=/* @__PURE__ */Object.freeze([]),ay=/* @__PURE__ */Object.freeze([]),uy=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),cy=/* @__PURE__ */Object.freeze(r.Platform.OS==="web"?{rows:1}:{}),dy=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function fy(e){let t=e.color,n=e.slots.sendButton,i=textRole(e,"body").fontSize+ty;return r.StyleSheet.create({bar:{marginTop:Kb,marginHorizontal:Yb,marginBottom:Qb,minHeight:qb,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Gb,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:ey,paddingLeft:8-(ey-Gb),paddingRight:6-(ey-Gb)},input:{fontSize:i,lineHeight:Math.round(i*ry),minHeight:Math.round(i*ry),...r.Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:ny,height:ny,borderRadius:ny/2},disc:{width:Xb,height:Xb,borderRadius:Xb/2,alignItems:"center",justifyContent:"center",backgroundColor:n?.backgroundColor??t.text.primary,...ug(n)},dimmed:{opacity:Jb},tray:{marginHorizontal:Yb,marginTop:Kb,paddingBottom:0}})}function hy(e){return r.StyleSheet.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:r,activePet:n,scopeEpoch:i}=Lc(),l=t.useMemo(()=>createPetsRepository(e.registry.services.authFor(r)),[e,r,i]),[o,s]=t.useState({repository:l,pets:[],loading:true,error:null}),a=o.repository===l?o:{pets:[],loading:true,error:null},u=t.useRef(0),c=t.useCallback(async()=>{let e=++u.current;s(e=>({...e,repository:l,loading:true,error:null,pets:e.repository===l?e.pets:[]}));let t=await l.list();e===u.current&&s(t.ok?{repository:l,pets:t.value,loading:false,error:null}:e=>({repository:l,pets:e.repository===l?e.pets:[],loading:false,error:t.error}))},[l]);t.useEffect(()=>(c(),()=>{u.current+=1}),[c]),t.useEffect(()=>al(e,()=>{c()}),[e,c]);let d=t.useMemo(()=>n===null?null:a.pets.find(e=>e.petRef===n)??null,[n,a.pets]);return t.useMemo(()=>({pets:a.pets,activePet:d,loading:a.loading,error:a.error,refresh:c}),[a.pets,a.loading,a.error,d,c])}function py(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var gy=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var my=false;function by(e,t){return t!==void 0?(Hf(t,e),"onStartInApp"):Dd(e)==="presented"?"presenter":Hd(e)?"experience":(my||(my=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var yy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&yy.includes(e)}var vy="/widget/v1/televet/handoffs",xy="/widget/v1/televet/availability",wy="/widget/v1/televet/chat-entry",ky=/^[a-z0-9][a-z0-9_-]{0,39}$/,Cy=/^[A-Za-z0-9_-]{22}$/;var Sy=32,jy=128,_y=64;function vetVisitErrorReasonOf(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"}function Ry(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Ty(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Iy(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!ky.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let i=t?.entry;if(i!=null){if(i!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=i}let l=t?.visitRef,o=t?.intent,s=l!=null;if(s){let e=typeof l=="string"?l.trim():"";if(e.length<1||[...e].length>_y)return{ok:false,message:`visitRef must be 1..${_y} characters`};r.visit_ref=e}if(o!=null){if(!s)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${yy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Py(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function zy(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Dy(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,i){let l;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>jy)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${jy} characters`}));l=e}let o=Iy(l,i);if(!o.ok){let e=Ry(o.message);return e.ok?e:n(e.error)}let s=o.body,a=await t.send("televet.visit.handoff",{method:"POST",path:vy,body:s},{idempotent:false,maxAttempts:1});if(!a.ok)return n(a.error);let u=Ey(a.value),c=s.return_to!==void 0,d=c?a.value?.flow_id:void 0;if(c&&(typeof d!="string"||!Cy.test(d))){let e=Ty("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=s.visit_ref!==void 0,h=f?Py(a.value?.visit):null;if(f&&h===null){let e=Ty("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Dy(r,"televet.visit.handoff_created",{pet_scoped:s.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Sy)return Ry(`state must be at most ${Sy} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:xy,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Ty("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:wy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function Ey(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||!Fy(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Oy=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Ay=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,My=/[\s\u0000-\u001f\u007f]/;function Fy(e){if(My.test(e))return false;let t=Ay.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let i=n.replace(/:\d+$/,"").toLowerCase(),l=r==="https",o=r==="http"&&Oy.has(i);if(!l&&!o)return false;let s=e.indexOf("#");if(s<0)return false;let a=e.slice(s);return a.startsWith("#h=")&&a.length>3}function Dy(e,t,r){if(e)try{e.track(t,r)}catch{}}var Ly=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function By(e,r,n){let{usState:i,chat:l,scope:o}=n,s=r&&(i!==null||l),a=`${i??""}|${l?"chat":""}`,[u,c]=t.useState(null);if(t.useEffect(()=>{if(!s)return;let t=true,r=e.current;return c(null),(async()=>{try{if(l&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&c({key:a,open:e})}),()=>{t=false}},[s,a,i,l,o,e]),!s)return null;let d=u!==null&&u.key===a;return{open:d&&u.open,pending:!d}}var Vy=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Hy(e,r={}){let{runtime:n,userRef:i,scopeEpoch:l}=Lc(),o=useCapability("televet"),s=o.enabled&&i!==null,a=r.usState??null,u=r.entry==="chat",c=r.petRef??null,d=r.prefer==="redirect",f=t.useMemo(()=>{if(r.controller)return r.controller;let{services:e}=n.registry;return zy({auth:e.authFor(i),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[n,i,l,r.controller]),h=t.useRef(f);h.current=f;let p=t.useMemo(()=>({runtime:n,userRef:i,scopeEpoch:l}),[n,i,l]),g=By(h,s,{usState:a,chat:u,scope:p}),m=s&&(g===null||g.open)&&(!u||c!==null),b=r.returnTo??null,[y,v]=t.useState(Ly),x=t.useRef(null),w=t.useRef({runtime:n,userRef:i,scopeEpoch:l});w.current={runtime:n,userRef:i,scopeEpoch:l};let k=t.useRef(f);k.current=f;let C=t.useRef(m);C.current=m;let S=t.useCallback((t,r)=>{if(x.current)return x.current;let n=(e,t)=>(v({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!C.current)return Promise.resolve(n("unavailable",null));let i=e.prepare();if(!i.ok)return Promise.resolve(n(i.reason,null));let l=w.current,o=k.current;v(Vy);let s=(async()=>{let s,a={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},d=Object.keys(a).length===0?void 0:a,f=t===void 0?c:t;try{s=await(d===void 0?o.createHandoff(f):o.createHandoff(f,d))}catch{return e.abandon(i.value),n("unknown",null)}let h=w.current;if(h.runtime!==l.runtime||h.userRef!==l.userRef||h.scopeEpoch!==l.scopeEpoch)return e.abandon(i.value),n("cancelled",null);if(!s.ok)return e.abandon(i.value),n(vetVisitErrorReasonOf(s.error),s.error);let p=await e.finish(i.value,s.value);return p!==null?n(p,null):(v(Ly),/* @__PURE__ */Object.freeze(s.value.flowId===void 0?{opened:true}:{opened:true,flowId:s.value.flowId}))})().finally(()=>{x.current===s&&(x.current=null)});return x.current=s,s},[e,c,b,u]),j=t.useCallback((e,t)=>{if(!C.current)return v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?c:e,n={...r!==null?{petRef:r}:{},...a!==null?{usState:a}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return by(n)===null?(v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(v(Ly),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[c,a]),_=t.useCallback(e=>d?S(e,null):j(e,null),[d,S,j]),R=t.useCallback((e,t)=>d?S(void 0,{visitRef:e,intent:t??null}):j(void 0,{visitRef:e,intent:t??null}),[d,S,j]),T=t.useCallback(e=>d?S(void 0,null):j(void 0,{consultId:e.trim()}),[d,S,j]);return{available:m,isPending:o.isPending||(g?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:_,openVisit:R,joinVisit:T}}var Uy=e=>r.Linking.openURL(e);function useVetVisit(e={}){let{openUrl:r,...n}=e,i=t.useMemo(()=>{let e=r??Uy;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[r]);return Hy(i,n)}var Ny=44,$y=.6;function VetVisitButtonCore(e){let{petRef:n,label:i,openUrl:o,onOpened:s,onError:a,style:u,labelStyle:c,controller:d,returnTo:f,usState:h,entry:p,visitRef:g,intent:m,onStartInApp:b,prefer:y}=e,v=y==="redirect",x=useVetVisit({...f!==void 0?{returnTo:f}:{},...h!==void 0?{usState:h}:{},...p!==void 0?{entry:p}:{},...n!==void 0?{petRef:n}:{},...o!==void 0?{openUrl:o}:{},...d!==void 0?{controller:d}:{},prefer:v?"redirect":"in-app"}),w=useEverfurTheme(),k=t.useMemo(()=>Wy(w),[w]),C=t.useRef(false);if(!x.available)/* @__PURE__ */
146
+ /* @__PURE__ */l.jsx(Text,{style:w.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Og(D.error)}),
147
+ /* @__PURE__ */l.jsx(AnnounceLine,{line:Og(D.error)})]}):null,
148
+ /* @__PURE__ */l.jsxs(r.View,{style:w.composerRow,children:[s!==null?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:J?Tg(W.length,s.state.maxPerMessage):df.attachPhotoOrFileNative,accessibilityState:{disabled:J,expanded:R},disabled:J,style:[w.attachControl,b?k.add:null,J?w.attachControlDisabled:null],hitSlop:b?xy:void 0,onPress:()=>T(e=>!e),children:/* @__PURE__ */l.jsx(UploadGlyph,{size:b?vy:Hm,color:J?x.color.text.muted:b?x.color.text.primary:x.color.brandInk,strokeWidth:1.75})}):null,
149
+ /* @__PURE__ */l.jsx(zd,{style:b?[w.input,k.input]:w.input,onFocus:z,onBlur:E,value:j,onChangeText:G,placeholder:M,placeholderTextColor:x.slots.composerInput?.textColor??x.color.text.placeholder,accessibilityLabel:df.composerLabel,onSubmitEditing:q,returnKeyType:"send",...Sy,...b?jy:null,blurOnSubmit:false,multiline:true,editable:true}),D.supported?/* @__PURE__ */l.jsx(DictationButton,{active:D.active,listening:D.status==="listening",elapsedMs:D.elapsedMs,onToggle:D.toggle}):null,i?/* @__PURE__ */l.jsx(r.Pressable,{onPress:K,accessibilityRole:"button",accessibilityLabel:df.stop,style:w.sendControl,children:/* @__PURE__ */l.jsx(r.View,{style:b?k.disc:w.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */l.jsx(StopGlyph,{size:b?hy:Lm,color:b?te:ee,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */l.jsx(r.Pressable,{onPress:q,disabled:X,accessibilityRole:"button",accessibilityLabel:df.send,accessibilityState:{disabled:X,busy:U},style:[w.sendControl,Z?b?k.dimmed:w.sendControlDisabled:null],children:b?/* @__PURE__ */l.jsx(r.View,{style:k.disc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(ArrowUpGlyph,{size:hy,color:te,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */l.jsx(r.View,{style:w.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(SendGlyph,{size:Dm,color:ee,testID:"everfur-send-glyph"})})})]})]})]})}var ky=/* @__PURE__ */Object.freeze([]),Cy=/* @__PURE__ */Object.freeze([]),Sy=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),jy=/* @__PURE__ */Object.freeze(r.Platform.OS==="web"?{rows:1}:{}),_y=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Ry(e){let t=e.color,n=e.slots.sendButton,i=textRole(e,"body").fontSize+my;return r.StyleSheet.create({bar:{marginTop:uy,marginHorizontal:cy,marginBottom:dy,minHeight:sy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:ay,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:gy,paddingLeft:8-(gy-ay),paddingRight:6-(gy-ay)},input:{fontSize:i,lineHeight:Math.round(i*by),minHeight:Math.round(i*by),...r.Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:yy,height:yy,borderRadius:yy/2},disc:{width:fy,height:fy,borderRadius:fy/2,alignItems:"center",justifyContent:"center",backgroundColor:n?.backgroundColor??t.text.primary,...Sg(n)},dimmed:{opacity:py},tray:{marginHorizontal:cy,marginTop:uy,paddingBottom:0}})}function Ty(e){return r.StyleSheet.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:r,activePet:n,scopeEpoch:i}=Hc(),l=t.useMemo(()=>createPetsRepository(e.registry.services.authFor(r)),[e,r,i]),[o,s]=t.useState({repository:l,pets:[],loading:true,error:null}),a=o.repository===l?o:{pets:[],loading:true,error:null},u=t.useRef(0),c=t.useCallback(async()=>{let e=++u.current;s(e=>({...e,repository:l,loading:true,error:null,pets:e.repository===l?e.pets:[]}));let t=await l.list();e===u.current&&s(t.ok?{repository:l,pets:t.value,loading:false,error:null}:e=>({repository:l,pets:e.repository===l?e.pets:[],loading:false,error:t.error}))},[l]);t.useEffect(()=>(c(),()=>{u.current+=1}),[c]),t.useEffect(()=>dl(e,()=>{c()}),[e,c]);let d=t.useMemo(()=>n===null?null:a.pets.find(e=>e.petRef===n)??null,[n,a.pets]);return t.useMemo(()=>({pets:a.pets,activePet:d,loading:a.loading,error:a.error,refresh:c}),[a.pets,a.loading,a.error,d,c])}function Iy(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Py=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var zy=false;function Ey(e,t){return t!==void 0?(rh(t,e),"onStartInApp"):Vd(e)==="presented"?"presenter":$d(e)?"experience":(zy||(zy=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Oy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Oy.includes(e)}var Ay="/widget/v1/televet/handoffs",My="/widget/v1/televet/availability",Fy="/widget/v1/televet/chat-entry",Dy=/^[a-z0-9][a-z0-9_-]{0,39}$/,Ly=/^[A-Za-z0-9_-]{22}$/;var By=32,Vy=128,Hy=64;function vetVisitErrorReasonOf(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"}function Uy(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Ny(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function $y(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Dy.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let i=t?.entry;if(i!=null){if(i!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=i}let l=t?.visitRef,o=t?.intent,s=l!=null;if(s){let e=typeof l=="string"?l.trim():"";if(e.length<1||[...e].length>Hy)return{ok:false,message:`visitRef must be 1..${Hy} characters`};r.visit_ref=e}if(o!=null){if(!s)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Oy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Wy(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function qy(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Zy(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,i){let l;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Vy)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Vy} characters`}));l=e}let o=$y(l,i);if(!o.ok){let e=Uy(o.message);return e.ok?e:n(e.error)}let s=o.body,a=await t.send("televet.visit.handoff",{method:"POST",path:Ay,body:s},{idempotent:false,maxAttempts:1});if(!a.ok)return n(a.error);let u=Gy(a.value),c=s.return_to!==void 0,d=c?a.value?.flow_id:void 0;if(c&&(typeof d!="string"||!Ly.test(d))){let e=Ny("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=s.visit_ref!==void 0,h=f?Wy(a.value?.visit):null;if(f&&h===null){let e=Ny("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Zy(r,"televet.visit.handoff_created",{pet_scoped:s.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>By)return Uy(`state must be at most ${By} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:My,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Ny("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:Fy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function Gy(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||!Xy(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Ky=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Yy=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Qy=/[\s\u0000-\u001f\u007f]/;function Xy(e){if(Qy.test(e))return false;let t=Yy.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let i=n.replace(/:\d+$/,"").toLowerCase(),l=r==="https",o=r==="http"&&Ky.has(i);if(!l&&!o)return false;let s=e.indexOf("#");if(s<0)return false;let a=e.slice(s);return a.startsWith("#h=")&&a.length>3}function Zy(e,t,r){if(e)try{e.track(t,r)}catch{}}var Jy=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function ev(e,r,n){let{usState:i,chat:l,scope:o}=n,s=r&&(i!==null||l),a=`${i??""}|${l?"chat":""}`,[u,c]=t.useState(null);if(t.useEffect(()=>{if(!s)return;let t=true,r=e.current;return c(null),(async()=>{try{if(l&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&c({key:a,open:e})}),()=>{t=false}},[s,a,i,l,o,e]),!s)return null;let d=u!==null&&u.key===a;return{open:d&&u.open,pending:!d}}var tv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function rv(e,r={}){let{runtime:n,userRef:i,scopeEpoch:l}=Hc(),o=useCapability("televet"),s=o.enabled&&i!==null,a=r.usState??null,u=r.entry==="chat",c=r.petRef??null,d=r.prefer==="redirect",f=t.useMemo(()=>{if(r.controller)return r.controller;let{services:e}=n.registry;return qy({auth:e.authFor(i),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[n,i,l,r.controller]),h=t.useRef(f);h.current=f;let p=t.useMemo(()=>({runtime:n,userRef:i,scopeEpoch:l}),[n,i,l]),g=ev(h,s,{usState:a,chat:u,scope:p}),m=s&&(g===null||g.open)&&(!u||c!==null),b=r.returnTo??null,[y,v]=t.useState(Jy),x=t.useRef(null),w=t.useRef({runtime:n,userRef:i,scopeEpoch:l});w.current={runtime:n,userRef:i,scopeEpoch:l};let k=t.useRef(f);k.current=f;let C=t.useRef(m);C.current=m;let S=t.useCallback((t,r)=>{if(x.current)return x.current;let n=(e,t)=>(v({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!C.current)return Promise.resolve(n("unavailable",null));let i=e.prepare();if(!i.ok)return Promise.resolve(n(i.reason,null));let l=w.current,o=k.current;v(tv);let s=(async()=>{let s,a={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},d=Object.keys(a).length===0?void 0:a,f=t===void 0?c:t;try{s=await(d===void 0?o.createHandoff(f):o.createHandoff(f,d))}catch{return e.abandon(i.value),n("unknown",null)}let h=w.current;if(h.runtime!==l.runtime||h.userRef!==l.userRef||h.scopeEpoch!==l.scopeEpoch)return e.abandon(i.value),n("cancelled",null);if(!s.ok)return e.abandon(i.value),n(vetVisitErrorReasonOf(s.error),s.error);let p=await e.finish(i.value,s.value);return p!==null?n(p,null):(v(Jy),/* @__PURE__ */Object.freeze(s.value.flowId===void 0?{opened:true}:{opened:true,flowId:s.value.flowId}))})().finally(()=>{x.current===s&&(x.current=null)});return x.current=s,s},[e,c,b,u]),j=t.useCallback((e,t)=>{if(!C.current)return v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?c:e,n={...r!==null?{petRef:r}:{},...a!==null?{usState:a}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Ey(n)===null?(v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(v(Jy),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[c,a]),_=t.useCallback(e=>d?S(e,null):j(e,null),[d,S,j]),R=t.useCallback((e,t)=>d?S(void 0,{visitRef:e,intent:t??null}):j(void 0,{visitRef:e,intent:t??null}),[d,S,j]),T=t.useCallback(e=>d?S(void 0,null):j(void 0,{consultId:e.trim()}),[d,S,j]);return{available:m,isPending:o.isPending||(g?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:_,openVisit:R,joinVisit:T}}var nv=e=>r.Linking.openURL(e);function useVetVisit(e={}){let{openUrl:r,...n}=e,i=t.useMemo(()=>{let e=r??nv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[r]);return rv(i,n)}var iv=44,lv=.6;function VetVisitButtonCore(e){let{petRef:n,label:i,openUrl:o,onOpened:s,onError:a,style:u,labelStyle:c,controller:d,returnTo:f,usState:h,entry:p,visitRef:g,intent:m,onStartInApp:b,prefer:y}=e,v=y==="redirect",x=useVetVisit({...f!==void 0?{returnTo:f}:{},...h!==void 0?{usState:h}:{},...p!==void 0?{entry:p}:{},...n!==void 0?{petRef:n}:{},...o!==void 0?{openUrl:o}:{},...d!==void 0?{controller:d}:{},prefer:v?"redirect":"in-app"}),w=useEverfurTheme(),k=t.useMemo(()=>ov(w),[w]),C=t.useRef(false);if(!x.available)/* @__PURE__ */
150
150
  return l.jsxs(l.Fragment,{children:[null,
151
- /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]});let S=x.status==="opening",j=i??gy.visitButton;/* @__PURE__ */
151
+ /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]});let S=x.status==="opening",j=i??Py.visitButton;/* @__PURE__ */
152
152
  return l.jsxs(l.Fragment,{children:[
153
- /* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{if(!(S||C.current)){if(!v){let e={...n!==void 0?{petRef:n}:{},...h!==void 0?{usState:h}:{},...g!=null?{visitRef:g,intent:m??null}:{}};by(e,b)===null&&Hf(a,"unavailable",null);return}C.current=true,(g==null?x.open():x.openVisit(g,m??null)).then(e=>{e.opened?Hf(s,e.flowId??null):e.reason!=="cancelled"&&Hf(a,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:j,accessibilityState:{busy:S,disabled:S},style:[k.button,S?k.busy:null,u],children:/* @__PURE__ */l.jsx(Text,{style:[k.label,c],children:j})}),
154
- /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]})}function Wy(e){let{color:t,space:n,radius:i,type:l,slots:o}=e;return r.StyleSheet.create({button:{minHeight:Ny,minWidth:Ny,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:i.pill,backgroundColor:t.primary,...ug(o.vetVisitButton)},busy:{opacity:$y},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...dg(o.vetVisitButton)}})}function qy(e){let[r,n]=t.useState(null);return{shown:e!==null&&r!==e,onError:()=>n(e)}}function BrandImage({uri:e,label:t,decorative:n=false,style:i,resizeMode:o="contain",fallback:s=null,onError:a,testID:u}){let c=qy(e);if(e===null||!c.shown)return s;let d=n?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
155
- return l.jsx(r.Image,{source:{uri:e},style:i,resizeMode:o,...d,onError:()=>{c.onError(),a?.()},...u===void 0?{}:{testID:u}})}function BrandLogo({logoUrl:e,name:t,barStyle:n,logoStyle:i,testID:o}){let s=qy(e);return e===null||!s.shown?null:/* @__PURE__ */l.jsx(r.View,{style:n,...o===void 0?{}:{testID:o},children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e},style:i,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:s.onError})})}var Gy=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),Ky=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Yy(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return Ky;let n=Math.abs(e.leading-e.trailing);if(n<.5)return Ky;let i=e.row-t-e.leading-e.trailing,l=Math.min(n,Math.max(0,i-r));return l<.5?Ky:e.leading<e.trailing?{leading:e.leading+l,trailing:void 0}:{leading:void 0,trailing:e.trailing+l}}function Qy(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function Xy(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Zy(e){if(e.brightness!=="light")return false;let t=Ro.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),i=new Set(Xy(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&Xy(r).every(e=>i.has(e))}function Jy(e){let t=(e.brightness==="dark"?Io:Ro).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function ev(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function tv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function rv(e){let t=tv(e.ageYears),r=ev(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var nv=/* @__PURE__ */Object.freeze([
153
+ /* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{if(!(S||C.current)){if(!v){let e={...n!==void 0?{petRef:n}:{},...h!==void 0?{usState:h}:{},...g!=null?{visitRef:g,intent:m??null}:{}};Ey(e,b)===null&&rh(a,"unavailable",null);return}C.current=true,(g==null?x.open():x.openVisit(g,m??null)).then(e=>{e.opened?rh(s,e.flowId??null):e.reason!=="cancelled"&&rh(a,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:j,accessibilityState:{busy:S,disabled:S},style:[k.button,S?k.busy:null,u],children:/* @__PURE__ */l.jsx(Text,{style:[k.label,c],children:j})}),
154
+ /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]})}function ov(e){let{color:t,space:n,radius:i,type:l,slots:o}=e;return r.StyleSheet.create({button:{minHeight:iv,minWidth:iv,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:i.pill,backgroundColor:t.primary,...Sg(o.vetVisitButton)},busy:{opacity:lv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,..._g(o.vetVisitButton)}})}function sv(e){let[r,n]=t.useState(null);return{shown:e!==null&&r!==e,onError:()=>n(e)}}function BrandImage({uri:e,label:t,decorative:n=false,style:i,resizeMode:o="contain",fallback:s=null,onError:a,testID:u}){let c=sv(e);if(e===null||!c.shown)return s;let d=n?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
155
+ return l.jsx(r.Image,{source:{uri:e},style:i,resizeMode:o,...d,onError:()=>{c.onError(),a?.()},...u===void 0?{}:{testID:u}})}function BrandLogo({logoUrl:e,name:t,barStyle:n,logoStyle:i,testID:o}){let s=sv(e);return e===null||!s.shown?null:/* @__PURE__ */l.jsx(r.View,{style:n,...o===void 0?{}:{testID:o},children:/* @__PURE__ */l.jsx(r.Image,{source:{uri:e},style:i,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:s.onError})})}var av=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),uv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function cv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return uv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return uv;let i=e.row-t-e.leading-e.trailing,l=Math.min(n,Math.max(0,i-r));return l<.5?uv:e.leading<e.trailing?{leading:e.leading+l,trailing:void 0}:{leading:void 0,trailing:e.trailing+l}}function dv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function fv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function hv(e){if(e.brightness!=="light")return false;let t=Po.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),i=new Set(fv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&fv(r).every(e=>i.has(e))}function pv(e){let t=(e.brightness==="dark"?Eo:Po).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function gv(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function mv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function bv(e){let t=mv(e.ageYears),r=gv(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var yv=/* @__PURE__ */Object.freeze([
156
156
  /* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
157
157
  /* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
158
158
  /* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
159
159
  /* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
160
160
  /* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
161
- /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function iv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return nv[t%nv.length]}function lv(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function ov(e){return{...iv(e.petRef),initial:lv(e.name)}}function sv(e,t,r){let n=ov(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function av(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:n,ringStroke:i}){let o=useEverfurTheme(),s=t.useMemo(()=>uv(o),[o]),a=n-i*2,u=e===null?null:sv(e,Zy(o),{fill:o.color.highlight,ink:o.color.onHighlight}),c=av(a);/* @__PURE__ */
162
- return l.jsx(Ring,{size:n,strokeWidth:i,color:o.color.mark,children:/* @__PURE__ */l.jsx(r.View,{style:[s.disc,{width:a,height:a,borderRadius:a/2},u===null?s.discEmpty:{backgroundColor:u.background}],children:/* @__PURE__ */l.jsx(Text,{tier:"badge",style:[s.letter,{fontSize:c,lineHeight:Math.round(c*1.2),color:u===null?o.color.text.muted:u.foreground}],children:u===null?lv(null):u.initial})})})}function uv(e){return r.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function cv(e,t){let{borderRadius:r,...n}=ug(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function dv(e,t){let{backgroundColor:r,borderColor:n,borderWidth:i,borderRadius:l}=ug(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:i??1},...l===void 0?{}:{borderTopRightRadius:l,borderBottomRightRadius:l}}}var fv=48,hv=2,pv=320,gv="80%",mv="rgba(17,17,17,0.45)",bv=18,yv=22,vv=12,xv=.4,wv=44;function kv(e){return e?.name?.trim()||Yd.yourPet}function PetSwitcherSheet({visible:e,pets:n,activePetRef:i,onSelect:o,onAddPet:s=null,onClose:a}){let u=useEverfurTheme(),c=t.useMemo(()=>Cv(u),[u]);return e?/* @__PURE__ */l.jsx(r.Modal,{visible:true,transparent:true,animationType:u.motion.reducedMotion?"none":"fade",onRequestClose:a,children:/* @__PURE__ */l.jsxs(r.View,{style:c.root,children:[
163
- /* @__PURE__ */l.jsx(r.Pressable,{style:Ag,onPress:a,accessibilityRole:"button",accessibilityLabel:Yd.close,children:/* @__PURE__ */l.jsx(r.View,{style:c.backdrop})}),
164
- /* @__PURE__ */l.jsxs(r.View,{style:c.panel,accessibilityViewIsModal:true,children:[
165
- /* @__PURE__ */l.jsx(Text,{tier:"heading",style:c.title,accessibilityRole:"header",children:Yd.yourPets}),
166
- /* @__PURE__ */l.jsx(r.ScrollView,{style:c.list,contentContainerStyle:c.listContent,showsVerticalScrollIndicator:true,children:n.map(e=>{let t=e.petRef===i,n=kv(e),s=rv(e);/* @__PURE__ */
167
- return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Qd(t?Yd.petCurrentlyActive:Yd.switchToPet,{name:n}),accessibilityState:{selected:t},style:[c.row,t?c.rowActive:null],onPress:()=>o(e.petRef),children:[
168
- /* @__PURE__ */l.jsx(PetDisc,{pet:e,size:fv,ringStroke:hv}),
161
+ /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function vv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return yv[t%yv.length]}function xv(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function wv(e){return{...vv(e.petRef),initial:xv(e.name)}}function kv(e,t,r){let n=wv(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function Cv(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:n,ringStroke:i}){let o=useEverfurTheme(),s=t.useMemo(()=>Sv(o),[o]),a=n-i*2,u=e===null?null:kv(e,hv(o),{fill:o.color.highlight,ink:o.color.onHighlight}),c=Cv(a);/* @__PURE__ */
162
+ return l.jsx(Ring,{size:n,strokeWidth:i,color:o.color.mark,children:/* @__PURE__ */l.jsx(r.View,{style:[s.disc,{width:a,height:a,borderRadius:a/2},u===null?s.discEmpty:{backgroundColor:u.background}],children:/* @__PURE__ */l.jsx(Text,{tier:"badge",style:[s.letter,{fontSize:c,lineHeight:Math.round(c*1.2),color:u===null?o.color.text.muted:u.foreground}],children:u===null?xv(null):u.initial})})})}function Sv(e){return r.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function jv(e,t){let{borderRadius:r,...n}=Sg(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function _v(e,t){let{backgroundColor:r,borderColor:n,borderWidth:i,borderRadius:l}=Sg(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:i??1},...l===void 0?{}:{borderTopRightRadius:l,borderBottomRightRadius:l}}}var Rv=48,Tv=2,Iv=320,Pv="80%",zv="rgba(17,17,17,0.45)",Ev=18,Ov=22,Av=12,Mv=.4,Fv=44;function Dv(e){return e?.name?.trim()||df.yourPet}function PetSwitcherSheet({visible:e,pets:n,activePetRef:i,onSelect:o,onAddPet:s=null,onClose:a}){let u=useEverfurTheme(),c=t.useMemo(()=>Lv(u),[u]),d=lf();return e?/* @__PURE__ */l.jsx(r.Modal,{visible:true,transparent:true,animationType:u.motion.reducedMotion?"none":"fade",onRequestClose:a,children:/* @__PURE__ */l.jsxs(r.View,{style:c.root,children:[
163
+ /* @__PURE__ */l.jsx(r.Pressable,{style:Yg,onPress:a,accessibilityRole:"button",accessibilityLabel:df.close,children:/* @__PURE__ */l.jsx(r.View,{style:c.backdrop})}),
164
+ /* @__PURE__ */l.jsxs(r.View,{style:of(c.panel,d),accessibilityViewIsModal:true,children:[
165
+ /* @__PURE__ */l.jsx(Text,{tier:"heading",style:c.title,accessibilityRole:"header",children:df.yourPets}),
166
+ /* @__PURE__ */l.jsx(r.ScrollView,{style:c.list,contentContainerStyle:c.listContent,showsVerticalScrollIndicator:true,children:n.map(e=>{let t=e.petRef===i,n=Dv(e),s=bv(e);/* @__PURE__ */
167
+ return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:ff(t?df.petCurrentlyActive:df.switchToPet,{name:n}),accessibilityState:{selected:t},style:[c.row,t?c.rowActive:null],onPress:()=>o(e.petRef),children:[
168
+ /* @__PURE__ */l.jsx(PetDisc,{pet:e,size:Rv,ringStroke:Tv}),
169
169
  /* @__PURE__ */l.jsxs(r.View,{style:c.copy,children:[
170
170
  /* @__PURE__ */l.jsx(Text,{style:c.name,numberOfLines:1,children:n}),
171
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:c.meta,numberOfLines:1,children:t?`${Yd.activePrefix}${s}`:s})]}),t?/* @__PURE__ */l.jsx(CheckGlyph,{size:bv,color:u.color.brandInk}):null]},e.petRef)})}),s!==null?/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.addAnotherPet,style:c.addRow,onPress:s,children:[
171
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:c.meta,numberOfLines:1,children:t?`${df.activePrefix}${s}`:s})]}),t?/* @__PURE__ */l.jsx(CheckGlyph,{size:Ev,color:u.color.brandInk}):null]},e.petRef)})}),s!==null?/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:df.addAnotherPet,style:c.addRow,onPress:s,children:[
172
172
  /* @__PURE__ */l.jsx(r.View,{style:c.addDisc,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:c.addPlus,children:"+"})}),
173
- /* @__PURE__ */l.jsx(Text,{style:c.addLabel,children:Yd.addAnotherPet})]}):null,
174
- /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.close,containerStyle:c.closeSlot,style:c.closeButton,onPress:a,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:c.closeText,children:Yd.close})})]})]})}):null}function Cv(e){let t=e.color,n=e.radius,i=dg(e.slots.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:mv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:yv,borderTopRightRadius:yv,gap:14,maxHeight:gv,...cv(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...i},list:{maxHeight:pv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:wv,paddingHorizontal:8},addDisc:{width:fv,height:fv,borderRadius:n.pill,alignItems:"center",justifyContent:"center",borderWidth:hv,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...i},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:xv},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:vv,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:xv}})}var Sv=44,jv=36,_v=22,Rv=20,Tv=9,Iv=1.5,Pv=6,zv=35,Ev=1.75,Ov=12.4,Av=.5,Mv=8,Fv=28,Dv=160,Lv=16,Bv=8;function Vv(e,t){return py(e,t)}function ChatHeader({pets:e,petRef:n,historyUnread:i,onOpenHistory:o,onNewChat:s,onPetChange:a,onAddPet:u,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=t.useMemo(()=>Hv(f),[f]),[p,g]=t.useState(false),m=Vv(e.pets,n),b=m!==null&&(e.pets.length>=2||u!==void 0),y=n??m?.petRef??null,v=kv(m),[x,w]=t.useState(Gy),k=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>Qy(t,e,r))},[]),C=t.useMemo(()=>k("row"),[k]),S=t.useMemo(()=>k("leading"),[k]),j=t.useMemo(()=>k("trailing"),[k]),_=2*Lv+2*(f.slots.header?.borderColor!==void 0?1:0)+2*Bv,R=Yy(x,_,Dv),T=t=>{g(false),e.setActivePet(t),Hf(a,t)},I=u===void 0?null:()=>{g(false),Hf(u)};/* @__PURE__ */
173
+ /* @__PURE__ */l.jsx(Text,{style:c.addLabel,children:df.addAnotherPet})]}):null,
174
+ /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:df.close,containerStyle:c.closeSlot,style:c.closeButton,onPress:a,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:c.closeText,children:df.close})})]})]})}):null}function Lv(e){let t=e.color,n=e.radius,i=_g(e.slots.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:zv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Ov,borderTopRightRadius:Ov,gap:14,maxHeight:Pv,...jv(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...i},list:{maxHeight:Iv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:Fv,paddingHorizontal:8},addDisc:{width:Rv,height:Rv,borderRadius:n.pill,alignItems:"center",justifyContent:"center",borderWidth:Tv,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...i},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Mv},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:Av,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Mv}})}var Bv=44,Vv=36,Hv=22,Uv=20,Nv=9,$v=1.5,Wv=6,qv=35,Gv=1.75,Kv=12.4,Yv=.5,Qv=8,Xv=28,Zv=160,Jv=16,ex=8;function tx(e,t){return Iy(e,t)}function ChatHeader({pets:e,petRef:n,historyUnread:i,onOpenHistory:o,onNewChat:s,onPetChange:a,onAddPet:u,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=t.useMemo(()=>rx(f),[f]),[p,g]=t.useState(false),m=tx(e.pets,n),b=m!==null&&(e.pets.length>=2||u!==void 0),y=n??m?.petRef??null,v=Dv(m),[x,w]=t.useState(av),k=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>dv(t,e,r))},[]),C=t.useMemo(()=>k("row"),[k]),S=t.useMemo(()=>k("leading"),[k]),j=t.useMemo(()=>k("trailing"),[k]),_=2*Jv+2*(f.slots.header?.borderColor!==void 0?1:0)+2*ex,R=cv(x,_,Zv),T=t=>{g(false),e.setActivePet(t),rh(a,t)},I=u===void 0?null:()=>{g(false),rh(u)};/* @__PURE__ */
175
175
  return l.jsxs(l.Fragment,{children:[
176
176
  /* @__PURE__ */l.jsxs(r.View,{style:h.row,onLayout:C,children:[
177
- /* @__PURE__ */l.jsx(r.View,{style:[h.leading,R.leading===void 0?null:{minWidth:R.leading}],children:/* @__PURE__ */l.jsxs(r.View,{style:h.sideContent,onLayout:S,children:[s!==void 0?/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Zh.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:s,children:/* @__PURE__ */l.jsx(EditGlyph,{size:Rv,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
178
- /* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:i?`${Yd.openHistoryNative}${Yd.newReplySuffix}`:Yd.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:o,children:[
179
- /* @__PURE__ */l.jsx(MenuGlyph,{size:_v,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),i?/* @__PURE__ */l.jsx(r.View,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
177
+ /* @__PURE__ */l.jsx(r.View,{style:[h.leading,R.leading===void 0?null:{minWidth:R.leading}],children:/* @__PURE__ */l.jsxs(r.View,{style:h.sideContent,onLayout:S,children:[s!==void 0?/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:hp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:s,children:/* @__PURE__ */l.jsx(EditGlyph,{size:Uv,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
178
+ /* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:i?`${df.openHistoryNative}${df.newReplySuffix}`:df.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:o,children:[
179
+ /* @__PURE__ */l.jsx(MenuGlyph,{size:Hv,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),i?/* @__PURE__ */l.jsx(r.View,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
180
180
  /* @__PURE__ */l.jsx(r.View,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */l.jsx(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
181
181
  /* @__PURE__ */l.jsx(r.View,{style:[h.trailing,R.trailing===void 0?null:{minWidth:R.trailing}],children:/* @__PURE__ */l.jsxs(r.View,{style:h.trailingContent,onLayout:j,children:[y===null?null:/* @__PURE__ */l.jsx(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
182
- /* @__PURE__ */l.jsx(r.View,{style:h.right,children:b?/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Qd(Yd.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
183
- /* @__PURE__ */l.jsx(PetDisc,{pet:m,size:zv,ringStroke:Ev}),
184
- /* @__PURE__ */l.jsx(r.View,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */l.jsx(PlusGlyph,{size:Mv,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&m===null?
185
- /* @__PURE__ */l.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityLabel:Yd.yourPet,children:/* @__PURE__ */l.jsx(Ring,{size:zv,strokeWidth:Ev,color:f.color.mark,children:/* @__PURE__ */l.jsx(r.View,{style:h.placeholderDisc})})}):/* @__PURE__ */l.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:m===null?Yd.yourPet:v,children:/* @__PURE__ */l.jsx(PetDisc,{pet:m,size:zv,ringStroke:Ev})})})]})}),
186
- /* @__PURE__ */l.jsx(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:m?.petRef??null,onSelect:T,onAddPet:I,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */l.jsx(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Hv(i),[i]);/* @__PURE__ */
187
- return l.jsx(r.View,{style:n==="header"?o.textingEntryRowHeader:o.textingEntryRowThread,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:o.textingEntrySlot,style:o.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:o.vetEntryLabel,numberOfLines:1,children:e.label})})})}function Hv(e){let t=e.color,n=zv-Ev*2,i=e.slots.header;return r.StyleSheet.create({vetEntry:{minHeight:Sv,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Lv,paddingBottom:10,backgroundColor:i?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Lv,paddingTop:e.space.sm},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:Lv,paddingVertical:10,backgroundColor:t.surface,...ug(i)},iconSlot:{borderRadius:jv/2},iconButton:{width:jv,height:jv,borderRadius:jv/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Pv,right:Pv,width:Tv,height:Tv,borderRadius:Tv,backgroundColor:t.danger,borderWidth:Iv,borderColor:i?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:Bv,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:Fv,width:Dv,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:zv/2},avatarWrap:{width:zv,height:zv,position:"relative"},placeholderDisc:{width:n,height:n,borderRadius:n/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Ov,height:Ov,borderRadius:Ov/2,borderWidth:Av,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var Uv=/* @__PURE__ */Object.freeze([
188
- /* @__PURE__ */Object.freeze({key:"inaccurate",label:Yd.feedbackReasonInaccurate,feedbackType:"wrong"}),
189
- /* @__PURE__ */Object.freeze({key:"outdated",label:Yd.feedbackReasonOutdated,feedbackType:"outdated"}),
190
- /* @__PURE__ */Object.freeze({key:"unsafe",label:Yd.feedbackReasonUnsafe,feedbackType:"dangerous"}),
191
- /* @__PURE__ */Object.freeze({key:"unclear",label:Yd.feedbackReasonUnclear,feedbackType:"unclear"}),
192
- /* @__PURE__ */Object.freeze({key:"other",label:Yd.feedbackReasonOther,feedbackType:"not_helpful"})]),Nv=/* @__PURE__ */Object.freeze([
193
- /* @__PURE__ */Object.freeze({sentiment:"up",label:Yd.feedbackHelpful}),
194
- /* @__PURE__ */Object.freeze({sentiment:"down",label:Yd.feedbackNotHelpful})]);function $v(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function Wv(e,t){if(e==="down"&&t!==null){let e=Uv.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return $v(e)}var qv=44,Gv="rgba(17,17,17,0.55)",Kv=26,Yv=36,Qv=4,Xv=20,Zv=38,Jv=18,ex=12;function FeedbackReasons({visible:e,onSubmit:n,onSkip:i}){let o=useEverfurTheme(),s=t.useMemo(()=>tx(o),[o]),[a,u]=t.useState(null),[c,d]=t.useState(""),[f,h]=t.useState(false),[p,g]=t.useState(false),m=()=>{u(null),d(""),h(false),g(false)},b=()=>{f||(m(),i())},y=async()=>{if(f)return;h(true),g(false);let e=c.trim();await n(a,e.length>0?e:null)?m():(h(false),g(true))};if(!e)return null;let v=[...c].length>dn;/* @__PURE__ */
195
- return l.jsx(r.Modal,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"slide",onRequestClose:b,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{behavior:r.Platform.OS==="ios"?"padding":void 0,style:s.root,children:[
196
- /* @__PURE__ */l.jsx(r.Pressable,{style:s.scrim,onPress:b,accessibilityRole:"button",accessibilityLabel:Yd.feedbackSkipA11y}),
197
- /* @__PURE__ */l.jsxs(r.View,{style:s.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
182
+ /* @__PURE__ */l.jsx(r.View,{style:h.right,children:b?/* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:ff(df.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
183
+ /* @__PURE__ */l.jsx(PetDisc,{pet:m,size:qv,ringStroke:Gv}),
184
+ /* @__PURE__ */l.jsx(r.View,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */l.jsx(PlusGlyph,{size:Qv,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&m===null?
185
+ /* @__PURE__ */l.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityLabel:df.yourPet,children:/* @__PURE__ */l.jsx(Ring,{size:qv,strokeWidth:Gv,color:f.color.mark,children:/* @__PURE__ */l.jsx(r.View,{style:h.placeholderDisc})})}):/* @__PURE__ */l.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:m===null?df.yourPet:v,children:/* @__PURE__ */l.jsx(PetDisc,{pet:m,size:qv,ringStroke:Gv})})})]})}),
186
+ /* @__PURE__ */l.jsx(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:m?.petRef??null,onSelect:T,onAddPet:I,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */l.jsx(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:n}){let i=useEverfurTheme(),o=t.useMemo(()=>rx(i),[i]);/* @__PURE__ */
187
+ return l.jsx(r.View,{style:n==="header"?o.textingEntryRowHeader:o.textingEntryRowThread,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:o.textingEntrySlot,style:o.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:o.vetEntryLabel,numberOfLines:1,children:e.label})})})}function rx(e){let t=e.color,n=qv-Gv*2,i=e.slots.header;return r.StyleSheet.create({vetEntry:{minHeight:Bv,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Jv,paddingBottom:10,backgroundColor:i?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Jv,paddingTop:e.space.md,paddingBottom:e.space.xs},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:Jv,paddingVertical:10,backgroundColor:t.surface,...Sg(i)},iconSlot:{borderRadius:Vv/2},iconButton:{width:Vv,height:Vv,borderRadius:Vv/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Wv,right:Wv,width:Nv,height:Nv,borderRadius:Nv,backgroundColor:t.danger,borderWidth:$v,borderColor:i?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:ex,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:Xv,width:Zv,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:qv/2},avatarWrap:{width:qv,height:qv,position:"relative"},placeholderDisc:{width:n,height:n,borderRadius:n/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Kv,height:Kv,borderRadius:Kv/2,borderWidth:Yv,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var nx=/* @__PURE__ */Object.freeze([
188
+ /* @__PURE__ */Object.freeze({key:"inaccurate",label:df.feedbackReasonInaccurate,feedbackType:"wrong"}),
189
+ /* @__PURE__ */Object.freeze({key:"outdated",label:df.feedbackReasonOutdated,feedbackType:"outdated"}),
190
+ /* @__PURE__ */Object.freeze({key:"unsafe",label:df.feedbackReasonUnsafe,feedbackType:"dangerous"}),
191
+ /* @__PURE__ */Object.freeze({key:"unclear",label:df.feedbackReasonUnclear,feedbackType:"unclear"}),
192
+ /* @__PURE__ */Object.freeze({key:"other",label:df.feedbackReasonOther,feedbackType:"not_helpful"})]),ix=/* @__PURE__ */Object.freeze([
193
+ /* @__PURE__ */Object.freeze({sentiment:"up",label:df.feedbackHelpful}),
194
+ /* @__PURE__ */Object.freeze({sentiment:"down",label:df.feedbackNotHelpful})]);function lx(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function ox(e,t){if(e==="down"&&t!==null){let e=nx.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return lx(e)}var sx=44,ax="rgba(17,17,17,0.55)",ux=26,cx=36,dx=4,fx=20,hx=38,px=18,gx=12;function FeedbackReasons({visible:e,onSubmit:n,onSkip:i}){let o=useEverfurTheme(),s=t.useMemo(()=>mx(o),[o]),a=lf(),[u,c]=t.useState(null),[d,f]=t.useState(""),[h,p]=t.useState(false),[g,m]=t.useState(false),b=()=>{c(null),f(""),p(false),m(false)},y=()=>{h||(b(),i())},v=async()=>{if(h)return;p(true),m(false);let e=d.trim();await n(u,e.length>0?e:null)?b():(p(false),m(true))};if(!e)return null;let x=[...d].length>pn;/* @__PURE__ */
195
+ return l.jsx(r.Modal,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"slide",onRequestClose:y,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{behavior:r.Platform.OS==="ios"?"padding":void 0,style:s.root,children:[
196
+ /* @__PURE__ */l.jsx(r.Pressable,{style:s.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:df.feedbackSkipA11y}),
197
+ /* @__PURE__ */l.jsxs(r.View,{style:of(s.sheet,a),accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
198
198
  /* @__PURE__ */l.jsx(r.View,{style:s.handle}),
199
199
  /* @__PURE__ */l.jsxs(r.View,{style:s.header,children:[
200
- /* @__PURE__ */l.jsx(r.View,{style:s.iconBadge,children:/* @__PURE__ */l.jsx(ThumbGlyph,{size:Jv,color:o.color.brandInk,active:false,rotate:"180deg"})}),
200
+ /* @__PURE__ */l.jsx(r.View,{style:s.iconBadge,children:/* @__PURE__ */l.jsx(ThumbGlyph,{size:px,color:o.color.brandInk,active:false,rotate:"180deg"})}),
201
201
  /* @__PURE__ */l.jsxs(r.View,{style:s.headerText,children:[
202
- /* @__PURE__ */l.jsx(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:Yd.feedbackTitle}),
203
- /* @__PURE__ */l.jsx(Text,{style:s.subtitle,children:Yd.feedbackSubtitle})]})]}),
204
- /* @__PURE__ */l.jsx(r.View,{style:s.options,children:Uv.map(e=>{let t=a===e.key;/* @__PURE__ */
205
- return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[s.option,t?s.optionSelected:null],onPress:()=>u(t=>t===e.key?null:e.key),children:[
202
+ /* @__PURE__ */l.jsx(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:df.feedbackTitle}),
203
+ /* @__PURE__ */l.jsx(Text,{style:s.subtitle,children:df.feedbackSubtitle})]})]}),
204
+ /* @__PURE__ */l.jsx(r.View,{style:s.options,children:nx.map(e=>{let t=u===e.key;/* @__PURE__ */
205
+ return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[s.option,t?s.optionSelected:null],onPress:()=>c(t=>t===e.key?null:e.key),children:[
206
206
  /* @__PURE__ */l.jsx(Text,{style:[s.optionLabel,t?s.optionLabelSelected:null],children:e.label}),
207
- /* @__PURE__ */l.jsx(r.View,{style:[s.radio,t?s.radioSelected:null],children:t?/* @__PURE__ */l.jsx(CheckGlyph,{size:ex,color:o.color.surface,strokeWidth:2}):null})]},e.key)})}),
207
+ /* @__PURE__ */l.jsx(r.View,{style:[s.radio,t?s.radioSelected:null],children:t?/* @__PURE__ */l.jsx(CheckGlyph,{size:gx,color:o.color.surface,strokeWidth:2}):null})]},e.key)})}),
208
208
  /* @__PURE__ */l.jsxs(r.View,{style:s.inputWrap,children:[
209
- /* @__PURE__ */l.jsx(Td,{style:s.input,placeholder:Yd.feedbackNotesPlaceholder,placeholderTextColor:o.color.text.placeholder,accessibilityLabel:Yd.feedbackNotesPlaceholder,value:c,onChangeText:d,multiline:true,editable:!f}),c.length>0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[s.counter,v?s.counterOver:null],children:`${[...c].length}/${dn}`}):null]}),p?/* @__PURE__ */l.jsx(Text,{style:s.failed,accessibilityRole:"alert",children:Yd.feedbackFailed}):null,
209
+ /* @__PURE__ */l.jsx(zd,{style:s.input,placeholder:df.feedbackNotesPlaceholder,placeholderTextColor:o.color.text.placeholder,accessibilityLabel:df.feedbackNotesPlaceholder,value:d,onChangeText:f,multiline:true,editable:!h}),d.length>0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[s.counter,x?s.counterOver:null],children:`${[...d].length}/${pn}`}):null]}),g?/* @__PURE__ */l.jsx(Text,{style:s.failed,accessibilityRole:"alert",children:df.feedbackFailed}):null,
210
210
  /* @__PURE__ */l.jsxs(r.View,{style:s.actions,children:[
211
- /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.feedbackSubmit,accessibilityState:{busy:f,disabled:f||v},disabled:f||v,style:[s.submit,f||v?s.submitDisabled:null],onPress:()=>{y()},children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:s.submitLabel,children:Yd.feedbackSubmit})}),
212
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Yd.feedbackSkipA11y,hitSlop:8,onPress:b,style:s.skip,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:s.skipLabel,children:Yd.feedbackSkip})})]})]})]})})}function tx(e){let t=e.color,n=e.type,i=e.radius,l=e.slots,o=dg(l.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Ag,backgroundColor:Gv},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Kv,borderTopRightRadius:Kv,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...cv(l.dialog)},handle:{alignSelf:"center",width:Yv,height:Qv,borderRadius:Qv/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Zv,height:Zv,borderRadius:Zv/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:n.letterSpacing.tight,...o},subtitle:{...face(e,"regular"),fontSize:n.size.body,lineHeight:n.size.body*n.lineHeight.relaxed,color:t.text.muted,...o},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:i.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...ug(l.chip,r.StyleSheet.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.primary,...dg(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:Xv,height:Xv,borderRadius:Xv/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:i.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:n.size.body,color:t.text.primary,textAlignVertical:"top",...ug(l.input,1),...dg(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:n.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:qv,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:i.pill,backgroundColor:t.brand,...ug(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.onPrimary,...dg(l.primaryButton)},skip:{minHeight:qv,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.muted}})}var rx=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function nx(){let e=globalThis,r=e[rx];if(r!==void 0)return r;let n={factory:t.createContext(null),home:t.createContext(null)};return e[rx]=n,n}var ix=nx().factory,lx=nx().home;function ox(){return t.useContext(ix)}function sx(){return t.useContext(lx)?.kit??null}function ax(){return t.useContext(lx)}var ux=15,cx=8;function HistoryBar({bar:e,history:n,empty:i,unread:o,extra:s}){let a=useEverfurTheme(),u=sx(),c=t.useMemo(()=>u!==null?hx(a,u):px(a),[a,u]),d=n.cursor===null?n.rows.length:0,f=t=>{let n=e.renderIcon;if(n!==void 0)/* @__PURE__ */return l.jsx(HostRender,{render:()=>n(t),fallback:null});if(u===null)return null;let i=String(r.StyleSheet.flatten(c.label).color??a.color.linkInk);return t==="history"?/* @__PURE__ */l.jsx(HistoryGlyph,{size:fx,color:i,strokeWidth:1.8}):/* @__PURE__ */l.jsx(EditGlyph,{size:fx,color:i,strokeWidth:1.8})};/* @__PURE__ */
211
+ /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:df.feedbackSubmit,accessibilityState:{busy:h,disabled:h||x},disabled:h||x,style:[s.submit,h||x?s.submitDisabled:null],onPress:()=>{v()},children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:s.submitLabel,children:df.feedbackSubmit})}),
212
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:df.feedbackSkipA11y,hitSlop:8,onPress:y,style:s.skip,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:s.skipLabel,children:df.feedbackSkip})})]})]})]})})}function mx(e){let t=e.color,n=e.type,i=e.radius,l=e.slots,o=_g(l.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Yg,backgroundColor:ax},sheet:{backgroundColor:t.surface,borderTopLeftRadius:ux,borderTopRightRadius:ux,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...jv(l.dialog)},handle:{alignSelf:"center",width:cx,height:dx,borderRadius:dx/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:hx,height:hx,borderRadius:hx/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:n.letterSpacing.tight,...o},subtitle:{...face(e,"regular"),fontSize:n.size.body,lineHeight:n.size.body*n.lineHeight.relaxed,color:t.text.muted,...o},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:i.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...Sg(l.chip,r.StyleSheet.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.primary,..._g(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:fx,height:fx,borderRadius:fx/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:i.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:n.size.body,color:t.text.primary,textAlignVertical:"top",...Sg(l.input,1),..._g(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:n.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:sx,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:i.pill,backgroundColor:t.brand,...Sg(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.onPrimary,..._g(l.primaryButton)},skip:{minHeight:sx,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.muted}})}var bx=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function yx(){let e=globalThis,r=e[bx];if(r!==void 0)return r;let n={factory:t.createContext(null),home:t.createContext(null)};return e[bx]=n,n}var vx=yx().factory,xx=yx().home;function wx(){return t.useContext(vx)}function kx(){return t.useContext(xx)?.kit??null}function Cx(){return t.useContext(xx)}var Sx=15,jx=8;function HistoryBar({bar:e,history:n,empty:i,unread:o,extra:s}){let a=useEverfurTheme(),u=kx(),c=t.useMemo(()=>u!==null?Tx(a,u):Ix(a),[a,u]),d=n.cursor===null?n.rows.length:0,f=t=>{let n=e.renderIcon;if(n!==void 0)/* @__PURE__ */return l.jsx(HostRender,{render:()=>n(t),fallback:null});if(u===null)return null;let i=String(r.StyleSheet.flatten(c.label).color??a.color.linkInk);return t==="history"?/* @__PURE__ */l.jsx(HistoryGlyph,{size:Rx,color:i,strokeWidth:1.8}):/* @__PURE__ */l.jsx(EditGlyph,{size:Rx,color:i,strokeWidth:1.8})};/* @__PURE__ */
213
213
  return l.jsxs(r.View,{style:c.bar,testID:"everfur-history-bar",children:[
214
- /* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:d>0?`${e.chats} ${d}`:e.chats,accessibilityState:{expanded:n.open},onPress:n.open?n.close:n.show,style:c.control,hitSlop:u!==null?dx:void 0,children:[f("history"),
214
+ /* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:d>0?`${e.chats} ${d}`:e.chats,accessibilityState:{expanded:n.open},onPress:n.open?n.close:n.show,style:c.control,hitSlop:u!==null?_x:void 0,children:[f("history"),
215
215
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:c.label,children:e.chats}),d>0?/* @__PURE__ */l.jsx(r.View,{style:c.count,children:/* @__PURE__ */l.jsx(Text,{tier:"badge",style:c.countText,children:String(d)})}):null,o?/* @__PURE__ */l.jsx(r.View,{style:c.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,s??null,
216
- /* @__PURE__ */l.jsx(r.View,{style:c.spacer}),i?null:/* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:n.newConversation,style:c.control,hitSlop:u!==null?dx:void 0,children:[f("edit"),
217
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:c.label,children:e.newChat})]})]})}var dx=4,fx=18;function hx(e,t){return{...px(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function px(e){let t=e.color,n=e.space;return r.StyleSheet.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:im},label:{...face(e,"bold"),fontSize:ux,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:cx,height:cx,borderRadius:cx/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var gx=.88,mx=420,bx=58,yx="rgba(17,17,17,0.28)",vx=.15,xx=14,wx=12,kx=44,Cx=16,Sx=14,jx=12,_x=14,Rx=8,Tx=2,Ix=.5,Px=Bp(Ip.standard);function zx(e){return Math.min(Math.round(e*gx),mx)}function HistoryDrawer({chat:e,history:r}){let[n,i]=t.useState(r.open),o=t.useCallback(()=>i(false),[]);return r.open&&!n&&i(true),n?/* @__PURE__ */l.jsx(DrawerModal,{chat:e,history:r,onHidden:o}):null}function DrawerModal({chat:e,history:i,onHidden:o}){let s=useEverfurTheme(),a=t.useMemo(()=>Ex(s),[s]),u=Mp(),c=n.useSafeAreaInsets(),{width:d}=r.useWindowDimensions(),f=zx(d),h=i.open,p=t.useRef(null);p.current===null&&(p.current=new r.Animated.Value(u.drawerMs<=0&&h?1:0));let g=p.current;t.useEffect(()=>{if(!h&&u.drawerMs<=0){o();return}let e=r.Animated.timing(g,{toValue:h?1:0,duration:u.drawerMs,easing:Px,useNativeDriver:true});return e.start(({finished:e})=>{e&&!h&&o()}),()=>e.stop()},[h,g,u.drawerMs,o]);let m=g.interpolate({inputRange:[0,1],outputRange:[-f,0]}),b=i.filtered,y=i.rows.length===0,v=i.cursor===null&&!i.loading&&i.error===null,x=y&&i.loading?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,accessibilityLabel:Zh.loading,accessibilityState:{busy:true},children:[
216
+ /* @__PURE__ */l.jsx(r.View,{style:c.spacer}),i?null:/* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:n.newConversation,style:c.control,hitSlop:u!==null?_x:void 0,children:[f("edit"),
217
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:c.label,children:e.newChat})]})]})}var _x=4,Rx=18;function Tx(e,t){return{...Ix(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function Ix(e){let t=e.color,n=e.space;return r.StyleSheet.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:vm},label:{...face(e,"bold"),fontSize:Sx,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:jx,height:jx,borderRadius:jx/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var Px=.88,zx=420,Ex=58,Ox="rgba(17,17,17,0.28)",Ax=.15,Mx=14,Fx=12,Dx=44,Lx=16,Bx=14,Vx=12,Hx=14,Ux=8,Nx=2,$x=.5,Wx=eg($p.standard);function qx(e){return Math.min(Math.round(e*Px),zx)}function HistoryDrawer({chat:e,history:r}){let[n,i]=t.useState(r.open),o=t.useCallback(()=>i(false),[]);return r.open&&!n&&i(true),n?/* @__PURE__ */l.jsx(DrawerModal,{chat:e,history:r,onHidden:o}):null}function DrawerModal({chat:e,history:i,onHidden:o}){let s=useEverfurTheme(),a=t.useMemo(()=>Gx(s),[s]),u=Qp(),c=n.useSafeAreaInsets(),{width:d}=r.useWindowDimensions(),f=qx(d),h=i.open,p=t.useRef(null);p.current===null&&(p.current=new r.Animated.Value(u.drawerMs<=0&&h?1:0));let g=p.current;t.useEffect(()=>{if(!h&&u.drawerMs<=0){o();return}let e=r.Animated.timing(g,{toValue:h?1:0,duration:u.drawerMs,easing:Wx,useNativeDriver:true});return e.start(({finished:e})=>{e&&!h&&o()}),()=>e.stop()},[h,g,u.drawerMs,o]);let m=g.interpolate({inputRange:[0,1],outputRange:[-f,0]}),b=i.filtered,y=i.rows.length===0,v=i.cursor===null&&!i.loading&&i.error===null,x=y&&i.loading?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,accessibilityLabel:hp.loading,accessibilityState:{busy:true},children:[
218
218
  /* @__PURE__ */l.jsx(r.ActivityIndicator,{color:a.emptyTitle.color}),
219
- /* @__PURE__ */l.jsx(Text,{style:a.emptyBody,children:Zh.loading})]}):y&&i.error!==null?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,children:[
220
- /* @__PURE__ */l.jsx(Text,{style:a.emptyTitle,accessibilityRole:"alert",children:Zh.loadFailed}),
219
+ /* @__PURE__ */l.jsx(Text,{style:a.emptyBody,children:hp.loading})]}):y&&i.error!==null?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,children:[
220
+ /* @__PURE__ */l.jsx(Text,{style:a.emptyTitle,accessibilityRole:"alert",children:hp.loadFailed}),
221
221
  /* @__PURE__ */l.jsx(Text,{style:a.emptyBody,children:i.error}),
222
- /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Zh.retry,containerStyle:a.retrySlot,style:a.retryButton,onPress:()=>{i.load()},children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.retryText,children:Zh.retry})})]}):i.emptyKind==="empty"?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,children:[
223
- /* @__PURE__ */l.jsx(Text,{style:a.emptyTitle,children:Zh.empty}),
224
- /* @__PURE__ */l.jsx(Text,{style:a.emptyBody,children:Zh.emptyBody})]}):
225
- /* @__PURE__ */l.jsx(Text,{style:a.noMatch,children:Zh.noMatch}),w=!i.searching&&i.loadingMore?/* @__PURE__ */l.jsx(r.View,{style:a.loadMoreFooter,children:/* @__PURE__ */l.jsx(Text,{style:a.loadMoreLabel,children:Zh.loadingMore})}):null;/* @__PURE__ */
222
+ /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:hp.retry,containerStyle:a.retrySlot,style:a.retryButton,onPress:()=>{i.load()},children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.retryText,children:hp.retry})})]}):i.emptyKind==="empty"?/* @__PURE__ */l.jsxs(r.View,{style:a.emptyCard,children:[
223
+ /* @__PURE__ */l.jsx(Text,{style:a.emptyTitle,children:hp.empty}),
224
+ /* @__PURE__ */l.jsx(Text,{style:a.emptyBody,children:hp.emptyBody})]}):
225
+ /* @__PURE__ */l.jsx(Text,{style:a.noMatch,children:hp.noMatch}),w=!i.searching&&i.loadingMore?/* @__PURE__ */l.jsx(r.View,{style:a.loadMoreFooter,children:/* @__PURE__ */l.jsx(Text,{style:a.loadMoreLabel,children:hp.loadingMore})}):null;/* @__PURE__ */
226
226
  return l.jsx(r.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:i.close,children:/* @__PURE__ */l.jsxs(r.View,{style:a.root,children:[
227
- /* @__PURE__ */l.jsx(r.Pressable,{style:Ag,onPress:i.close,accessibilityRole:"button",accessibilityLabel:Zh.closeA11y,children:/* @__PURE__ */l.jsx(r.Animated.View,{style:[a.backdrop,{opacity:g}]})}),
228
- /* @__PURE__ */l.jsx(r.Animated.View,{style:[a.panel,{width:f,paddingTop:Math.max(bx,c.top+s.space.md),transform:[{translateX:m}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{style:a.keyboardAvoider,behavior:r.Platform.OS==="ios"?"padding":"height",children:[
227
+ /* @__PURE__ */l.jsx(r.Pressable,{style:Yg,onPress:i.close,accessibilityRole:"button",accessibilityLabel:hp.closeA11y,children:/* @__PURE__ */l.jsx(r.Animated.View,{style:[a.backdrop,{opacity:g}]})}),
228
+ /* @__PURE__ */l.jsx(r.Animated.View,{style:[a.panel,{width:f,paddingTop:Math.max(Ex,c.top+s.space.md),transform:[{translateX:m}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{style:a.keyboardAvoider,behavior:r.Platform.OS==="ios"?"padding":"height",children:[
229
229
  /* @__PURE__ */l.jsxs(r.View,{style:a.header,children:[
230
- /* @__PURE__ */l.jsx(Text,{tier:"heading",style:a.heading,accessibilityRole:"header",children:Zh.heading}),
231
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Zh.newChat,style:a.newChat,onPress:i.newConversation,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.newChatLabel,children:Zh.newChat})}),
232
- /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Zh.close,hitSlop:0,style:a.closeButton,onPress:i.close,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:Cx,color:s.color.text.muted,strokeWidth:1.75})})]}),
230
+ /* @__PURE__ */l.jsx(Text,{tier:"heading",style:a.heading,accessibilityRole:"header",children:hp.heading}),
231
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:hp.newChat,style:a.newChat,onPress:i.newConversation,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.newChatLabel,children:hp.newChat})}),
232
+ /* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:hp.close,hitSlop:0,style:a.closeButton,onPress:i.close,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:Lx,color:s.color.text.muted,strokeWidth:1.75})})]}),
233
233
  /* @__PURE__ */l.jsxs(r.View,{style:a.searchPill,children:[
234
- /* @__PURE__ */l.jsx(SearchGlyph,{size:_x,color:s.color.text.muted,strokeWidth:1.5}),
235
- /* @__PURE__ */l.jsx(Td,{value:i.query,onChangeText:e=>i.setQuery(e.replace(/^\s+/,"")),style:a.searchInput,placeholder:Zh.searchPlaceholder,placeholderTextColor:s.color.text.placeholder,accessibilityLabel:Zh.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
236
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.countLabel,children:rp(i.rows.length,v)}),i.error!==null&&!y?/* @__PURE__ */l.jsx(r.View,{style:a.errorCard,children:/* @__PURE__ */l.jsx(Text,{style:a.errorText,accessibilityRole:"alert",children:i.error})}):null,
237
- /* @__PURE__ */l.jsx(r.FlatList,{data:b,keyExtractor:e=>e.id,renderItem:({item:t})=>/* @__PURE__ */l.jsx(Row,{row:t,active:t.id===e.conversationId,disabled:i.loading,styles:a,onPress:()=>{i.resume(t.id)}}),contentContainerStyle:b.length===0?a.listEmpty:a.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:x,ListFooterComponent:w,onEndReached:i.loadMore,onEndReachedThreshold:Ix})]})})]})})}function Row({row:e,active:t,disabled:n,styles:i,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0,a=tp(e);/* @__PURE__ */
238
- return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:np(e),accessibilityState:{selected:t,disabled:n},disabled:n,style:[i.item,t?i.itemActive:null],onPress:o,children:[
234
+ /* @__PURE__ */l.jsx(SearchGlyph,{size:Hx,color:s.color.text.muted,strokeWidth:1.5}),
235
+ /* @__PURE__ */l.jsx(zd,{value:i.query,onChangeText:e=>i.setQuery(e.replace(/^\s+/,"")),style:a.searchInput,placeholder:hp.searchPlaceholder,placeholderTextColor:s.color.text.placeholder,accessibilityLabel:hp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
236
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.countLabel,children:bp(i.rows.length,v)}),i.error!==null&&!y?/* @__PURE__ */l.jsx(r.View,{style:a.errorCard,children:/* @__PURE__ */l.jsx(Text,{style:a.errorText,accessibilityRole:"alert",children:i.error})}):null,
237
+ /* @__PURE__ */l.jsx(r.FlatList,{data:b,keyExtractor:e=>e.id,renderItem:({item:t})=>/* @__PURE__ */l.jsx(Row,{row:t,active:t.id===e.conversationId,disabled:i.loading,styles:a,onPress:()=>{i.resume(t.id)}}),contentContainerStyle:b.length===0?a.listEmpty:a.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:x,ListFooterComponent:w,onEndReached:i.loadMore,onEndReachedThreshold:$x})]})})]})})}function Row({row:e,active:t,disabled:n,styles:i,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0,a=mp(e);/* @__PURE__ */
238
+ return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:yp(e),accessibilityState:{selected:t,disabled:n},disabled:n,style:[i.item,t?i.itemActive:null],onPress:o,children:[
239
239
  /* @__PURE__ */l.jsxs(r.View,{style:i.itemRow,children:[
240
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:i.itemTitle,numberOfLines:1,children:Jh(e.title)}),s?/* @__PURE__ */l.jsx(r.View,{style:i.unreadDot}):null]}),a!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.itemMeta,numberOfLines:1,children:a}):null]})}function Ex(e){let t=e.color,n=e.space,i=e.type,l=e.slots,o=t.text.primary,s=dg(l.card);return r.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:yx},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:n.lg,borderRightWidth:r.StyleSheet.hairlineWidth,borderRightColor:t.borderRingCream,gap:n.md,...dv(l.dialog,r.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:n.md},header:{flexDirection:"row",alignItems:"center",gap:n.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:i.size.subtitle,color:o,...dg(l.dialog)},newChat:{minHeight:kx,justifyContent:"center",paddingHorizontal:n.xs},newChatLabel:{...face(e,"bold"),fontSize:xx,color:t.brandInk},closeButton:{width:kx,height:kx,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:n.md+Tx,paddingVertical:n.sm+Tx,borderWidth:1,borderColor:t.borderRingCream,...ug(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:i.size.bodyTight,color:t.text.primary,padding:0,...dg(l.input)},countLabel:{...face(e,"mono"),fontSize:wx,color:t.text.muted},list:{gap:n.xs,paddingBottom:n.xl},listEmpty:{flexGrow:1},item:{paddingVertical:n.sm+Tx,paddingHorizontal:n.sm,borderRadius:e.radius.md,gap:Tx},itemActive:{backgroundColor:El(t.highlight,vx)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:n.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:i.size.bodyTight,color:o},itemMeta:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.muted},unreadDot:{width:Rx,height:Rx,borderRadius:Rx/2,backgroundColor:t.danger},errorCard:{borderRadius:jx,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:n.md},errorText:{...face(e,"regular"),fontSize:i.size.caption,color:t.danger},emptyCard:{borderRadius:Sx,padding:n.md+Tx,gap:n.xs+Tx,backgroundColor:t.surfaceSubtle,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.borderRingCream,...ug(l.card,r.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:i.size.bodyTight,color:o,...s},emptyBody:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.secondary,...s},noMatch:{...face(e,"regular"),fontSize:i.size.bodyTight,color:t.text.muted,paddingVertical:n.sm},retrySlot:{marginTop:n.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:n.md+Tx,paddingVertical:n.sm,borderWidth:1,borderColor:t.brandInk,...ug(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:i.size.caption,color:t.brandInk,...dg(l.primaryButton)},loadMoreFooter:{paddingVertical:n.md+Tx,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.muted}})}function Ox(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let i=new Date(t);i.setHours(0,0,0,0);let l=new Date(n);l.setHours(0,0,0,0);let o=Math.round((i.getTime()-l.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function Ax(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function Mx(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=Ox(n.updatedAt,t)??"",i=r[r.length-1];i!==void 0&&i.day===e?i.rows.push(n):r.push({day:e,rows:[n]})}return r}var Fx="rgba(38,37,35,0.38)",Dx=28,Lx=40,Bx=5,Vx=11,Hx=10.5,Ux=36,Nx=11,$x=14,Wx=15,qx=13.5,Gx=48,Kx=2,Yx=1.3,Qx=.12,Xx=16,Zx=8,Jx="80%";function ew(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */l.jsx(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:i,sheet:o}){let s=useEverfurTheme(),a=t.useMemo(()=>tw(s),[s]),u=n.useSafeAreaInsets(),c=t.useMemo(()=>Mx(i.rows),[i.rows]);if(!i.open)return null;let d=s.color,f=o?.title?.trim(),h=f!==void 0&&f!==""?f:Zh.heading;/* @__PURE__ */
240
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:i.itemTitle,numberOfLines:1,children:pp(e.title)}),s?/* @__PURE__ */l.jsx(r.View,{style:i.unreadDot}):null]}),a!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.itemMeta,numberOfLines:1,children:a}):null]})}function Gx(e){let t=e.color,n=e.space,i=e.type,l=e.slots,o=t.text.primary,s=_g(l.card);return r.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Ox},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:n.lg,borderRightWidth:r.StyleSheet.hairlineWidth,borderRightColor:t.borderRingCream,gap:n.md,..._v(l.dialog,r.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:n.md},header:{flexDirection:"row",alignItems:"center",gap:n.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:i.size.subtitle,color:o,..._g(l.dialog)},newChat:{minHeight:Dx,justifyContent:"center",paddingHorizontal:n.xs},newChatLabel:{...face(e,"bold"),fontSize:Mx,color:t.brandInk},closeButton:{width:Dx,height:Dx,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:n.md+Nx,paddingVertical:n.sm+Nx,borderWidth:1,borderColor:t.borderRingCream,...Sg(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:i.size.bodyTight,color:t.text.primary,padding:0,..._g(l.input)},countLabel:{...face(e,"mono"),fontSize:Fx,color:t.text.muted},list:{gap:n.xs,paddingBottom:n.xl},listEmpty:{flexGrow:1},item:{paddingVertical:n.sm+Nx,paddingHorizontal:n.sm,borderRadius:e.radius.md,gap:Nx},itemActive:{backgroundColor:Ml(t.highlight,Ax)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:n.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:i.size.bodyTight,color:o},itemMeta:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.muted},unreadDot:{width:Ux,height:Ux,borderRadius:Ux/2,backgroundColor:t.danger},errorCard:{borderRadius:Vx,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:n.md},errorText:{...face(e,"regular"),fontSize:i.size.caption,color:t.danger},emptyCard:{borderRadius:Bx,padding:n.md+Nx,gap:n.xs+Nx,backgroundColor:t.surfaceSubtle,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.borderRingCream,...Sg(l.card,r.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:i.size.bodyTight,color:o,...s},emptyBody:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.secondary,...s},noMatch:{...face(e,"regular"),fontSize:i.size.bodyTight,color:t.text.muted,paddingVertical:n.sm},retrySlot:{marginTop:n.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:n.md+Nx,paddingVertical:n.sm,borderWidth:1,borderColor:t.brandInk,...Sg(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:i.size.caption,color:t.brandInk,..._g(l.primaryButton)},loadMoreFooter:{paddingVertical:n.md+Nx,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:i.size.caption,color:t.text.muted}})}function Kx(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let i=new Date(t);i.setHours(0,0,0,0);let l=new Date(n);l.setHours(0,0,0,0);let o=Math.round((i.getTime()-l.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function Yx(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function Qx(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=Kx(n.updatedAt,t)??"",i=r[r.length-1];i!==void 0&&i.day===e?i.rows.push(n):r.push({day:e,rows:[n]})}return r}var Xx="rgba(38,37,35,0.38)",Zx=28,Jx=40,ew=5,tw=11,rw=10.5,nw=36,iw=11,lw=14,ow=15,sw=13.5,aw=48,uw=2,cw=1.3,dw=.12,fw=16,hw=8,pw="80%";function gw(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */l.jsx(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:i,sheet:o}){let s=useEverfurTheme(),a=t.useMemo(()=>mw(s),[s]),u=n.useSafeAreaInsets(),c=t.useMemo(()=>Qx(i.rows),[i.rows]),d=lf();if(!i.open)return null;let f=s.color,h=o?.title?.trim(),p=h!==void 0&&h!==""?h:hp.heading;/* @__PURE__ */
241
241
  return l.jsx(r.Modal,{visible:true,transparent:true,animationType:"slide",onRequestClose:i.close,children:/* @__PURE__ */l.jsxs(r.View,{style:a.root,children:[
242
- /* @__PURE__ */l.jsx(r.Pressable,{style:[Ag,a.scrim],onPress:i.close,accessibilityRole:"button",accessibilityLabel:Zh.closeA11y}),
243
- /* @__PURE__ */l.jsxs(r.View,{style:[a.sheet,{paddingBottom:Math.max(40,u.bottom+s.space.lg)}],accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
242
+ /* @__PURE__ */l.jsx(r.Pressable,{style:[Yg,a.scrim],onPress:i.close,accessibilityRole:"button",accessibilityLabel:hp.closeA11y}),
243
+ /* @__PURE__ */l.jsxs(r.View,{style:of([a.sheet,{paddingBottom:Math.max(40,u.bottom+s.space.lg)}],d),accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
244
244
  /* @__PURE__ */l.jsx(r.View,{style:a.grab}),
245
245
  /* @__PURE__ */l.jsxs(r.View,{style:a.top,children:[
246
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.kicker,accessibilityRole:"header",children:h}),
247
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Zh.closeA11y,onPress:i.close,style:a.close,children:ew(o,"close",/* @__PURE__ */l.jsx(CloseGlyph,{size:22,color:d.text.primary,strokeWidth:2}))})]}),
248
- /* @__PURE__ */l.jsxs(r.ScrollView,{style:a.scroll,contentContainerStyle:a.scrollContent,keyboardShouldPersistTaps:"handled",children:[i.loading&&i.rows.length===0?/* @__PURE__ */l.jsxs(r.View,{style:a.state,accessibilityLabel:Zh.loading,accessibilityState:{busy:true},children:[
249
- /* @__PURE__ */l.jsx(r.ActivityIndicator,{color:d.brandInk}),
250
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.mono,children:Zh.loading})]}):null,i.error!==null?/* @__PURE__ */l.jsxs(r.View,{style:a.state,children:[
251
- /* @__PURE__ */l.jsx(Text,{style:a.stateText,accessibilityRole:"alert",children:Zh.loadFailed}),
252
- /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Zh.retry,onPress:()=>{i.load()},style:a.link,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.linkText,children:Zh.retry})})]}):null,!i.loading&&i.error===null&&i.rows.length===0?/* @__PURE__ */l.jsx(Text,{style:[a.stateText,a.state],children:Zh.empty}):null,c.map((n,s)=>/* @__PURE__ */l.jsxs(t.Fragment,{children:[n.day?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.mono,a.day,s===0?a.dayFirst:null],children:n.day}):null,n.rows.map(t=>{let n=t.id===e.conversationId,s=t.unreadCount!==null&&t.unreadCount>0,u=Ax(t.updatedAt);/* @__PURE__ */
253
- return l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:np(t),accessibilityState:{selected:n},onPress:()=>{i.resume(t.id)},style:[a.row,n?a.rowCurrent:null],children:[
254
- /* @__PURE__ */l.jsx(r.View,{style:a.icon,children:ew(o,"chat",/* @__PURE__ */l.jsx(ChatBubbleGlyph,{size:19,color:d.linkInk,strokeWidth:1.75}))}),
246
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.kicker,accessibilityRole:"header",children:p}),
247
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:hp.closeA11y,onPress:i.close,style:a.close,children:gw(o,"close",/* @__PURE__ */l.jsx(CloseGlyph,{size:22,color:f.text.primary,strokeWidth:2}))})]}),
248
+ /* @__PURE__ */l.jsxs(r.ScrollView,{style:a.scroll,contentContainerStyle:a.scrollContent,keyboardShouldPersistTaps:"handled",children:[i.loading&&i.rows.length===0?/* @__PURE__ */l.jsxs(r.View,{style:a.state,accessibilityLabel:hp.loading,accessibilityState:{busy:true},children:[
249
+ /* @__PURE__ */l.jsx(r.ActivityIndicator,{color:f.brandInk}),
250
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.mono,children:hp.loading})]}):null,i.error!==null?/* @__PURE__ */l.jsxs(r.View,{style:a.state,children:[
251
+ /* @__PURE__ */l.jsx(Text,{style:a.stateText,accessibilityRole:"alert",children:hp.loadFailed}),
252
+ /* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:hp.retry,onPress:()=>{i.load()},style:a.link,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.linkText,children:hp.retry})})]}):null,!i.loading&&i.error===null&&i.rows.length===0?/* @__PURE__ */l.jsx(Text,{style:[a.stateText,a.state],children:hp.empty}):null,c.map((n,s)=>/* @__PURE__ */l.jsxs(t.Fragment,{children:[n.day?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.mono,a.day,s===0?a.dayFirst:null],children:n.day}):null,n.rows.map(t=>{let n=t.id===e.conversationId,s=t.unreadCount!==null&&t.unreadCount>0,u=Yx(t.updatedAt);/* @__PURE__ */
253
+ return l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:yp(t),accessibilityState:{selected:n},onPress:()=>{i.resume(t.id)},style:[a.row,n?a.rowCurrent:null],children:[
254
+ /* @__PURE__ */l.jsx(r.View,{style:a.icon,children:gw(o,"chat",/* @__PURE__ */l.jsx(ChatBubbleGlyph,{size:19,color:f.linkInk,strokeWidth:1.75}))}),
255
255
  /* @__PURE__ */l.jsxs(r.View,{style:a.rowWords,children:[
256
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.rowTitle,numberOfLines:1,children:Jh(t.title)}),t.preview!==void 0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.preview,numberOfLines:1,children:t.preview}):null]}),
257
- /* @__PURE__ */l.jsxs(r.View,{style:a.rowEnd,children:[u!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.mono,a.time,s?a.timeUnread:null],children:u}):null,s?/* @__PURE__ */l.jsx(r.View,{style:a.unreadDot,testID:`everfur-history-sheet-unread-${String(t.id)}`}):null]})]},String(t.id))})]},n.day)),i.cursor!==null&&!i.loadingMore?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Zh.more,onPress:i.loadMore,style:a.link,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.linkText,children:Zh.more})}):null]}),
258
- /* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:Zh.newChat,onPress:i.newConversation,style:a.newChat,children:[ew(o,"edit",/* @__PURE__ */l.jsx(EditGlyph,{size:18,color:s.slots.primaryButton?.textColor??d.onPrimary,strokeWidth:1.75})),
259
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.newChatText,children:Zh.newChat})]})]})]})})}function tw(e){let t=e.color,n=e.space,i={...face(e,"mono"),fontSize:Hx,letterSpacing:Hx*.06,textTransform:"uppercase",color:t.text.muted};return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:Fx},sheet:{maxHeight:Jx,backgroundColor:t.surface,borderTopLeftRadius:Dx,borderTopRightRadius:Dx,paddingTop:10,paddingHorizontal:20},grab:{width:Lx,height:Bx,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...i,fontSize:Vx,letterSpacing:Vx*.08,flexShrink:1},close:{width:im,height:im,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:im/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:n.xs},mono:i,day:{marginTop:n.lg,marginBottom:n.xs},dayFirst:{marginTop:Kx},state:{marginVertical:n.md,gap:n.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:im,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:n.md,paddingVertical:10,paddingHorizontal:n.sm,borderRadius:$x,minHeight:im},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:Ux,height:Ux,borderRadius:Nx,backgroundColor:El(t.linkInk,Qx)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:Wx,lineHeight:Wx*Yx,color:t.text.primary},preview:{...face(e,"regular"),fontSize:qx,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:Hx*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:Zx,height:Zx,borderRadius:Zx/2,backgroundColor:t.danger},newChat:{marginTop:n.lg,minHeight:Gx,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...ug(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:Xx,color:t.onPrimary,...dg(e.slots.primaryButton)}})}var rw="Close",nw=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${iw(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function iw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...nw,...t.copy},i={pet:e.pet,possessive:healthPlanPossessive(e.pet)},l=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,s=o===void 0?null:n.action(i),a=n.close(i),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(i)?.trim()||r.kicker,a=n.resultsClose(i),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...l===void 0?{}:{badge:l},title:r.title,results:[f,...c.rows??[]],...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?rw:a,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...l===void 0?{}:{badge:l},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?rw:a,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function lw(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function ow(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var sw=20,aw=14,uw=16,cw=18,dw=22,fw=15,hw=12,pw=24,gw=15,mw=14.5,bw=21,yw=14.5,vw=18,xw=9,ww=36,kw=14,Cw=15,Sw=8,jw=40;function TopCard({card:e,open:n,onOpenChange:i,ask:o}){let s=useEverfurTheme(),a=sx(),u=t.useMemo(()=>a!==null?Rw(a):Tw(s),[s,a]),c=t.useMemo(()=>ug(s.slots.card),[s.slots.card]);if(!n)return null;let d=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:Yd.close,f=e.action,h=e.ask,p=/* @__PURE__ */l.jsx(CloseGlyph,{size:a!==null?HOME_CLOSE_GLYPH(a):vw,color:a!==null?String(a.text(".ask-focus__x").color):s.color.text.primary,strokeWidth:2});/* @__PURE__ */
256
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.rowTitle,numberOfLines:1,children:pp(t.title)}),t.preview!==void 0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:a.preview,numberOfLines:1,children:t.preview}):null]}),
257
+ /* @__PURE__ */l.jsxs(r.View,{style:a.rowEnd,children:[u!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.mono,a.time,s?a.timeUnread:null],children:u}):null,s?/* @__PURE__ */l.jsx(r.View,{style:a.unreadDot,testID:`everfur-history-sheet-unread-${String(t.id)}`}):null]})]},String(t.id))})]},n.day)),i.cursor!==null&&!i.loadingMore?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:hp.more,onPress:i.loadMore,style:a.link,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.linkText,children:hp.more})}):null]}),
258
+ /* @__PURE__ */l.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:hp.newChat,onPress:i.newConversation,style:a.newChat,children:[gw(o,"edit",/* @__PURE__ */l.jsx(EditGlyph,{size:18,color:s.slots.primaryButton?.textColor??f.onPrimary,strokeWidth:1.75})),
259
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.newChatText,children:hp.newChat})]})]})]})})}function mw(e){let t=e.color,n=e.space,i={...face(e,"mono"),fontSize:rw,letterSpacing:rw*.06,textTransform:"uppercase",color:t.text.muted};return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:Xx},sheet:{maxHeight:pw,backgroundColor:t.surface,borderTopLeftRadius:Zx,borderTopRightRadius:Zx,paddingTop:10,paddingHorizontal:20},grab:{width:Jx,height:ew,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...i,fontSize:tw,letterSpacing:tw*.08,flexShrink:1},close:{width:vm,height:vm,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:vm/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:n.xs},mono:i,day:{marginTop:n.lg,marginBottom:n.xs},dayFirst:{marginTop:uw},state:{marginVertical:n.md,gap:n.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:vm,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:n.md,paddingVertical:10,paddingHorizontal:n.sm,borderRadius:lw,minHeight:vm},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:nw,height:nw,borderRadius:iw,backgroundColor:Ml(t.linkInk,dw)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:ow,lineHeight:ow*cw,color:t.text.primary},preview:{...face(e,"regular"),fontSize:sw,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:rw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:hw,height:hw,borderRadius:hw/2,backgroundColor:t.danger},newChat:{marginTop:n.lg,minHeight:aw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...Sg(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:fw,color:t.onPrimary,..._g(e.slots.primaryButton)}})}var bw="Close",yw=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${vw(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function vw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...yw,...t.copy},i={pet:e.pet,possessive:healthPlanPossessive(e.pet)},l=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,s=o===void 0?null:n.action(i),a=n.close(i),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(i)?.trim()||r.kicker,a=n.resultsClose(i),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...l===void 0?{}:{badge:l},title:r.title,results:[f,...c.rows??[]],...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?bw:a,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...l===void 0?{}:{badge:l},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?bw:a,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function xw(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function ww(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var kw=20,Cw=14,Sw=16,jw=18,_w=22,Rw=15,Tw=12,Iw=24,Pw=15,zw=14.5,Ew=21,Ow=14.5,Aw=18,Mw=9,Fw=36,Dw=14,Lw=15,Bw=8,Vw=40;function TopCard({card:e,open:n,onOpenChange:i,ask:o}){let s=useEverfurTheme(),a=kx(),u=t.useMemo(()=>a!==null?Uw(a):Nw(s),[s,a]),c=t.useMemo(()=>Sg(s.slots.card),[s.slots.card]);if(!n)return null;let d=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:df.close,f=e.action,h=e.ask,p=/* @__PURE__ */l.jsx(CloseGlyph,{size:a!==null?HOME_CLOSE_GLYPH(a):Aw,color:a!==null?String(a.text(".ask-focus__x").color):s.color.text.primary,strokeWidth:2});/* @__PURE__ */
260
260
  return l.jsxs(r.View,{style:[u.card,c],testID:"everfur-top-card",children:[
261
261
  /* @__PURE__ */l.jsxs(r.View,{style:u.kickerRow,children:[
262
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:u.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */l.jsx(r.View,{style:u.badge,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:u.badgeText,numberOfLines:1,children:e.badge})}):null,d!==null?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>i(false),accessibilityRole:"button",accessibilityLabel:d,style:u.close,hitSlop:a!==null?_w:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */l.jsx(HostRender,{render:()=>e.renderIcon?.("close"),fallback:p}):p}):null]}),
262
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:u.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */l.jsx(r.View,{style:u.badge,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:u.badgeText,numberOfLines:1,children:e.badge})}):null,d!==null?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>i(false),accessibilityRole:"button",accessibilityLabel:d,style:u.close,hitSlop:a!==null?Hw:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */l.jsx(HostRender,{render:()=>e.renderIcon?.("close"),fallback:p}):p}):null]}),
263
263
  /* @__PURE__ */l.jsx(Text,{tier:"heading",style:u.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */l.jsxs(r.View,{style:u.finding,children:[
264
264
  /* @__PURE__ */l.jsx(r.View,{style:u.dot}),
265
- /* @__PURE__ */l.jsxs(Text,{style:u.findingText,children:[e.lead!==void 0?/* @__PURE__ */l.jsx(Text,{style:u.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,f!==void 0||h!==void 0?/* @__PURE__ */l.jsxs(r.View,{style:u.actions,children:[f!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{Hf(f.onPress)},accessibilityRole:"button",accessibilityLabel:f.label,style:u.action,hitSlop:a!==null?_w:void 0,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.actionText,children:f.label})}):null,h!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>o(h.prompt),accessibilityRole:"button",accessibilityLabel:h.label,style:u.ask,hitSlop:a!==null?_w:void 0,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.askText,children:h.label})}):null]}):null]})}function TopCardPill({card:e,open:n,onOpenChange:i}){let o=useEverfurTheme(),s=sx(),a=t.useMemo(()=>s!==null?Rw(s):Tw(o),[o,s]);if(n||e.closeLabel===void 0)return null;let u=e.pill??e.kicker;/* @__PURE__ */
266
- return l.jsxs(r.Pressable,{onPress:()=>i(true),accessibilityRole:"button",accessibilityLabel:u,accessibilityState:{expanded:false},style:a.pill,hitSlop:s!==null?_w:void 0,testID:"everfur-top-card-pill",children:[
265
+ /* @__PURE__ */l.jsxs(Text,{style:u.findingText,children:[e.lead!==void 0?/* @__PURE__ */l.jsx(Text,{style:u.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,f!==void 0||h!==void 0?/* @__PURE__ */l.jsxs(r.View,{style:u.actions,children:[f!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{rh(f.onPress)},accessibilityRole:"button",accessibilityLabel:f.label,style:u.action,hitSlop:a!==null?Hw:void 0,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.actionText,children:f.label})}):null,h!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>o(h.prompt),accessibilityRole:"button",accessibilityLabel:h.label,style:u.ask,hitSlop:a!==null?Hw:void 0,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.askText,children:h.label})}):null]}):null]})}function TopCardPill({card:e,open:n,onOpenChange:i}){let o=useEverfurTheme(),s=kx(),a=t.useMemo(()=>s!==null?Uw(s):Nw(o),[o,s]);if(n||e.closeLabel===void 0)return null;let u=e.pill??e.kicker;/* @__PURE__ */
266
+ return l.jsxs(r.Pressable,{onPress:()=>i(true),accessibilityRole:"button",accessibilityLabel:u,accessibilityState:{expanded:false},style:a.pill,hitSlop:s!==null?Hw:void 0,testID:"everfur-top-card-pill",children:[
267
267
  /* @__PURE__ */l.jsx(r.View,{style:a.pillDot}),
268
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.pillText,numberOfLines:1,children:u})]})}var _w=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:vw};function Rw(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),i=typeof n.height=="number"?n.height:xw;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-i)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function Tw(e){let t=e.color,n=e.space;return r.StyleSheet.create({card:{paddingTop:aw,paddingHorizontal:uw,paddingBottom:uw,borderRadius:sw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:im-8},kicker:{...ow(e),fontSize:fw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:pw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:hw,color:t.text.secondary},close:{width:im,height:im,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:im/2},title:{...ow(e),fontSize:cw,lineHeight:dw,color:t.text.primary,marginTop:n.xs},finding:{flexDirection:"row",gap:n.sm,marginTop:n.xs+2},dot:{width:xw,height:xw,borderRadius:xw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:mw,lineHeight:bw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.lg,marginTop:14},action:{minHeight:Math.max(jw,im),paddingHorizontal:n.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:gw,color:t.onPrimary},ask:{minHeight:im,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:yw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:Math.max(ww,im),paddingHorizontal:kw,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Sw,height:Sw,borderRadius:Sw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:Cw,color:t.danger,flexShrink:1}})}var Iw=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),Pw=/* @__PURE__ */new WeakMap;function zw(e){let t=Pw.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",i=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...Iw},l=(e,t)=>Al(e,t,_l(t),Ew),o=(e,t)=>contrastRatio(e,t)>=Ew?e:jl(t,Ew),s=[i.card,i.paper].map(e=>zl(r.brandSoft,e)??e),a={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:l(r.linkInk,[i.card,i.paper,i.tile]),badge:r.brandSoft,onBadge:l(r.brandInk,s)},u=/* @__PURE__ */Object.freeze({...i,...a});return Pw.set(e,u),u}var Ew=4.5;function Ow(e,t){for(let r of t)if(contrastRatio(r,e)>=Ew)return r;return jl(e,Ew)}function Aw(e,t,r){let n=El(e,t);return(n===null?null:zl(n,r))??r}function Mw(e){let t=zw(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:Ow(t.accent,[t.ink,t.onAccent]),accent2:Aw(t.accent,.75,n),accent4:Aw(t.accent,.17,n),accentChip:Aw(t.accent,.47,n),link:t.link,linkChip:Aw(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var Fw=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),Dw=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),Lw=["paddingTop","paddingRight","paddingBottom","paddingLeft"],Bw=17,Vw=1.5,Hw=400,Uw=700;function Nw(e){return e<=450?"regular":e<=650?"medium":"bold"}function $w(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function Ww(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:$w(r)}}let n=t==="$serif"?headingFace(e,Nw(r)):face(e,Nw(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:$w(r)}}function qw(e,t,r={}){let n=Mw(e),i=e.brightness==="dark",l=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?i?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},s=/* @__PURE__ */new Map,a=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),i=n.join("|"),a=s.get(i);if(a!==void 0)return a;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),l&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return s.set(i,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=a(e),i={};for(let[e,t]of Object.entries(n))Fw.has(e)||Dw.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(i[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=i.height;delete i.height,typeof i.minHeight!="number"&&(i.minHeight=e)}let l=n.ring;if(Array.isArray(l)){let[e,t]=l;i.borderWidth=e,i.borderColor=t;for(let t of Lw){let r=i[t];typeof r=="number"&&(i[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;i.borderBottomWidth=e,i.borderBottomColor=t}let s=n.shadow;if(Array.isArray(s)){let[e,t,r,n]=s;i.shadowColor=n,i.shadowOffset={width:e,height:t},i.shadowOpacity=1,i.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;i.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(i);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let i=`${t}|${r.filter(Boolean).join("|")}`,l=d.get(i);if(l!==void 0)return l;let o=a(r),s=typeof o.fontSize=="number"?o.fontSize:Bw,u=typeof o.lh=="number"?o.lh:Vw,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...Ww(e,f,c),fontSize:s,lineHeight:Math.round(s*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*s*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(i,p),p};return{reduced:l,colors:n,view:c,text:(...e)=>f(Hw,e),strong:(...e)=>f(Uw,e),icon:(...e)=>{let t=a(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=a([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let i=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(i)?i:1,minWidth:0}},motion:(...e)=>{let t=a(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>a(t)[e]}}var Gw={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},Kw=16;var Yw=4e3,Qw=.5;function Xw(e,t,r){let n=1,i=-1;for(let l of e)i<0?i=l:i+t+l<=r?i+=t+l:(n+=1,i=l);return n}function Zw(e,t,r){if(e.length===0)return r;let n=Xw(e,t,r),i=[];for(let n=0;n<e.length;n+=1){let l=0;for(let o=n;o<e.length;o+=1)l+=(o>n?t:0)+e[o],l<=r&&i.push(l)}i.sort((e,t)=>e-t);let l=Qw*e.length+1;for(let o of i)if(Xw(e,t,o)<=n)return Math.min(r,o+l);return r}function BalancedTitle({text:e,style:n,measureCh:i}){let o=t.useMemo(()=>e.split(/\s+/).filter(e=>e!==""),[e]),s=r.StyleSheet.flatten(n),a=[e,s.fontFamily,s.fontSize,s.fontWeight,s.letterSpacing].join("|"),u=t.useRef({key:"",ch:null,line:null,words:[]});u.current.key!==a&&(u.current={key:a,ch:null,line:null,words:o.map(()=>null)});let[c,d]=t.useState(null),f=c!==null&&c.key===a?c.value:null,h=()=>{let e=u.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,r=t.reduce((e,t)=>e+t,0),n=t.length>1?Math.max(0,(e.line-r)/(t.length-1)):0,l=Zw(t,n,(e.ch+Qw)*i);d(t=>t!==null&&t.key===e.key&&t.value===l?t:{key:e.key,value:l})},p=e=>t=>{u.current.key===a&&(e(u.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
269
- return l.jsxs(r.View,{style:Jw.wrap,children:[
268
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:a.pillText,numberOfLines:1,children:u})]})}var Hw=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:Aw};function Uw(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),i=typeof n.height=="number"?n.height:Mw;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-i)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function Nw(e){let t=e.color,n=e.space;return r.StyleSheet.create({card:{paddingTop:Cw,paddingHorizontal:Sw,paddingBottom:Sw,borderRadius:kw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:vm-8},kicker:{...ww(e),fontSize:Rw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Iw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Tw,color:t.text.secondary},close:{width:vm,height:vm,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:vm/2},title:{...ww(e),fontSize:jw,lineHeight:_w,color:t.text.primary,marginTop:n.xs},finding:{flexDirection:"row",gap:n.sm,marginTop:n.xs+2},dot:{width:Mw,height:Mw,borderRadius:Mw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:zw,lineHeight:Ew,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.lg,marginTop:14},action:{minHeight:Math.max(Vw,vm),paddingHorizontal:n.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Pw,color:t.onPrimary},ask:{minHeight:vm,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Ow,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:Math.max(Fw,vm),paddingHorizontal:Dw,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Bw,height:Bw,borderRadius:Bw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:Lw,color:t.danger,flexShrink:1}})}var $w=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),Ww=/* @__PURE__ */new WeakMap;function qw(e){let t=Ww.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",i=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...$w},l=(e,t)=>Dl(e,t,Il(t),Gw),o=(e,t)=>contrastRatio(e,t)>=Gw?e:Tl(t,Gw),s=[i.card,i.paper].map(e=>Al(r.brandSoft,e)??e),a={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:l(r.linkInk,[i.card,i.paper,i.tile]),badge:r.brandSoft,onBadge:l(r.brandInk,s)},u=/* @__PURE__ */Object.freeze({...i,...a});return Ww.set(e,u),u}var Gw=4.5;function Kw(e,t){for(let r of t)if(contrastRatio(r,e)>=Gw)return r;return Tl(e,Gw)}function Yw(e,t,r){let n=Ml(e,t);return(n===null?null:Al(n,r))??r}function Qw(e){let t=qw(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:Kw(t.accent,[t.ink,t.onAccent]),accent2:Yw(t.accent,.75,n),accent4:Yw(t.accent,.17,n),accentChip:Yw(t.accent,.47,n),link:t.link,linkChip:Yw(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var Xw=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),Zw=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),Jw=["paddingTop","paddingRight","paddingBottom","paddingLeft"],ek=17,tk=1.5,rk=400,nk=700;function ik(e){return e<=450?"regular":e<=650?"medium":"bold"}function lk(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function sk(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:lk(r)}}let n=t==="$serif"?headingFace(e,ik(r)):face(e,ik(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:lk(r)}}function ak(e,t,r={}){let n=Qw(e),i=e.brightness==="dark",l=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?i?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},s=/* @__PURE__ */new Map,a=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),i=n.join("|"),a=s.get(i);if(a!==void 0)return a;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),l&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return s.set(i,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=a(e),i={};for(let[e,t]of Object.entries(n))Xw.has(e)||Zw.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(i[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=i.height;delete i.height,typeof i.minHeight!="number"&&(i.minHeight=e)}let l=n.ring;if(Array.isArray(l)){let[e,t]=l;i.borderWidth=e,i.borderColor=t;for(let t of Jw){let r=i[t];typeof r=="number"&&(i[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;i.borderBottomWidth=e,i.borderBottomColor=t}let s=n.shadow;if(Array.isArray(s)){let[e,t,r,n]=s;i.shadowColor=n,i.shadowOffset={width:e,height:t},i.shadowOpacity=1,i.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;i.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(i);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let i=`${t}|${r.filter(Boolean).join("|")}`,l=d.get(i);if(l!==void 0)return l;let o=a(r),s=typeof o.fontSize=="number"?o.fontSize:ek,u=typeof o.lh=="number"?o.lh:tk,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...sk(e,f,c),fontSize:s,lineHeight:Math.round(s*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*s*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(i,p),p};return{reduced:l,colors:n,view:c,text:(...e)=>f(rk,e),strong:(...e)=>f(nk,e),icon:(...e)=>{let t=a(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=a([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let i=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(i)?i:1,minWidth:0}},motion:(...e)=>{let t=a(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>a(t)[e]}}var uk={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},ck=16;var dk=4e3,fk=.5;function hk(e,t,r){let n=1,i=-1;for(let l of e)i<0?i=l:i+t+l<=r?i+=t+l:(n+=1,i=l);return n}function pk(e,t,r){if(e.length===0)return r;let n=hk(e,t,r),i=[];for(let n=0;n<e.length;n+=1){let l=0;for(let o=n;o<e.length;o+=1)l+=(o>n?t:0)+e[o],l<=r&&i.push(l)}i.sort((e,t)=>e-t);let l=fk*e.length+1;for(let o of i)if(hk(e,t,o)<=n)return Math.min(r,o+l);return r}function BalancedTitle({text:e,style:n,measureCh:i}){let o=t.useMemo(()=>e.split(/\s+/).filter(e=>e!==""),[e]),s=r.StyleSheet.flatten(n),a=[e,s.fontFamily,s.fontSize,s.fontWeight,s.letterSpacing].join("|"),u=t.useRef({key:"",ch:null,line:null,words:[]});u.current.key!==a&&(u.current={key:a,ch:null,line:null,words:o.map(()=>null)});let[c,d]=t.useState(null),f=c!==null&&c.key===a?c.value:null,h=()=>{let e=u.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,r=t.reduce((e,t)=>e+t,0),n=t.length>1?Math.max(0,(e.line-r)/(t.length-1)):0,l=pk(t,n,(e.ch+fk)*i);d(t=>t!==null&&t.key===e.key&&t.value===l?t:{key:e.key,value:l})},p=e=>t=>{u.current.key===a&&(e(u.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
269
+ return l.jsxs(r.View,{style:gk.wrap,children:[
270
270
  /* @__PURE__ */l.jsx(Text,{tier:"heading",style:f===null?n:[n,{maxWidth:f}],accessibilityRole:"header",children:e}),
271
- /* @__PURE__ */l.jsx(r.View,{style:Jw.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */l.jsxs(r.View,{style:Jw.probeRow,children:[
271
+ /* @__PURE__ */l.jsx(r.View,{style:gk.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */l.jsxs(r.View,{style:gk.probeRow,children:[
272
272
  /* @__PURE__ */l.jsx(Text,{tier:"heading",style:n,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
273
- /* @__PURE__ */l.jsx(Text,{tier:"heading",style:n,onLayout:p((e,t)=>{e.line=t}),children:o.join(" ")}),o.map((e,t)=>/* @__PURE__ */l.jsx(Text,{tier:"heading",style:n,onLayout:p((e,r)=>{e.words[t]=r}),children:e},`${t}:${e}`))]})})]})}var Jw=r.StyleSheet.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:Yw,flexDirection:"row",alignItems:"flex-start"}});function ek(e){return{kit:qw(e,Gw),Title:BalancedTitle,titleCh:Kw}}var tk=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function rk(){let e=globalThis,t=e[tk];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[tk]=r,r}var nk=e=>{let t=rk();return t.listeners.add(e),()=>t.listeners.delete(e)},ik=()=>rk().count>0;function useHostPoweredBy(){return t.useSyncExternalStore(nk,ik,ik)}var lk=/* @__PURE__ */Object.freeze({}),sk=100,ak=20;function uk(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function ck(e,n){let i=typeof e=="number"&&Number.isFinite(e),l=t.useRef(null),[o,s]=t.useState(null),a=t.useRef(null),u=t.useRef(null),c=t.useRef(true),d=t.useCallback(()=>{u.current!==null&&clearTimeout(u.current),u.current=null},[]);t.useEffect(()=>(c.current=true,()=>{c.current=false,d()}),[d]);let f=t.useCallback(function e(t){l.current?.measureInWindow((n,i)=>{let l=a.current;if(!c.current||l===null)return;let o=uk(i,l.y,l.height,r.Dimensions.get("window").height);if(o!==null){s(e=>e!==null&&e.chatTop===o.chatTop&&e.parentTop===o.parentTop?e:o);return}t>=ak||(u.current=setTimeout(()=>{u.current=null,e(t+1)},sk))})},[]),h=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;a.current={y:t,height:r},d(),f(0)},[f,d]);return t.useMemo(()=>{if(!n)return{avoidingProps:i?{keyboardVerticalOffset:e}:lk,probeRef:null,topInWindow:null};let t=o?.parentTop??0;return{avoidingProps:i?{keyboardVerticalOffset:e,onLayout:h}:t>0?{keyboardVerticalOffset:t,onLayout:h}:{onLayout:h},probeRef:l,topInWindow:o?.chatTop??null}},[n,i,e,o,h])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */l.jsx(r.View,{ref:e,collapsable:false,pointerEvents:"none",style:dk})}var dk=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function fk(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=r.Keyboard;if(typeof e?.addListener!="function")return;let t=r.Platform.OS==="ios",i=e.addListener(t?"keyboardWillShow":"keyboardDidShow",()=>n(true)),l=e.addListener(t?"keyboardWillHide":"keyboardDidHide",()=>n(false));return()=>{i.remove(),l.remove()}},[]),e}function hk(e,t,r){return Al(e,t,_l(t),r)}function pk(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=Jy(t),i=r?n.warning:n.info,l=Zy(t)&&!i?e:gk(e,t,r);return mk(l,t.slots.banner)}function gk(e,t,r){let n=t.color,i=zl(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,l=r?n.cautionAccent:n.infoEdge,o=hk(zl(l,n.surface)??l,[n.surface,n.chatGround],Yl),s=hk(r?n.warningStrong:n.info,[i,n.surface],Hl);/* @__PURE__ */
274
- return Object.freeze({...e,borderColor:o,backgroundColor:i,textColor:s,reasonColor:hk(n.text.primary,[i],Hl),pillColor:n.surface})}function mk(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function bk(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}var yk=.75,vk=1.5,xk=.4,wk=4,kk=1.5,Ck=22,Sk=14,jk=8,_k=20,Rk=10,Tk=13,Ik=12,Pk=15,zk=44,Ek=14,Ok=1.25,Ak=14,Mk=6,Fk=2;function Dk(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:El(r.danger,xk)??r.danger,borderWidth:vk},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:yk,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:r,renderVetAction:n,onFindVet:i,vet:o,compact:s=false}){let a=useEverfurTheme(),u=t.useMemo(()=>Lk(a),[a]),c=Mp(),d=e.tier===null?null:pk(e.tier,a),f=e.source;/* @__PURE__ */
273
+ /* @__PURE__ */l.jsx(Text,{tier:"heading",style:n,onLayout:p((e,t)=>{e.line=t}),children:o.join(" ")}),o.map((e,t)=>/* @__PURE__ */l.jsx(Text,{tier:"heading",style:n,onLayout:p((e,r)=>{e.words[t]=r}),children:e},`${t}:${e}`))]})})]})}var gk=r.StyleSheet.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:dk,flexDirection:"row",alignItems:"flex-start"}});function mk(e){return{kit:ak(e,uk),Title:BalancedTitle,titleCh:ck}}var bk=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function yk(){let e=globalThis,t=e[bk];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[bk]=r,r}var vk=e=>{let t=yk();return t.listeners.add(e),()=>t.listeners.delete(e)},xk=()=>yk().count>0;function useHostPoweredBy(){return t.useSyncExternalStore(vk,xk,xk)}var wk=/* @__PURE__ */Object.freeze({}),kk=100,Ck=20;function Sk(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function jk(e,n){let i=typeof e=="number"&&Number.isFinite(e),l=t.useRef(null),[o,s]=t.useState(null),a=t.useRef(null),u=t.useRef(null),c=t.useRef(true),d=t.useCallback(()=>{u.current!==null&&clearTimeout(u.current),u.current=null},[]);t.useEffect(()=>(c.current=true,()=>{c.current=false,d()}),[d]);let f=t.useCallback(function e(t){l.current?.measureInWindow((n,i)=>{let l=a.current;if(!c.current||l===null)return;let o=Sk(i,l.y,l.height,r.Dimensions.get("window").height);if(o!==null){s(e=>e!==null&&e.chatTop===o.chatTop&&e.parentTop===o.parentTop?e:o);return}t>=Ck||(u.current=setTimeout(()=>{u.current=null,e(t+1)},kk))})},[]),h=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;a.current={y:t,height:r},d(),f(0)},[f,d]);return t.useMemo(()=>{if(!n)return{avoidingProps:i?{keyboardVerticalOffset:e}:wk,probeRef:null,topInWindow:null};let t=o?.parentTop??0;return{avoidingProps:i?{keyboardVerticalOffset:e,onLayout:h}:t>0?{keyboardVerticalOffset:t,onLayout:h}:{onLayout:h},probeRef:l,topInWindow:o?.chatTop??null}},[n,i,e,o,h])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */l.jsx(r.View,{ref:e,collapsable:false,pointerEvents:"none",style:_k})}var _k=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function Rk(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=r.Keyboard;if(typeof e?.addListener!="function")return;let t=r.Platform.OS==="ios",i=e.addListener(t?"keyboardWillShow":"keyboardDidShow",()=>n(true)),l=e.addListener(t?"keyboardWillHide":"keyboardDidHide",()=>n(false));return()=>{i.remove(),l.remove()}},[]),e}function Tk(e,t,r){return Dl(e,t,Il(t),r)}function Ik(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=pv(t),i=r?n.warning:n.info,l=hv(t)&&!i?e:Pk(e,t,r);return zk(l,t.slots.banner)}function Pk(e,t,r){let n=t.color,i=Al(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,l=r?n.cautionAccent:n.infoEdge,o=Tk(Al(l,n.surface)??l,[n.surface,n.chatGround],Zl),s=Tk(r?n.warningStrong:n.info,[i,n.surface],$l);/* @__PURE__ */
274
+ return Object.freeze({...e,borderColor:o,backgroundColor:i,textColor:s,reasonColor:Tk(n.text.primary,[i],$l),pillColor:n.surface})}function zk(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function Ek(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}var Ok=.75,Ak=1.5,Mk=.4,Fk=4,Dk=1.5,Lk=22,Bk=14,Vk=8,Hk=20,Uk=10,Nk=13,$k=12,Wk=15,qk=44,Gk=14,Kk=1.25,Yk=14,Qk=6,Xk=2;function Zk(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:Ml(r.danger,Mk)??r.danger,borderWidth:Ak},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:Ok,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:r,renderVetAction:n,onFindVet:i,vet:o,compact:s=false}){let a=useEverfurTheme(),u=t.useMemo(()=>Jk(a),[a]),c=Qp(),d=e.tier===null?null:Ik(e.tier,a),f=e.source;/* @__PURE__ */
275
275
  return l.jsxs(l.Fragment,{children:[
276
276
  /* @__PURE__ */l.jsx(FadePresence,{visible:e.showBanner&&d!==null,inMs:c.bannerInMs,outMs:c.bannerOutMs,style:u.pinned,children:d!==null&&f!==null?/* @__PURE__ */l.jsx(BannerCard,{tier:d,reason:f.reason,surface:e,petRef:r,renderVetAction:n,onFindVet:i,vet:o,styles:u,compact:s}):null}),
277
- /* @__PURE__ */l.jsx(FadePresence,{visible:e.showCompactIcon,inMs:c.iconInMs,outMs:c.iconOutMs,style:u.indicatorRow,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.showLatestVetAlert,hitSlop:Rk,onPress:e.expand,children:/* @__PURE__ */l.jsx(InfoGlyph,{size:_k,color:a.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:n,petRef:i,renderVetAction:o,onFindVet:s,vet:a,styles:u,compact:c}){let d=useEverfurTheme(),f=Dk(d,e),h=/* @__PURE__ */l.jsx(VetAction,{tier:e,paint:f,petRef:i,onFindVet:s,vet:a,styles:u}),p=n.showVetAction?o!==void 0?/* @__PURE__ */l.jsx(HostRender,{render:()=>o(e.level),fallback:h,resetKey:e.level}):h:null,g=f.action!==null?/* @__PURE__ */l.jsx(PoisonControl,{paint:f.action,styles:u}):null,m=e.level==="emergency"&&s===void 0,b=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
277
+ /* @__PURE__ */l.jsx(FadePresence,{visible:e.showCompactIcon,inMs:c.iconInMs,outMs:c.iconOutMs,style:u.indicatorRow,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:df.showLatestVetAlert,hitSlop:Uk,onPress:e.expand,children:/* @__PURE__ */l.jsx(InfoGlyph,{size:Hk,color:a.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:n,petRef:i,renderVetAction:o,onFindVet:s,vet:a,styles:u,compact:c}){let d=useEverfurTheme(),f=Zk(d,e),h=/* @__PURE__ */l.jsx(VetAction,{tier:e,paint:f,petRef:i,onFindVet:s,vet:a,styles:u}),p=n.showVetAction?o!==void 0?/* @__PURE__ */l.jsx(HostRender,{render:()=>o(e.level),fallback:h,resetKey:e.level}):h:null,g=f.action!==null?/* @__PURE__ */l.jsx(PoisonControl,{paint:f.action,styles:u}):null,m=e.level==="emergency"&&s===void 0,b=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
278
278
  return l.jsxs(r.View,{...b?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[u.card,f.card,c?u.cardCompact:null],testID:c?"chat-urgency-compact":void 0,children:[
279
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:[u.label,{color:f.label}],children:e.label}),t!==null?/* @__PURE__ */l.jsx(Text,{style:[u.reason,{color:f.reason}],numberOfLines:c?Fk:void 0,accessibilityLabel:c?t:void 0,children:t}):null,m?/* @__PURE__ */l.jsx(Text,{style:[u.reason,u.erLine,{color:f.reason}],children:Yd.goToNearestEmergencyVet}):null,p!==null||g!==null?/* @__PURE__ */l.jsxs(r.View,{style:u.actions,children:[p,g]}):null,n.dismissLabel!==null?/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:n.dismissLabel,hitSlop:jk,containerStyle:u.closeSlot,style:u.closeButton,onPress:n.dismiss,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:Sk,color:f.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let n=()=>{try{r.Linking.openURL(Jd).catch(()=>{})}catch{}};/* @__PURE__ */
280
- return l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:n,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:Yd.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:i,styles:o}){let s=useEverfurTheme(),a=useVetVisit(bk(r,i)),u=a.status==="opening",c=!a.available&&n!==void 0,d=a.available?()=>{a.open()}:n!==void 0?()=>{Hf(n,e.level)}:null;if(d===null)return null;let f=t.action;if(f!==null){let e=c?Yd.nearestEmergencyVet:Yd.findVet,t=cg(s.slots.vetVisitButton)?.textColor??f.ink;/* @__PURE__ */
281
- return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:c?Yd.nearestEmergencyVet:Yd.findVetA11y,accessibilityState:{busy:u},hitSlop:0,style:[o.action,{backgroundColor:f.fill,borderColor:f.edge},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
282
- /* @__PURE__ */l.jsx(MapPinGlyph,{size:Tk,color:t,strokeWidth:1.5}),
283
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.actionLabel,{color:t}],children:e})]})}let h=cg(s.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
284
- return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:Yd.findVetA11y,accessibilityState:{busy:u},style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
285
- /* @__PURE__ */l.jsx(MapPinGlyph,{size:Tk,color:h,strokeWidth:1.5}),
286
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.findVetLabel,{color:h}],children:Yd.findVet})]})}function Lk(e){let t=cg(e.slots.vetVisitButton),n=e.space,i=e.type;return r.StyleSheet.create({pinned:{marginTop:0,marginBottom:n.xs,paddingHorizontal:n.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:n.lg+wk,paddingVertical:n.lg,gap:n.sm},cardCompact:{paddingVertical:n.md,gap:n.xs},label:{...face(e,"bold"),fontSize:i.size.body,paddingRight:Ck},reason:{...face(e,"regular"),fontSize:i.size.bodyTight,lineHeight:Math.round(i.size.bodyTight*kk),paddingRight:Ck},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm},action:{flexDirection:"row",alignItems:"center",gap:Mk,minHeight:zk,paddingHorizontal:Ek,borderRadius:e.radius.pill,borderWidth:Ok},actionLabel:{...face(e,"bold"),fontSize:Ak},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...ug(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:Ik,lineHeight:Pk},closeSlot:{position:"absolute",top:n.md,right:n.md},closeButton:{width:Ck,height:Ck,borderRadius:Ck/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:n.lg,paddingTop:2,paddingBottom:n.xs}})}function Bk(e,r,n,i){let[l,o]=t.useState({pet:n,user:r}),s=l.pet!==n||l.user===null&&r!==null;s&&o({pet:n,user:r});let a=s?{user:r}:l,u=n!==null&&a.user!==null&&a.user!==r;return t.useEffect(()=>{if(!u||r===null||n===null)return;let t=true,i=createPetsRepository(e.registry.services.authFor(r)),l=async()=>{let e=await i.list();t&&e.ok&&e.value.some(e=>e.petRef===n)&&o({pet:n,user:r})};l();let s=al(e,()=>{l()});return()=>{t=false,s()}},[u,e,r,n,i]),u}var Vk=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(e){let{runtime:r,userRef:n,activePet:i,scopeEpoch:l}=Lc(),o=e?.petRef??i??null,s=e?.conversationId??null,a=Bk(r,n,o,l),u=t.useMemo(()=>({runtime:r,userRef:n,petRef:o,conversationId:s,scopeEpoch:l,held:a}),[r,n,o,s,l,a]),[c,d]=t.useState(null),f=a?null:c?.scope===u?c.controller:r.registry.peekChat({userRef:n,petRef:o,conversationId:s}),h=t.useRef(null);t.useEffect(()=>{if(a)return;let e=r.registry.acquireChat({userRef:n,petRef:o,conversationId:s});return h.current=e,d({scope:u,controller:e}),()=>{h.current=null,d(t=>t?.controller===e?null:t),r.registry.releaseChat(e)}},[r,n,o,s,l,a,u]);let p=t.useCallback(e=>f?f.subscribe(e):NOOP_UNSUBSCRIBE,[f]),g=t.useCallback(()=>f?f.getSnapshot():Vk,[f]),m=t.useSyncExternalStore(p,g,g),b=t.useCallback((e,t)=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?Uk(f,f.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>h.current===f):Promise.resolve($k()),[f]),y=t.useCallback(e=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?Uk(f,f.askEverfur(e),()=>h.current===f):Promise.resolve($k()),[f]),v=t.useCallback(()=>f&&h.current===f?Uk(f,f.retryLast(),()=>h.current===f):Promise.resolve($k()),[f]),x=t.useCallback(()=>{f&&h.current===f&&f.stop()},[f]),w=t.useCallback(()=>{f&&h.current===f&&f.newConversation()},[f]),[k,C]=t.useState({controller:null,byMessage:{}}),S=k.controller===f?k.byMessage:Hk,j=t.useCallback(async(e,t,r,n)=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let i=String(e),l=k.controller===f?k.byMessage[i]:void 0;if(l===t&&r==null)return C(e=>{let t={...e.controller===f?e.byMessage:{}};return delete t[i],{controller:f,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));C(e=>({controller:f,byMessage:{...e.controller===f?e.byMessage:{},[i]:t}}));let o=await f.submitFeedback(e,Wv(t,r??null),n??null);return h.current!==f?err(makeEverfurError("accessDenied")):(o.ok||C(e=>{let t={...e.controller===f?e.byMessage:{}};return l===void 0?delete t[i]:t[i]=l,{controller:f,byMessage:t}}),o)},[f,k]),_=t.useMemo(()=>{let e=async e=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let t=await e(f);return h.current===f?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...o?{petRef:o}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[f,o]);return t.useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:o,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,..._,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,pendingCheckin:m.pendingCheckin??null,newConversation:w,sentimentByMessage:S,feedback:j,send:b,askEverfur:y,retryLast:v,stop:x}),[m,o,b,y,v,x,_,w,S,j])}var NOOP_UNSUBSCRIBE=()=>{},Hk=/* @__PURE__ */Object.freeze({});async function Uk(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(Nk(n.messages))}function Nk(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}function $k(){return jh()}function Wk(){let e=useEverfurPets(),{handle:r}=Lc(),n=t.useCallback(e=>r.setActivePet(e),[r]);return t.useMemo(()=>({...e,setActivePet:n}),[e,n])}function qk(){try{let e=r.AccessibilityInfo?.announceForAccessibility;typeof e=="function"&&e.call(r.AccessibilityInfo,Yd.answered)}catch{}}function Gk(e){let r=t.useRef(false),n=t.useRef({send:e.send,id:e.conversationId});t.useEffect(()=>{let t=n.current;if((t.send!==e.send||t.id!==null&&t.id!==e.conversationId)&&(r.current=false),n.current={send:e.send,id:e.conversationId},r.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&qk()}r.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var Kk=/* @__PURE__ */Object.freeze({kind:"live"}),Yk=/* @__PURE__ */Object.freeze({kind:"folded"});function Qk(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=Yr(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function Xk(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=Qk(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let i of e){let e=Qk(i);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===i.id){t.set(i.id,Kk),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(i.id,Yk);continue}let l=[e.dueDay];n={id:i.id,caseId:e.caseId,days:l},t.set(i.id,{kind:"past",runDueDays:l})}return t}function Zk(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var Jk=864e5,eC=365;function tC(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 i=Math.floor(n/Jk)-Math.floor(r/Jk);return i<1||i>eC?null:i}function rC(e){return Qk(e)?.dueDay||null}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"})}function AssistantSender({avatarUrl:e,named:t,styles:n}){let i=qy(e);return i.shown?/* @__PURE__ */l.jsxs(r.View,{style:n.assistantSender,testID:"everfur-assistant-sender",children:[
287
- /* @__PURE__ */l.jsx(BrandImage,{uri:e,decorative:true,style:n.assistantAvatar,resizeMode:"cover",onError:i.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */l.jsx(Text,{tier:"control",style:[n.assistantName,n.assistantNameInRow],children:Yd.assistantName}):null]}):t?/* @__PURE__ */l.jsx(Text,{tier:"control",style:n.assistantName,children:Yd.assistantName}):null}var iC=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),lC="#C8BEB4";function oC(e){return e?iC[e.toUpperCase()]??lC:lC}function sC(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function aC(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function uC(e){let t=aC(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function cC(e,t){let r=aC(e.source_name)??aC(e.sourceName),n=aC(e.section),i=aC(e.authority_tier)??aC(e.authorityTier),l=sC(i),o=r??aC(e.title)??`Source ${t+1}`,s=aC(e.monograph_chunk_id)??aC(e.chunkId),a=[n,l].filter(e=>e!==null).join(" · ");/* @__PURE__ */
288
- return Object.freeze({title:o,sourceName:r,section:n,authorityTier:i,tierLabel:l,meta:a.length===0?null:a,url:uC(e.url),excerpt:aC(e.excerpt),tierColor:oC(i),key:`${o}-${s??"none"}-${t}`})}function dC(e){return e===void 0||e.length===0?fC:/* @__PURE__ */Object.freeze(e.map((e,t)=>cC(e,t)))}var fC=/* @__PURE__ */Object.freeze([]);function hC(e){return e===1?`1 ${Yd.sourceSingular}`:`${e} ${Yd.sourcePlural}`}function pC(e,t){return`${t?Yd.hideSources:Yd.showSources} ${hC(e)}`}function gC(e){return[e.url!==null?`${Yd.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function mC(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var bC=/^\s*[-*]\s+(\S.*)$/,yC=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function vC(e){let t=[],r=[],n=null,i=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},l=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=bC.exec(t),o=e===null?yC.exec(t):null,s=e?.[1]??o?.[2];if(s===void 0){l(),r.push(t);continue}let a=o!==null;i(),n!==null&&n.ordered!==a&&l(),n===null&&(n={ordered:a,start:o===null?1:Number(o[1]),items:[]}),n.items.push(s.trim())}return i(),l(),t}function xC(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function wC(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function kC(e){return hardenHttpsUrl(e.trim())}function CC(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:wC(t.followUpActions,{answer:r.text,question:xC(e.messages,r.id),messageId:r.id})}var SC=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,jC=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${bp}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${bp}})`,"gi"),_C=/https:\/\//i,RC=`.,;:!?'"`;function TC(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&_C.test(e)}function IC(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):EC(r,e,t)},i=0;SC.lastIndex=0;for(let t=SC.exec(e);t!==null;t=SC.exec(e)){t.index>i&&n(e.slice(i,t.index));let l=t[1],o=t[2],s=t[3];l!==void 0?r.push({kind:"bold",text:l}):o!==void 0?r.push({kind:"italic",text:o}):s!==void 0&&r.push({kind:"code",text:s}),i=t.index+t[0].length}return i<e.length&&n(e.slice(i)),r}function PC(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(RC.includes(r))t-=1;else if(r===")"&&zC(e,"(",t)<zC(e,")",t))t-=1;else break}return e.slice(0,t)}function zC(e,t,r){let n=0;for(let i=0;i<r;i+=1)e[i]===t&&(n+=1);return n}function EC(e,t,r){if(!_C.test(t)){e.push({kind:"text",text:t});return}let n=0;jC.lastIndex=0;for(let i=jC.exec(t);i!==null;i=jC.exec(t)){let l=i[1],o=i[2],s=i[3],a,u,c;if(l!==void 0&&o!==void 0)a=l.trim(),u=a.length>0?wp(o,r):null,c=i[0].length;else if(s!==void 0)a=PC(s),u=wp(a,r),c=a.length;else continue;u!==null&&(i.index>n&&e.push({kind:"text",text:t.slice(n,i.index)}),e.push({kind:"link",text:a,href:u}),n=i.index+c,jC.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var OC=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function AC(e,t){return t===void 0||!TC(e,t.hosts)?false:IC(e,t.hosts).some(e=>e.kind==="link")}function MC(e,t,r){let n=r?.hosts;return TC(e,n)?IC(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
279
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:[u.label,{color:f.label}],children:e.label}),t!==null?/* @__PURE__ */l.jsx(Text,{style:[u.reason,{color:f.reason}],numberOfLines:c?Xk:void 0,accessibilityLabel:c?t:void 0,children:t}):null,m?/* @__PURE__ */l.jsx(Text,{style:[u.reason,u.erLine,{color:f.reason}],children:df.goToNearestEmergencyVet}):null,p!==null||g!==null?/* @__PURE__ */l.jsxs(r.View,{style:u.actions,children:[p,g]}):null,n.dismissLabel!==null?/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:n.dismissLabel,hitSlop:Vk,containerStyle:u.closeSlot,style:u.closeButton,onPress:n.dismiss,children:/* @__PURE__ */l.jsx(CloseGlyph,{size:Bk,color:f.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let n=()=>{try{r.Linking.openURL(gf).catch(()=>{})}catch{}};/* @__PURE__ */
280
+ return l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:df.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:n,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:df.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:i,styles:o}){let s=useEverfurTheme(),a=useVetVisit(Ek(r,i)),u=a.status==="opening",c=!a.available&&n!==void 0,d=a.available?()=>{a.open()}:n!==void 0?()=>{rh(n,e.level)}:null;if(d===null)return null;let f=t.action;if(f!==null){let e=c?df.nearestEmergencyVet:df.findVet,t=jg(s.slots.vetVisitButton)?.textColor??f.ink;/* @__PURE__ */
281
+ return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:c?df.nearestEmergencyVet:df.findVetA11y,accessibilityState:{busy:u},hitSlop:0,style:[o.action,{backgroundColor:f.fill,borderColor:f.edge},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
282
+ /* @__PURE__ */l.jsx(MapPinGlyph,{size:Nk,color:t,strokeWidth:1.5}),
283
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.actionLabel,{color:t}],children:e})]})}let h=jg(s.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
284
+ return l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:df.findVetA11y,accessibilityState:{busy:u},style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
285
+ /* @__PURE__ */l.jsx(MapPinGlyph,{size:Nk,color:h,strokeWidth:1.5}),
286
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.findVetLabel,{color:h}],children:df.findVet})]})}function Jk(e){let t=jg(e.slots.vetVisitButton),n=e.space,i=e.type;return r.StyleSheet.create({pinned:{marginTop:0,marginBottom:n.xs,paddingHorizontal:n.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:n.lg+Fk,paddingVertical:n.lg,gap:n.sm},cardCompact:{paddingVertical:n.md,gap:n.xs},label:{...face(e,"bold"),fontSize:i.size.body,paddingRight:Lk},reason:{...face(e,"regular"),fontSize:i.size.bodyTight,lineHeight:Math.round(i.size.bodyTight*Dk),paddingRight:Lk},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm},action:{flexDirection:"row",alignItems:"center",gap:Qk,minHeight:qk,paddingHorizontal:Gk,borderRadius:e.radius.pill,borderWidth:Kk},actionLabel:{...face(e,"bold"),fontSize:Yk},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...Sg(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:$k,lineHeight:Wk},closeSlot:{position:"absolute",top:n.md,right:n.md},closeButton:{width:Lk,height:Lk,borderRadius:Lk/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:n.lg,paddingTop:2,paddingBottom:n.xs}})}function eC(e,r,n,i){let[l,o]=t.useState({pet:n,user:r}),s=l.pet!==n||l.user===null&&r!==null;s&&o({pet:n,user:r});let a=s?{user:r}:l,u=n!==null&&a.user!==null&&a.user!==r;return t.useEffect(()=>{if(!u||r===null||n===null)return;let t=true,i=createPetsRepository(e.registry.services.authFor(r)),l=async()=>{let e=await i.list();t&&e.ok&&e.value.some(e=>e.petRef===n)&&o({pet:n,user:r})};l();let s=dl(e,()=>{l()});return()=>{t=false,s()}},[u,e,r,n,i]),u}var tC=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(e){let{runtime:r,userRef:n,activePet:i,scopeEpoch:l}=Hc(),o=e?.petRef??i??null,s=e?.conversationId??null,a=eC(r,n,o,l),u=t.useMemo(()=>({runtime:r,userRef:n,petRef:o,conversationId:s,scopeEpoch:l,held:a}),[r,n,o,s,l,a]),[c,d]=t.useState(null),f=a?null:c?.scope===u?c.controller:r.registry.peekChat({userRef:n,petRef:o,conversationId:s}),h=t.useRef(null);t.useEffect(()=>{if(a)return;let e=r.registry.acquireChat({userRef:n,petRef:o,conversationId:s});return h.current=e,d({scope:u,controller:e}),()=>{h.current=null,d(t=>t?.controller===e?null:t),r.registry.releaseChat(e)}},[r,n,o,s,l,a,u]);let p=t.useCallback(e=>f?f.subscribe(e):NOOP_UNSUBSCRIBE,[f]),g=t.useCallback(()=>f?f.getSnapshot():tC,[f]),m=t.useSyncExternalStore(p,g,g),b=t.useCallback((e,t)=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?nC(f,f.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>h.current===f):Promise.resolve(lC()),[f]),y=t.useCallback(e=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?nC(f,f.askEverfur(e),()=>h.current===f):Promise.resolve(lC()),[f]),v=t.useCallback(()=>f&&h.current===f?nC(f,f.retryLast(),()=>h.current===f):Promise.resolve(lC()),[f]),x=t.useCallback(()=>{f&&h.current===f&&f.stop()},[f]),w=t.useCallback(()=>{f&&h.current===f&&f.newConversation()},[f]),[k,C]=t.useState({controller:null,byMessage:{}}),S=k.controller===f?k.byMessage:rC,j=t.useCallback(async(e,t,r,n)=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let i=String(e),l=k.controller===f?k.byMessage[i]:void 0;if(l===t&&r==null)return C(e=>{let t={...e.controller===f?e.byMessage:{}};return delete t[i],{controller:f,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));C(e=>({controller:f,byMessage:{...e.controller===f?e.byMessage:{},[i]:t}}));let o=await f.submitFeedback(e,ox(t,r??null),n??null);return h.current!==f?err(makeEverfurError("accessDenied")):(o.ok||C(e=>{let t={...e.controller===f?e.byMessage:{}};return l===void 0?delete t[i]:t[i]=l,{controller:f,byMessage:t}}),o)},[f,k]),_=t.useMemo(()=>{let e=async e=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let t=await e(f);return h.current===f?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...o?{petRef:o}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[f,o]);return t.useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:o,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,..._,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,pendingCheckin:m.pendingCheckin??null,newConversation:w,sentimentByMessage:S,feedback:j,send:b,askEverfur:y,retryLast:v,stop:x}),[m,o,b,y,v,x,_,w,S,j])}var NOOP_UNSUBSCRIBE=()=>{},rC=/* @__PURE__ */Object.freeze({});async function nC(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(iC(n.messages))}function iC(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}function lC(){return Vh()}function oC(){let e=useEverfurPets(),{handle:r}=Hc(),n=t.useCallback(e=>r.setActivePet(e),[r]);return t.useMemo(()=>({...e,setActivePet:n}),[e,n])}function sC(){try{let e=r.AccessibilityInfo?.announceForAccessibility;typeof e=="function"&&e.call(r.AccessibilityInfo,df.answered)}catch{}}function aC(e){let r=t.useRef(false),n=t.useRef({send:e.send,id:e.conversationId});t.useEffect(()=>{let t=n.current;if((t.send!==e.send||t.id!==null&&t.id!==e.conversationId)&&(r.current=false),n.current={send:e.send,id:e.conversationId},r.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&sC()}r.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var uC=/* @__PURE__ */Object.freeze({kind:"live"}),cC=/* @__PURE__ */Object.freeze({kind:"folded"});function dC(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=Zr(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function fC(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=dC(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let i of e){let e=dC(i);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===i.id){t.set(i.id,uC),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(i.id,cC);continue}let l=[e.dueDay];n={id:i.id,caseId:e.caseId,days:l},t.set(i.id,{kind:"past",runDueDays:l})}return t}function hC(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var pC=864e5,gC=365;function mC(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 i=Math.floor(n/pC)-Math.floor(r/pC);return i<1||i>gC?null:i}function bC(e){return dC(e)?.dueDay||null}function yC(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:e,named:t,styles:n}){let i=sv(e);return i.shown?/* @__PURE__ */l.jsxs(r.View,{style:n.assistantSender,testID:"everfur-assistant-sender",children:[
287
+ /* @__PURE__ */l.jsx(BrandImage,{uri:e,decorative:true,style:n.assistantAvatar,resizeMode:"cover",onError:i.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */l.jsx(Text,{tier:"control",style:[n.assistantName,n.assistantNameInRow],children:df.assistantName}):null]}):t?/* @__PURE__ */l.jsx(Text,{tier:"control",style:n.assistantName,children:df.assistantName}):null}var vC=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),xC="#C8BEB4";function wC(e){return e?vC[e.toUpperCase()]??xC:xC}function kC(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function CC(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function SC(e){let t=CC(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function jC(e,t){let r=CC(e.source_name)??CC(e.sourceName),n=CC(e.section),i=CC(e.authority_tier)??CC(e.authorityTier),l=kC(i),o=r??CC(e.title)??`Source ${t+1}`,s=CC(e.monograph_chunk_id)??CC(e.chunkId),a=[n,l].filter(e=>e!==null).join(" · ");/* @__PURE__ */
288
+ return Object.freeze({title:o,sourceName:r,section:n,authorityTier:i,tierLabel:l,meta:a.length===0?null:a,url:SC(e.url),excerpt:CC(e.excerpt),tierColor:wC(i),key:`${o}-${s??"none"}-${t}`})}function _C(e){return e===void 0||e.length===0?RC:/* @__PURE__ */Object.freeze(e.map((e,t)=>jC(e,t)))}var RC=/* @__PURE__ */Object.freeze([]);function TC(e){return e===1?`1 ${df.sourceSingular}`:`${e} ${df.sourcePlural}`}function IC(e,t){return`${t?df.hideSources:df.showSources} ${TC(e)}`}function PC(e){return[e.url!==null?`${df.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function zC(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var EC=/^\s*[-*]\s+(\S.*)$/,OC=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function AC(e){let t=[],r=[],n=null,i=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},l=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=EC.exec(t),o=e===null?OC.exec(t):null,s=e?.[1]??o?.[2];if(s===void 0){l(),r.push(t);continue}let a=o!==null;i(),n!==null&&n.ordered!==a&&l(),n===null&&(n={ordered:a,start:o===null?1:Number(o[1]),items:[]}),n.items.push(s.trim())}return i(),l(),t}function MC(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function FC(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function DC(e){return hardenHttpsUrl(e.trim())}function LC(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:FC(t.followUpActions,{answer:r.text,question:MC(e.messages,r.id),messageId:r.id})}var BC=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,VC=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${Ep}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${Ep}})`,"gi"),HC=/https:\/\//i,UC=`.,;:!?'"`;function NC(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&HC.test(e)}function $C(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):GC(r,e,t)},i=0;BC.lastIndex=0;for(let t=BC.exec(e);t!==null;t=BC.exec(e)){t.index>i&&n(e.slice(i,t.index));let l=t[1],o=t[2],s=t[3];l!==void 0?r.push({kind:"bold",text:l}):o!==void 0?r.push({kind:"italic",text:o}):s!==void 0&&r.push({kind:"code",text:s}),i=t.index+t[0].length}return i<e.length&&n(e.slice(i)),r}function WC(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(UC.includes(r))t-=1;else if(r===")"&&qC(e,"(",t)<qC(e,")",t))t-=1;else break}return e.slice(0,t)}function qC(e,t,r){let n=0;for(let i=0;i<r;i+=1)e[i]===t&&(n+=1);return n}function GC(e,t,r){if(!HC.test(t)){e.push({kind:"text",text:t});return}let n=0;VC.lastIndex=0;for(let i=VC.exec(t);i!==null;i=VC.exec(t)){let l=i[1],o=i[2],s=i[3],a,u,c;if(l!==void 0&&o!==void 0)a=l.trim(),u=a.length>0?Fp(o,r):null,c=i[0].length;else if(s!==void 0)a=WC(s),u=Fp(a,r),c=a.length;else continue;u!==null&&(i.index>n&&e.push({kind:"text",text:t.slice(n,i.index)}),e.push({kind:"link",text:a,href:u}),n=i.index+c,VC.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var KC=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function YC(e,t){return t===void 0||!NC(e,t.hosts)?false:$C(e,t.hosts).some(e=>e.kind==="link")}function QC(e,t,r){let n=r?.hosts;return NC(e,n)?$C(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
289
289
  return l.jsx(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */l.jsx(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */l.jsx(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
290
- return l.jsx(Text,{style:OC,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var FC=10.5,DC=16,LC=12,BC=38,VC=11,HC=15,UC=22,NC=32,$C=13.5,WC=14,qC=15,GC=16,KC=13,YC=13,QC=26,XC=21,ZC=42,JC=1,eS=.06,tS=.07,rS=.12,nS="45%";function iS(){let e=useEverfurTheme(),r=t.useMemo(()=>lS(e),[e]);return{theme:e,styles:r}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */l.jsx(ChevronGlyph,{size:GC,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */l.jsx(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:n,styles:i}=iS();if(e.render!==void 0){let n=e.render;/* @__PURE__ */
291
- return l.jsx(r.View,{style:[i.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */l.jsx(HostRender,{render:n,fallback:null})})}let o=e.value!==void 0,s=t?.styles,a=[i.card,o?s?.cardStat:null,e.variant!==void 0?s?.cardVariant?.[e.variant]:null],u=e.tile?.tone,c=e.pill?.tone,d=e.tile?.imageUrl!==void 0?kC(e.tile.imageUrl):null,f=/* @__PURE__ */l.jsxs(l.Fragment,{children:[o?null:/* @__PURE__ */l.jsx(r.View,{style:[i.tile,u!==void 0?s?.tileTone?.[u]:null],children:d!==null?/* @__PURE__ */l.jsx(r.Image,{source:{uri:d},style:i.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
290
+ return l.jsx(Text,{style:KC,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var XC=10.5,ZC=16,JC=12,eS=38,tS=11,rS=15,nS=22,iS=32,lS=13.5,oS=14,sS=15,aS=16,uS=13,cS=13,dS=26,fS=21,hS=42,pS=1,gS=.06,mS=.07,bS=.12,yS="45%";function vS(){let e=useEverfurTheme(),r=t.useMemo(()=>xS(e),[e]);return{theme:e,styles:r}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */l.jsx(ChevronGlyph,{size:aS,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */l.jsx(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:n,styles:i}=vS();if(e.render!==void 0){let n=e.render;/* @__PURE__ */
291
+ return l.jsx(r.View,{style:[i.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */l.jsx(HostRender,{render:n,fallback:null})})}let o=e.value!==void 0,s=t?.styles,a=[i.card,o?s?.cardStat:null,e.variant!==void 0?s?.cardVariant?.[e.variant]:null],u=e.tile?.tone,c=e.pill?.tone,d=e.tile?.imageUrl!==void 0?DC(e.tile.imageUrl):null,f=/* @__PURE__ */l.jsxs(l.Fragment,{children:[o?null:/* @__PURE__ */l.jsx(r.View,{style:[i.tile,u!==void 0?s?.tileTone?.[u]:null],children:d!==null?/* @__PURE__ */l.jsx(r.Image,{source:{uri:d},style:i.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
292
292
  /* @__PURE__ */l.jsxs(r.View,{style:i.cardWords,children:[
293
293
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:i.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.cardMeta,children:e.meta}):null]}),o?/* @__PURE__ */l.jsxs(Text,{tier:"control",style:i.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */l.jsx(Text,{style:i.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */l.jsxs(l.Fragment,{children:[e.pill!==void 0?/* @__PURE__ */l.jsx(r.View,{style:[i.pill,c!==void 0?s?.pillTone?.[c]:null],children:/* @__PURE__ */l.jsx(Text,{tier:"badge",style:[i.pillText,c!==void 0?s?.pillToneText?.[c]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */l.jsx(Chevron,{options:t,color:n.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
294
- return l.jsx(r.Pressable,{onPress:()=>{Hf(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:a,children:f})}/* @__PURE__ */
295
- return l.jsx(r.View,{style:a,children:f})}function CardsAnswer({message:e,text:n,streaming:i,messages:o,options:s,sentiment:a,onSentiment:u,sender:c,footer:d,onOpenUrl:f}){let{styles:h}=iS(),p=t.useMemo(()=>({answer:e.text,question:xC(o,e.id),messageId:e.id}),[e.text,e.id,o]),g=!i&&e.pending!==true,m=g?wC(s?.cards,p):[],b=t.useMemo(()=>g?dC(e.citations):[],[g,e.citations]),y=s?.byline,v=s?.feedback!==void 0&&e.responseId!==void 0&&u!==void 0?s.feedback:null,x={bold:h.bold,italic:h.italic,code:h.code},w=Sp(),k=g?w:void 0;/* @__PURE__ */
294
+ return l.jsx(r.Pressable,{onPress:()=>{rh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:a,children:f})}/* @__PURE__ */
295
+ return l.jsx(r.View,{style:a,children:f})}function CardsAnswer({message:e,text:n,streaming:i,messages:o,options:s,sentiment:a,onSentiment:u,sender:c,footer:d,onOpenUrl:f}){let{styles:h}=vS(),p=t.useMemo(()=>({answer:e.text,question:MC(o,e.id),messageId:e.id}),[e.text,e.id,o]),g=!i&&e.pending!==true,m=g?FC(s?.cards,p):[],b=t.useMemo(()=>g?_C(e.citations):[],[g,e.citations]),y=s?.byline,v=s?.feedback!==void 0&&e.responseId!==void 0&&u!==void 0?s.feedback:null,x={bold:h.bold,italic:h.italic,code:h.code},w=Bp(),k=g?w:void 0;/* @__PURE__ */
296
296
  return l.jsxs(r.View,{style:h.answer,testID:"everfur-answer-cards",children:[y!==void 0?/* @__PURE__ */l.jsxs(r.View,{style:h.byline,children:[y.icon??null,
297
297
  /* @__PURE__ */l.jsx(Text,{tier:"compact",style:h.bylineText,children:y.label})]}):c,
298
- /* @__PURE__ */l.jsx(r.View,{style:h.body,children:mC(n).flatMap((e,t)=>vC(e).map((e,n)=>{let i=`${t}-${n}`;return e.kind==="text"?/* @__PURE__ */l.jsx(Text,{style:h.paragraph,children:MC(e.text,x,k)},i):/* @__PURE__ */l.jsx(r.View,{style:h.list,children:e.items.map((t,n)=>/* @__PURE__ */l.jsxs(r.View,{style:h.listItem,children:[
298
+ /* @__PURE__ */l.jsx(r.View,{style:h.body,children:zC(n).flatMap((e,t)=>AC(e).map((e,n)=>{let i=`${t}-${n}`;return e.kind==="text"?/* @__PURE__ */l.jsx(Text,{style:h.paragraph,children:QC(e.text,x,k)},i):/* @__PURE__ */l.jsx(r.View,{style:h.list,children:e.items.map((t,n)=>/* @__PURE__ */l.jsxs(r.View,{style:h.listItem,children:[
299
299
  /* @__PURE__ */l.jsx(Text,{style:h.paragraph,children:e.ordered?`${e.start+n}.`:"•"}),
300
- /* @__PURE__ */l.jsx(Text,{style:[h.paragraph,h.listText],children:MC(t,x,k)})]},n))},i)}))}),m.length>0?/* @__PURE__ */l.jsx(r.View,{style:h.cards,children:m.map(e=>/* @__PURE__ */l.jsx(AnswerCard,{card:e,options:s},e.key))}):null,b.length>0?/* @__PURE__ */l.jsxs(r.View,{style:h.cards,accessibilityLabel:hC(b.length),children:[
301
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:h.label,children:Yd.sourcesHeading}),b.map(e=>{let t=e.url;/* @__PURE__ */
300
+ /* @__PURE__ */l.jsx(Text,{style:[h.paragraph,h.listText],children:QC(t,x,k)})]},n))},i)}))}),m.length>0?/* @__PURE__ */l.jsx(r.View,{style:h.cards,children:m.map(e=>/* @__PURE__ */l.jsx(AnswerCard,{card:e,options:s},e.key))}):null,b.length>0?/* @__PURE__ */l.jsxs(r.View,{style:h.cards,accessibilityLabel:TC(b.length),children:[
301
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:h.label,children:df.sourcesHeading}),b.map(e=>{let t=e.url;/* @__PURE__ */
302
302
  return l.jsx(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */l.jsx(SourceTileGlyph,{})},...f!==void 0&&t!==null?{onPress:()=>f(t)}:{}},options:s},e.key)})]}):null,g&&v!==null&&u!==void 0?/* @__PURE__ */l.jsxs(r.View,{style:[h.feedback,s?.styles?.feedback],children:[
303
303
  /* @__PURE__ */l.jsx(FeedbackChip,{label:v.helpful,on:a==="up",onPress:()=>u("up"),styles:h,host:s?.styles}),
304
304
  /* @__PURE__ */l.jsx(FeedbackChip,{label:v.notHelpful,on:a==="down",onPress:()=>u("down"),styles:h,host:s?.styles})]}):null,g?d(v===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
305
- return l.jsx(BookGlyph,{size:XC,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:n,styles:i,host:o}){/* @__PURE__ */
306
- return l.jsx(r.Pressable,{onPress:n,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[i.chip,o?.feedbackChip,t?i.chipOn:null],hitSlop:(im-NC)/2,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[i.chipText,o?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:n,actions:i,options:o}){let{theme:s,styles:a}=iS();if(e.length===0&&i.length===0)return null;let u=o?.styles,c=n??Yd.followUpsHeadingNative;/* @__PURE__ */
305
+ return l.jsx(BookGlyph,{size:fS,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:n,styles:i,host:o}){/* @__PURE__ */
306
+ return l.jsx(r.Pressable,{onPress:n,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[i.chip,o?.feedbackChip,t?i.chipOn:null],hitSlop:(vm-iS)/2,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[i.chipText,o?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:n,actions:i,options:o}){let{theme:s,styles:a}=vS();if(e.length===0&&i.length===0)return null;let u=o?.styles,c=n??df.followUpsHeadingNative;/* @__PURE__ */
307
307
  return l.jsxs(r.View,{style:[a.followUps,u?.followUps],accessibilityLabel:c,testID:"everfur-cards-follow-ups",children:[
308
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.label,u?.followUpsLabel],accessibilityRole:"header",children:c}),i.map(e=>/* @__PURE__ */l.jsxs(r.Pressable,{onPress:()=>{Hf(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:JC,style:[a.row,a.rowAction,u?.followUp,u?.followUpAction],children:[e.icon??null,
308
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:[a.label,u?.followUpsLabel],accessibilityRole:"header",children:c}),i.map(e=>/* @__PURE__ */l.jsxs(r.Pressable,{onPress:()=>{rh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:pS,style:[a.row,a.rowAction,u?.followUp,u?.followUpAction],children:[e.icon??null,
309
309
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:[a.rowText,a.rowTextAction,u?.followUpText,u?.followUpActionText],children:e.label}),
310
- /* @__PURE__ */l.jsx(Chevron,{options:o,color:s.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */l.jsxs(r.Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:JC,style:[a.row,u?.followUp],children:[
310
+ /* @__PURE__ */l.jsx(Chevron,{options:o,color:s.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */l.jsxs(r.Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:pS,style:[a.row,u?.followUp],children:[
311
311
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:[a.rowText,u?.followUpText],children:e}),
312
- /* @__PURE__ */l.jsx(Chevron,{options:o,color:s.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=iS();/* @__PURE__ */
313
- return l.jsx(r.View,{style:t.byline,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:t.bylineText,children:e})})}function lS(e){let t=e.color,n=e.space,i={...face(e,"mono"),fontSize:FC,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},o={borderWidth:1,borderColor:El(t.text.primary,eS)??t.borderRingCream},s={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:tS,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=dg(e.slots.chip);return r.StyleSheet.create({answer:{gap:n.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...i,letterSpacing:FC*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:n.sm,paddingLeft:n.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:n.sm},card:{flexDirection:"row",alignItems:"center",gap:n.md,padding:LC,borderRadius:DC,backgroundColor:t.surface,...o,...s,minHeight:im,...ug(e.slots.card)},tile:{width:BC,height:BC,borderRadius:VC,backgroundColor:El(t.linkInk,rS)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:BC,height:BC},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:HC,lineHeight:Math.round(HC*1.25),color:t.text.primary,...dg(e.slots.card)},cardMeta:{...i,letterSpacing:FC*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:UC,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:FC+2,color:t.text.muted},pill:{minHeight:QC,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:nS},pillText:{...face(e,"bold"),fontSize:YC,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,alignItems:"center"},chip:{minHeight:NC,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...lw(e),fontSize:$C,color:t.text.primary,...chipInk},followUps:{gap:n.sm,alignSelf:"stretch",marginTop:n.xs},label:{...face(e,"bold"),fontSize:KC,lineHeight:Math.round(KC*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:ZC,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:WC,backgroundColor:t.surface,...o},rowAction:{},rowText:{...lw(e),flex:1,fontSize:qC,lineHeight:Math.round(qC*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var oS=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),sS=/* @__PURE__ */Object.freeze(ir.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:oS.answers[e]})));function aS(e,r){let[n,i]=t.useState(null),[l,o]=t.useState(null),[s,a]=t.useState(null),u=t.useCallback(t=>{r!==null&&(i(t),o(null),r(e.caseId,t).then(e=>{i(null),e.ok?a(t):o(e.error)}))},[r,e.caseId]),c=s??e.answer;return{answer:c,answerable:!isCheckinSettled(e),escalated:c==="worse",pending:n,error:l,choose:u}}var uS=44,cS=.6,dS=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:n,onAnswer:i,petRef:o,onFindVet:s,vet:a,onLayout:u,onOpen:c}){let d=useEverfurTheme(),f=t.useMemo(()=>fS(d),[d]),h=aS(n??dS,n===null?null:i),p=h.answer!==null||h.pending!==null,g=n!==null&&i!==null&&h.answerable,m=n===null?null:tC(n.openedAt,rC(e));/* @__PURE__ */
314
- return l.jsxs(r.View,{style:f.card,accessibilityLabel:oS.eyebrow,onLayout:u,children:[
312
+ /* @__PURE__ */l.jsx(Chevron,{options:o,color:s.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=vS();/* @__PURE__ */
313
+ return l.jsx(r.View,{style:t.byline,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:t.bylineText,children:e})})}function xS(e){let t=e.color,n=e.space,i={...face(e,"mono"),fontSize:XC,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},o={borderWidth:1,borderColor:Ml(t.text.primary,gS)??t.borderRingCream},s={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:mS,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=_g(e.slots.chip);return r.StyleSheet.create({answer:{gap:n.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...i,letterSpacing:XC*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:n.sm,paddingLeft:n.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:n.sm},card:{flexDirection:"row",alignItems:"center",gap:n.md,padding:JC,borderRadius:ZC,backgroundColor:t.surface,...o,...s,minHeight:vm,...Sg(e.slots.card)},tile:{width:eS,height:eS,borderRadius:tS,backgroundColor:Ml(t.linkInk,bS)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:eS,height:eS},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:rS,lineHeight:Math.round(rS*1.25),color:t.text.primary,..._g(e.slots.card)},cardMeta:{...i,letterSpacing:XC*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:nS,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:XC+2,color:t.text.muted},pill:{minHeight:dS,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:yS},pillText:{...face(e,"bold"),fontSize:cS,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,alignItems:"center"},chip:{minHeight:iS,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...xw(e),fontSize:lS,color:t.text.primary,...chipInk},followUps:{gap:n.sm,alignSelf:"stretch",marginTop:n.xs},label:{...face(e,"bold"),fontSize:uS,lineHeight:Math.round(uS*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:hS,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:oS,backgroundColor:t.surface,...o},rowAction:{},rowText:{...xw(e),flex:1,fontSize:sS,lineHeight:Math.round(sS*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var wS=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),kS=/* @__PURE__ */Object.freeze(lr.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:wS.answers[e]})));function CS(e,r){let[n,i]=t.useState(null),[l,o]=t.useState(null),[s,a]=t.useState(null),u=t.useCallback(t=>{r!==null&&(i(t),o(null),r(e.caseId,t).then(e=>{i(null),e.ok?a(t):o(e.error)}))},[r,e.caseId]),c=s??e.answer;return{answer:c,answerable:!isCheckinSettled(e),escalated:c==="worse",pending:n,error:l,choose:u}}var SS=44,jS=.6,_S=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:n,onAnswer:i,petRef:o,onFindVet:s,vet:a,onLayout:u,onOpen:c}){let d=useEverfurTheme(),f=t.useMemo(()=>RS(d),[d]),h=CS(n??_S,n===null?null:i),p=h.answer!==null||h.pending!==null,g=n!==null&&i!==null&&h.answerable,m=n===null?null:mC(n.openedAt,bC(e));/* @__PURE__ */
314
+ return l.jsxs(r.View,{style:f.card,accessibilityLabel:wS.eyebrow,onLayout:u,children:[
315
315
  /* @__PURE__ */l.jsxs(r.View,{style:f.head,children:[
316
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:f.eyebrow,children:oS.eyebrow}),m!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:f.headDay,children:Qd(oS.day,{day:m})}):null]}),c?/* @__PURE__ */l.jsx(r.Pressable,{onPress:c,accessibilityRole:"button",accessibilityLabel:e.text,style:f.open,children:/* @__PURE__ */l.jsx(Text,{style:[f.question,f.openText],children:e.text})}):/* @__PURE__ */l.jsx(Text,{style:f.question,accessibilityRole:"text",children:e.text}),g?/* @__PURE__ */l.jsx(r.View,{style:[f.row,h.pending?f.rowPending:null],children:sS.map(({answer:e,label:t})=>{let n=(h.pending??h.answer)===e;/* @__PURE__ */
317
- return l.jsx(r.Pressable,{onPress:()=>h.choose(e),disabled:p,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:n,disabled:p,busy:h.pending===e},style:[f.pill,n?f.pillSelected:null],children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[f.pillLabel,n?f.pillLabelSelected:null],children:t})},e)})}):null,h.answer!==null?/* @__PURE__ */l.jsx(Text,{style:f.logged,children:oS.logged}):null,h.escalated?/* @__PURE__ */l.jsx(CheckinFindVet,{petRef:o??null,onFindVet:s,vet:a,styles:f}):null,n?.resolutionText?/* @__PURE__ */l.jsx(Text,{style:f.resolution,children:n.resolutionText}):null,h.error?/* @__PURE__ */l.jsx(Text,{style:f.error,accessibilityRole:"alert",children:h.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:n,styles:i}){return useVetVisit(bk(e,n)).available&&e!==null?/* @__PURE__ */l.jsx(VetVisitButtonCore,{entry:"chat",petRef:e,label:oS.findVet,...n?.returnTo!==void 0?{returnTo:n.returnTo}:{},...n?.usState!==void 0?{usState:n.usState}:{},...n?.prefer!==void 0?{prefer:n.prefer}:{},style:i.findVet,labelStyle:i.findVetLabel}):t===void 0?null:/* @__PURE__ */l.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:oS.findVet,style:i.findVet,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.findVetLabel,children:oS.findVet})})}function fS(e){let t=e.color,n=e.space,i=e.radius,l=e.type,o=cg(e.slots.card),s=dg(o);return r.StyleSheet.create({card:{maxWidth:"92%",padding:n.md,gap:n.sm,borderRadius:i.lg,backgroundColor:t.brandSoft,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder,...ug(o,r.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...s},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...s},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...s},open:{minHeight:uS,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:n.sm,marginTop:n.xs},rowPending:{opacity:cS},pill:{flex:1,minHeight:uS,alignItems:"center",justifyContent:"center",paddingHorizontal:n.md,borderRadius:i.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,...s},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...s},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:uS,alignItems:"center",justifyContent:"center",borderRadius:i.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var hS=244,pS=8,gS=13,mS=14,bS=.3,yS=-.24,vS=22,xS=10,wS=15;function CitationCards({citations:e,onOpenUrl:n}){let i=useEverfurTheme(),o=t.useMemo(()=>kS(i),[i]),s=t.useMemo(()=>dC(e),[e]),[a,u]=t.useState(false);if(s.length===0)return null;let c=s.length;/* @__PURE__ */
316
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:f.eyebrow,children:wS.eyebrow}),m!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:f.headDay,children:ff(wS.day,{day:m})}):null]}),c?/* @__PURE__ */l.jsx(r.Pressable,{onPress:c,accessibilityRole:"button",accessibilityLabel:e.text,style:f.open,children:/* @__PURE__ */l.jsx(Text,{style:[f.question,f.openText],children:e.text})}):/* @__PURE__ */l.jsx(Text,{style:f.question,accessibilityRole:"text",children:e.text}),g?/* @__PURE__ */l.jsx(r.View,{style:[f.row,h.pending?f.rowPending:null],children:kS.map(({answer:e,label:t})=>{let n=(h.pending??h.answer)===e;/* @__PURE__ */
317
+ return l.jsx(r.Pressable,{onPress:()=>h.choose(e),disabled:p,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:n,disabled:p,busy:h.pending===e},style:[f.pill,n?f.pillSelected:null],children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:[f.pillLabel,n?f.pillLabelSelected:null],children:t})},e)})}):null,h.answer!==null?/* @__PURE__ */l.jsx(Text,{style:f.logged,children:wS.logged}):null,h.escalated?/* @__PURE__ */l.jsx(CheckinFindVet,{petRef:o??null,onFindVet:s,vet:a,styles:f}):null,n?.resolutionText?/* @__PURE__ */l.jsx(Text,{style:f.resolution,children:n.resolutionText}):null,h.error?/* @__PURE__ */l.jsx(Text,{style:f.error,accessibilityRole:"alert",children:h.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:n,styles:i}){return useVetVisit(Ek(e,n)).available&&e!==null?/* @__PURE__ */l.jsx(VetVisitButtonCore,{entry:"chat",petRef:e,label:wS.findVet,...n?.returnTo!==void 0?{returnTo:n.returnTo}:{},...n?.usState!==void 0?{usState:n.usState}:{},...n?.prefer!==void 0?{prefer:n.prefer}:{},style:i.findVet,labelStyle:i.findVetLabel}):t===void 0?null:/* @__PURE__ */l.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:wS.findVet,style:i.findVet,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.findVetLabel,children:wS.findVet})})}function RS(e){let t=e.color,n=e.space,i=e.radius,l=e.type,o=jg(e.slots.card),s=_g(o);return r.StyleSheet.create({card:{maxWidth:"92%",padding:n.md,gap:n.sm,borderRadius:i.lg,backgroundColor:t.brandSoft,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder,...Sg(o,r.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...s},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...s},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...s},open:{minHeight:SS,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:n.sm,marginTop:n.xs},rowPending:{opacity:jS},pill:{flex:1,minHeight:SS,alignItems:"center",justifyContent:"center",paddingHorizontal:n.md,borderRadius:i.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,...s},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...s},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:SS,alignItems:"center",justifyContent:"center",borderRadius:i.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var TS=244,IS=8,PS=13,zS=14,ES=.3,OS=-.24,AS=22,MS=10,FS=15;function CitationCards({citations:e,onOpenUrl:n}){let i=useEverfurTheme(),o=t.useMemo(()=>DS(i),[i]),s=t.useMemo(()=>_C(e),[e]),[a,u]=t.useState(false);if(s.length===0)return null;let c=s.length;/* @__PURE__ */
318
318
  return l.jsxs(r.View,{style:o.block,children:[
319
- /* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:pC(c,a),accessibilityState:{expanded:a},containerStyle:o.toggleSlot,style:o.togglePill,onPress:()=>u(e=>!e),children:[
320
- /* @__PURE__ */l.jsx(BookGlyph,{size:gS,color:i.color.brandInk,strokeWidth:1.5}),
321
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:o.toggleLabel,children:hC(c)}),
322
- /* @__PURE__ */l.jsx(ChevronGlyph,{size:gS,color:i.color.brandInk,strokeWidth:1.5,direction:a?"up":"down"})]}),a?/* @__PURE__ */l.jsx(Deck,{cards:s,styles:o,open:n}):null]})}function Deck({cards:e,styles:t,open:n}){let i=Mp(),o=$p(i.citationsInMs,{risePx:i.citationsRisePx});/* @__PURE__ */
323
- return l.jsx(r.Animated.View,{style:o,children:/* @__PURE__ */l.jsx(r.ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */l.jsx(Card,{card:e,styles:t,open:n},e.key))})})}function Card({card:e,styles:t,open:n}){let i=useEverfurTheme(),o=e.url!==null&&n!==void 0,s=gC(o?e:{...e,url:null}),a=/* @__PURE__ */l.jsxs(l.Fragment,{children:[
319
+ /* @__PURE__ */l.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:IC(c,a),accessibilityState:{expanded:a},containerStyle:o.toggleSlot,style:o.togglePill,onPress:()=>u(e=>!e),children:[
320
+ /* @__PURE__ */l.jsx(BookGlyph,{size:PS,color:i.color.brandInk,strokeWidth:1.5}),
321
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:o.toggleLabel,children:TC(c)}),
322
+ /* @__PURE__ */l.jsx(ChevronGlyph,{size:PS,color:i.color.brandInk,strokeWidth:1.5,direction:a?"up":"down"})]}),a?/* @__PURE__ */l.jsx(Deck,{cards:s,styles:o,open:n}):null]})}function Deck({cards:e,styles:t,open:n}){let i=Qp(),o=lg(i.citationsInMs,{risePx:i.citationsRisePx});/* @__PURE__ */
323
+ return l.jsx(r.Animated.View,{style:o,children:/* @__PURE__ */l.jsx(r.ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */l.jsx(Card,{card:e,styles:t,open:n},e.key))})})}function Card({card:e,styles:t,open:n}){let i=useEverfurTheme(),o=e.url!==null&&n!==void 0,s=PC(o?e:{...e,url:null}),a=/* @__PURE__ */l.jsxs(l.Fragment,{children:[
324
324
  /* @__PURE__ */l.jsxs(r.View,{style:t.cardHeader,children:[
325
325
  /* @__PURE__ */l.jsx(r.View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
326
- /* @__PURE__ */l.jsx(Text,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?/* @__PURE__ */l.jsx(ArrowUpRightGlyph,{size:mS,color:i.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */l.jsx(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&n!==void 0){let r=e.url;/* @__PURE__ */
326
+ /* @__PURE__ */l.jsx(Text,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?/* @__PURE__ */l.jsx(ArrowUpRightGlyph,{size:zS,color:i.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */l.jsx(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&n!==void 0){let r=e.url;/* @__PURE__ */
327
327
  return l.jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>n(r),children:a})}/* @__PURE__ */
328
- return l.jsx(r.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}function kS(e){let t=e.color,n=e.space,i=e.radius,l=e.type.size,o=dg(e.slots.card);return r.StyleSheet.create({block:{gap:n.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:i.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:n.xs+2,paddingHorizontal:n.md,paddingVertical:n.xs+2,borderRadius:i.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:bS,color:t.brandInk,textTransform:"uppercase"},row:{gap:n.sm,paddingRight:n.xl,paddingTop:n.xs},card:{width:hS,borderRadius:i.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:n.md,gap:n.xs+2,...ug(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:n.sm},tierDot:{width:pS,height:pS,borderRadius:i.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:vS,color:t.text.primary,letterSpacing:yS,...o},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:xS,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...o},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:wS,color:t.text.muted,...o}})}var CS=15,SS=44,jS=16,_S=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:n,sentiment:i=null,onSentiment:o,note:s=null}){let a=useEverfurTheme(),u=t.useMemo(()=>RS(a),[a]),c=Mp(),d=e.role==="user",f=t.useMemo(()=>nC(e.createdAt),[e.createdAt]),h=n!==void 0&&e.role!=="vet"&&e.text.length>0,p=e.role==="assistant"&&o!==void 0&&e.responseId!==void 0,[g,m]=t.useState(false),b=t.useRef(null);t.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);let y=()=>{n!==void 0&&($f(n,e.text),m(true),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{m(false),b.current=null},c.copiedMs))};return f===null&&!h&&!p?null:/* @__PURE__ */l.jsxs(r.View,{style:u.wrap,children:[
329
- /* @__PURE__ */l.jsxs(r.View,{style:[u.row,d?u.rowUser:u.rowAssistant],children:[f!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:u.timestamp,children:f}):null,h?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:g?Yd.copied:d?Yd.copyUserMessage:Yd.copyAssistantMessage,onPress:y,style:u.iconHit,children:g?/* @__PURE__ */l.jsx(CheckGlyph,{size:CS,color:a.color.success,strokeWidth:2}):/* @__PURE__ */l.jsx(CopyGlyph,{size:CS,color:a.color.text.timestamp,strokeWidth:1.5})}):null,p?Nv.map(({sentiment:e,label:t})=>/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:i===e},onPress:()=>o?.(e),style:u.iconHit,children:/* @__PURE__ */l.jsx(ThumbGlyph,{size:CS,color:i===e?a.color.sentiment[e]:a.color.text.timestamp,active:i===e,rotate:_S[e],strokeWidth:1.5})},e)):null]}),s==="thanks"?/* @__PURE__ */l.jsx(Text,{style:u.thanks,accessibilityLiveRegion:"polite",children:Yd.feedbackThanks}):null,s==="failed"?/* @__PURE__ */l.jsxs(l.Fragment,{children:[
330
- /* @__PURE__ */l.jsx(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Yd.feedbackFailed}),
331
- /* @__PURE__ */l.jsx(AnnounceLine,{line:Yd.feedbackFailed})]}):null]})}function RS(e){let t=e.type;return r.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:jS,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:SS,height:SS,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var TS=16,IS=10,PS=12,zS=10,ES=2,OS=.06,AS=34,MS=9,FS=10.5,DS=.06,LS=15,BS=19.5,VS=14,HS=19.6;function OpeningCard({card:e,onLayout:n}){let i=useEverfurTheme(),o=t.useMemo(()=>US(i),[i]),s=e.styles;/* @__PURE__ */
328
+ return l.jsx(r.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}function DS(e){let t=e.color,n=e.space,i=e.radius,l=e.type.size,o=_g(e.slots.card);return r.StyleSheet.create({block:{gap:n.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:i.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:n.xs+2,paddingHorizontal:n.md,paddingVertical:n.xs+2,borderRadius:i.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:ES,color:t.brandInk,textTransform:"uppercase"},row:{gap:n.sm,paddingRight:n.xl,paddingTop:n.xs},card:{width:TS,borderRadius:i.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:n.md,gap:n.xs+2,...Sg(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:n.sm},tierDot:{width:IS,height:IS,borderRadius:i.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:AS,color:t.text.primary,letterSpacing:OS,...o},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:MS,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...o},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:FS,color:t.text.muted,...o}})}var LS=15,BS=44,VS=16,HS=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:n,sentiment:i=null,onSentiment:o,note:s=null}){let a=useEverfurTheme(),u=t.useMemo(()=>US(a),[a]),c=Qp(),d=e.role==="user",f=t.useMemo(()=>yC(e.createdAt),[e.createdAt]),h=n!==void 0&&e.role!=="vet"&&e.text.length>0,p=e.role==="assistant"&&o!==void 0&&e.responseId!==void 0,[g,m]=t.useState(false),b=t.useRef(null);t.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);let y=()=>{n!==void 0&&(lh(n,e.text),m(true),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{m(false),b.current=null},c.copiedMs))};return f===null&&!h&&!p?null:/* @__PURE__ */l.jsxs(r.View,{style:u.wrap,children:[
329
+ /* @__PURE__ */l.jsxs(r.View,{style:[u.row,d?u.rowUser:u.rowAssistant],children:[f!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:u.timestamp,children:f}):null,h?/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:g?df.copied:d?df.copyUserMessage:df.copyAssistantMessage,onPress:y,style:u.iconHit,children:g?/* @__PURE__ */l.jsx(CheckGlyph,{size:LS,color:a.color.success,strokeWidth:2}):/* @__PURE__ */l.jsx(CopyGlyph,{size:LS,color:a.color.text.timestamp,strokeWidth:1.5})}):null,p?ix.map(({sentiment:e,label:t})=>/* @__PURE__ */l.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:i===e},onPress:()=>o?.(e),style:u.iconHit,children:/* @__PURE__ */l.jsx(ThumbGlyph,{size:LS,color:i===e?a.color.sentiment[e]:a.color.text.timestamp,active:i===e,rotate:HS[e],strokeWidth:1.5})},e)):null]}),s==="thanks"?/* @__PURE__ */l.jsx(Text,{style:u.thanks,accessibilityLiveRegion:"polite",children:df.feedbackThanks}):null,s==="failed"?/* @__PURE__ */l.jsxs(l.Fragment,{children:[
330
+ /* @__PURE__ */l.jsx(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:df.feedbackFailed}),
331
+ /* @__PURE__ */l.jsx(AnnounceLine,{line:df.feedbackFailed})]}):null]})}function US(e){let t=e.type;return r.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:VS,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:BS,height:BS,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var NS=16,$S=10,WS=12,qS=10,GS=2,KS=.06,YS=34,QS=9,XS=10.5,ZS=.06,JS=15,ej=19.5,tj=14,rj=19.6;function OpeningCard({card:e,onLayout:n}){let i=useEverfurTheme(),o=t.useMemo(()=>nj(i),[i]),s=e.styles;/* @__PURE__ */
332
332
  return l.jsxs(r.View,{testID:"everfur-opening-card",onLayout:n,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[o.card,s?.card],children:[e.icon!==void 0?/* @__PURE__ */l.jsx(r.View,{style:[o.icon,s?.icon],children:e.icon}):null,
333
333
  /* @__PURE__ */l.jsxs(r.View,{style:o.words,children:[
334
334
  /* @__PURE__ */l.jsx(Text,{tier:"compact",style:[o.kicker,s?.kicker],children:e.kicker}),
335
- /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.title,s?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */l.jsx(Text,{style:[o.body,s?.body],children:e.body}):null]})]})}function US(e){let t=e.color;return r.StyleSheet.create({card:{flexDirection:"row",alignItems:"flex-start",gap:zS,paddingVertical:IS,paddingHorizontal:PS,alignSelf:"stretch",borderRadius:TS,backgroundColor:t.surface,borderWidth:1,borderColor:El(t.text.primary,OS)??t.borderRingCream},icon:{flexShrink:0,width:AS,height:AS,borderRadius:MS,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:ES},kicker:{...face(e,"mono"),fontSize:FS,letterSpacing:FS*DS,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:LS,lineHeight:BS,color:t.text.primary},body:{...face(e,"regular"),fontSize:VS,lineHeight:HS,color:t.text.secondary}})}var NS="#10462E",$S="Book a video visit",WS="#000000",qS="#83E0B4",GS=/* @__PURE__ */Object.freeze([
335
+ /* @__PURE__ */l.jsx(Text,{tier:"control",style:[o.title,s?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */l.jsx(Text,{style:[o.body,s?.body],children:e.body}):null]})]})}function nj(e){let t=e.color;return r.StyleSheet.create({card:{flexDirection:"row",alignItems:"flex-start",gap:qS,paddingVertical:$S,paddingHorizontal:WS,alignSelf:"stretch",borderRadius:NS,backgroundColor:t.surface,borderWidth:1,borderColor:Ml(t.text.primary,KS)??t.borderRingCream},icon:{flexShrink:0,width:YS,height:YS,borderRadius:QS,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:GS},kicker:{...face(e,"mono"),fontSize:XS,letterSpacing:XS*ZS,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:JS,lineHeight:ej,color:t.text.primary},body:{...face(e,"regular"),fontSize:tj,lineHeight:rj,color:t.text.secondary}})}var ij="#10462E",lj="Book a video visit",oj="#000000",sj="#83E0B4",aj=/* @__PURE__ */Object.freeze([
336
336
  /* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
337
- /* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:qS,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
338
- /* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:NS,brandEdge:true,borderWidth:1}),
339
- /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function KS(e,t){return e?null:{fill:t.fill,ink:t.ink}}var YS=8;function QS(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function XS(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=YS)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,i=QS(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:i,ink:i===null?null:QS(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var ZS=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function JS(e){return e==null?e:e.replace(ZS,"").trim()}var ej=/* @__PURE__ */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 tj(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return ej.has(t)}function rj(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function nj(e,t){let r=e?.trim();if(r===void 0||r==="")return ij(t);let n=t?.name?.trim()||Yd.emptyTitlePetFallback,i=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?i:n)}function ij(e){let t=e?.name?.trim()||Yd.emptyTitlePetFallback;return Qd(Yd.emptyTitle,{petName:t})}function lj(e){let t=e.toLowerCase();return t===rj("dog").toLowerCase()||t===rj("cat").toLowerCase()}function oj(e){let t=JS(e);if(tj(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return lj(r)?null:r}function sj(e,t=NS,r){let n=canonicalPetSpecies(e?.species),i=e?.name?.trim()||null,l=oj(e?.breed),o=tv(e?.ageYears),s=o===null?null:String(o),a=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
340
- return Object.freeze(GS.flatMap(e=>{let r=e.intent==="vet_report"&&a!==null?a:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!l||u&&!s)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&l===null||c.includes("{ageYears}")&&s===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&i===null))return[];let d=Qd(c,{petName:i??(n==="cat"?"my cat":"my dog"),breed:l??"",species:n??"",ageYears:s??""}),f=!i&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var aj=44,uj=0,cj={top:3,bottom:3},dj=1,fj=.28,hj=2,pj=2,gj=1.3,mj=-.015,bj=/* @__PURE__ */Object.freeze([
337
+ /* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:sj,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
338
+ /* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:ij,brandEdge:true,borderWidth:1}),
339
+ /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function uj(e,t){return e?null:{fill:t.fill,ink:t.ink}}var cj=8;function dj(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function fj(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=cj)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,i=dj(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:i,ink:i===null?null:dj(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var hj=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function pj(e){return e==null?e:e.replace(hj,"").trim()}var gj=/* @__PURE__ */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 mj(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return gj.has(t)}function bj(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function yj(e,t){let r=e?.trim();if(r===void 0||r==="")return vj(t);let n=t?.name?.trim()||df.emptyTitlePetFallback,i=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?i:n)}function vj(e){let t=e?.name?.trim()||df.emptyTitlePetFallback;return ff(df.emptyTitle,{petName:t})}function xj(e){let t=e.toLowerCase();return t===bj("dog").toLowerCase()||t===bj("cat").toLowerCase()}function wj(e){let t=pj(e);if(mj(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return xj(r)?null:r}function kj(e,t=ij,r){let n=canonicalPetSpecies(e?.species),i=e?.name?.trim()||null,l=wj(e?.breed),o=mv(e?.ageYears),s=o===null?null:String(o),a=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
340
+ return Object.freeze(aj.flatMap(e=>{let r=e.intent==="vet_report"&&a!==null?a:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!l||u&&!s)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&l===null||c.includes("{ageYears}")&&s===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&i===null))return[];let d=ff(c,{petName:i??(n==="cat"?"my cat":"my dog"),breed:l??"",species:n??"",ageYears:s??""}),f=!i&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var Cj=44,Sj=0,jj={top:3,bottom:3},_j=1,Rj=.28,Tj=2,Ij=2,Pj=1.3,zj=-.015,Ej=/* @__PURE__ */Object.freeze([
341
341
  /* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
342
342
  /* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
343
343
  /* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
344
- /* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:n,onSend:i,onVetPrep:o,vet:s,starterPrompts:a,emptyState:u,centered:c=false}){let d=useEverfurTheme(),f=t.useMemo(()=>yj(d),[d]),h=t.useMemo(()=>XS(a),[a]),p=t.useMemo(()=>h!==null?h.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??d.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??d.color.text.primary}})):sj(e,d.color.brandInk,{vetPrepLabel:$S}).map(e=>({prompt:e,send:e.label,paint:null})),[h,e,d.color.brandInk,d.color.highlight,d.color.text.primary]),g=u?.chipTints!==void 0,m=t.useMemo(()=>(u?.chipTints??(d.brightness==="light"?bj:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[u?.chipTints,d.brightness]),b=t.useMemo(()=>m.length===0?p:p.map((e,t)=>{if(e.paint!==null)return e;let r=m[t%m.length];return{...e,paint:{fill:r.tint,ink:r.ink??d.color.text.primary},...g?{}:{cycleDefault:true}}}),[p,m,g,d.color.text.primary]),y=t.useMemo(()=>KS(Zy(d),{fill:d.color.highlight,ink:d.color.onHighlight}),[d]),v=t.useMemo(()=>({fill:d.color.highlight,ink:d.color.onHighlight}),[d.color.highlight,d.color.onHighlight]),x=nj(u?.title,e),w=sx(),k=ax(),C=w!==null&&k!==null?/* @__PURE__ */l.jsx(k.Title,{text:x,style:[f.title,w.text(".serif",".ask-empty h2"),f.centerText],measureCh:k.titleCh}):/* @__PURE__ */l.jsx(Text,{tier:"heading",style:c?[f.title,f.centerText]:f.title,accessibilityRole:"header",children:x});/* @__PURE__ */
344
+ /* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:n,onSend:i,onVetPrep:o,vet:s,starterPrompts:a,emptyState:u,centered:c=false}){let d=useEverfurTheme(),f=t.useMemo(()=>Oj(d),[d]),h=t.useMemo(()=>fj(a),[a]),p=t.useMemo(()=>h!==null?h.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??d.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??d.color.text.primary}})):kj(e,d.color.brandInk,{vetPrepLabel:lj}).map(e=>({prompt:e,send:e.label,paint:null})),[h,e,d.color.brandInk,d.color.highlight,d.color.text.primary]),g=u?.chipTints!==void 0,m=t.useMemo(()=>(u?.chipTints??(d.brightness==="light"?Ej:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[u?.chipTints,d.brightness]),b=t.useMemo(()=>m.length===0?p:p.map((e,t)=>{if(e.paint!==null)return e;let r=m[t%m.length];return{...e,paint:{fill:r.tint,ink:r.ink??d.color.text.primary},...g?{}:{cycleDefault:true}}}),[p,m,g,d.color.text.primary]),y=t.useMemo(()=>uj(hv(d),{fill:d.color.highlight,ink:d.color.onHighlight}),[d]),v=t.useMemo(()=>({fill:d.color.highlight,ink:d.color.onHighlight}),[d.color.highlight,d.color.onHighlight]),x=yj(u?.title,e),w=kx(),k=Cx(),C=w!==null&&k!==null?/* @__PURE__ */l.jsx(k.Title,{text:x,style:[f.title,w.text(".serif",".ask-empty h2"),f.centerText],measureCh:k.titleCh}):/* @__PURE__ */l.jsx(Text,{tier:"heading",style:c?[f.title,f.centerText]:f.title,accessibilityRole:"header",children:x});/* @__PURE__ */
345
345
  return l.jsxs(r.View,{style:w!==null?f.homeBlock:f.block,children:[C,
346
- /* @__PURE__ */l.jsx(r.View,{style:w!==null?[f.list,f.listCentered,w.view(".ask-chips",".ask-empty .ask-chips")]:c?[f.list,f.listCentered]:f.list,accessibilityLabel:Yd.suggestions,children:b.map(({prompt:t,send:r,paint:a,cycleDefault:u},d)=>/* @__PURE__ */l.jsx(Chip,{prompt:t,send:r,themed:a??(h!==null?v:y),index:d,petRef:n,onSend:i,onVetPrep:o,vet:s,pet:e,styles:f,tinted:a!==null&&u!==true,soft:a!==null,centered:c},t.id))})]})}function Chip({prompt:e,send:t,themed:n,index:i,pet:o,petRef:s,onSend:a,onVetPrep:u,vet:c,styles:d,tinted:f,soft:h,centered:p}){let g=Mp(),m=$p(g.followUpInMs,{delayMs:Op(g,i),risePx:g.promptRisePx}),b=sx(),y=b!==null?[d.chipHome,b.view(".chip")]:p&&h?d.chipNoEdge:d.chipEdge,v={backgroundColor:n?.fill??e.background},x=d.chipSlot===null?v:f?{...d.chipSlot,...v}:{...v,...d.chipSlot},w=b!==null?[d.chipLabel,b.text(".chip")]:p?[d.chipLabel,d.centerText]:[d.chipLabel],k=b!==null?cj:uj,C=n===null?d.chipSlotLabel===null?w:[...w,d.chipSlotLabel]:f?[...w,...d.chipSlotLabel===null?[]:[d.chipSlotLabel],{color:n.ink}]:[...w,{color:n.ink},...d.chipSlotLabel===null?[]:[d.chipSlotLabel]];return e.intent==="vet_report"?u!==void 0?/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[d.chip,y,x],onPress:()=>{Hf(u,o)},children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:C,children:e.label})})}):s===null?null:/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(VetVisitButtonCore,{entry:"chat",petRef:s,label:e.label,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:[d.chip,y,x],labelStyle:C})}):/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[d.chip,y,x],onPress:()=>a(t),children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:C,children:e.label})})})}function yj(e){let t=cg(e.slots.chip),r=dg(t);return{chipSlot:t===void 0?null:ug(t,dj),chipSlotLabel:r.color===void 0?null:r,...vj(e)}}function vj(e){let t=e.color,n=e.space,i=e.type;return r.StyleSheet.create({block:{gap:n.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:i.size.heading,lineHeight:Math.round(i.size.heading*i.lineHeight.snug),color:t.brandInk,letterSpacing:i.size.heading*mj,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:n.sm+hj},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:dj,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:n.lg+pj,paddingVertical:n.sm,minHeight:aj,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:dj,borderColor:El(t.brandInk,fj)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:i.size.bodyTight,lineHeight:Math.round(i.size.bodyTight*gj),color:WS,textAlign:"left"}})}var xj=1e3,wj=150,kj=.25,Cj=.5,Sj=3;function TypingIndicator({petName:e=null,inline:n=false}){let{theme:i,styles:o}=Ym(),s=i.motion.reducedMotion,a=Zd(Yd.reading,e),u=t.useRef(Array.from({length:Sj},()=>new r.Animated.Value(0))).current;return t.useEffect(()=>{if(s)return;let e=u.map((e,t)=>r.Animated.loop(r.Animated.sequence([r.Animated.delay(t*wj),r.Animated.timing(e,{toValue:1,duration:xj*.4,useNativeDriver:true}),r.Animated.timing(e,{toValue:0,duration:xj*.6,useNativeDriver:true}),r.Animated.delay((Sj-t-1)*wj)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[s,u]),/* @__PURE__ */l.jsx(r.View,{style:n?o.readingInline:o.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:a,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:u.map((e,t)=>/* @__PURE__ */l.jsx(r.Animated.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[n?o.readingDotInline:o.readingDot,s?{opacity:Cj}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[kj,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},t))})}function jj(e,t,r){let n=e-r,i=t!=null?Math.min(n,t):n;return Math.max(0,i)}function _j(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function Rj(e,t,r){let n=Math.max(0,r),i=e===null?n:Math.min(Math.max(0,e),n);return i>t+1?i:null}var Tj=16;function Ij(e,r,n=null){let i=t.useRef(null),l=t.useRef(true),o=t.useRef(r),s=t.useRef(0),a=t.useRef(0),u=t.useRef(0),c=t.useRef(/* @__PURE__ */new Map),d=t.useRef(null),f=t.useRef(false),h=e[0]?.id??null,p=t.useRef(h),g=t.useRef(null);t.useEffect(()=>{let t=p.current;if(p.current=h,t===null||t===h||(g.current=null,l.current||!e.some(e=>e.id===t)))return;let r=c.current.get(t);r!==void 0&&(g.current={id:t,top:r,offset:s.current})},[h,e]);let m=_j(e),b=m===null?null:e[m.assistantIndex]?.id??null,y=m===null||m.userIndex===null?null:e[m.userIndex]?.id??null,v=t.useCallback(()=>{let e=i.current;if(e===null||!l.current||a.current===0)return;let t=null;if(b!==null){let e=c.current.get(b);if(e===void 0)return;let r=y===null?null:c.current.get(y)??null;t=jj(e,r,96)}let r=Rj(t,s.current,u.current-a.current);if(r!==null&&(s.current=r,e.scrollTo({y:r,animated:false})),!f.current||d.current===null)return;let n=Rj(d.current+Tj-a.current,s.current,u.current-a.current);n!==null&&(s.current=n,e.scrollTo({y:n,animated:false}))},[b,y]);t.useEffect(()=>{f.current=n!==null,n===null&&(d.current=null),v()},[n,v]),t.useEffect(()=>{r&&!o.current&&(l.current=true,f.current=false),o.current=r,v()},[e,r,v]);let x=t.useCallback(e=>{a.current=e.nativeEvent.layout.height,v()},[v]),w=t.useCallback((e,t)=>{u.current=t,a.current>0&&(s.current=Math.min(s.current,Math.max(0,t-a.current))),v()},[v]),k=t.useCallback(e=>{s.current=e.nativeEvent.contentOffset.y},[]),C=t.useCallback(()=>{l.current=false,f.current=false},[]),S=t.useCallback(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;s.current=t.y,l.current=r.height-t.y-n.height<=24},[]),j=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.y;c.current.set(e,r);let n=g.current;if(n!==null&&n.id===e&&r!==n.top){g.current=null;let e=Math.max(0,n.offset+r-n.top);s.current=e,i.current?.scrollTo({y:e,animated:false})}(e===b||e===y)&&v()},[b,y,v]),_=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current=t+r,v()},[v]);return{ref:i,onLayout:x,onContentSizeChange:w,onScroll:k,onScrollBeginDrag:C,onScrollEnd:S,rowLayout:j,asideLayout:_}}function Pj(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */l.jsx(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */l.jsx(LoadingState,{})}):/* @__PURE__ */l.jsx(LoadingState,{});case"empty":/* @__PURE__ */
346
+ /* @__PURE__ */l.jsx(r.View,{style:w!==null?[f.list,f.listCentered,w.view(".ask-chips",".ask-empty .ask-chips")]:c?[f.list,f.listCentered]:f.list,accessibilityLabel:df.suggestions,children:b.map(({prompt:t,send:r,paint:a,cycleDefault:u},d)=>/* @__PURE__ */l.jsx(Chip,{prompt:t,send:r,themed:a??(h!==null?v:y),index:d,petRef:n,onSend:i,onVetPrep:o,vet:s,pet:e,styles:f,tinted:a!==null&&u!==true,soft:a!==null,centered:c},t.id))})]})}function Chip({prompt:e,send:t,themed:n,index:i,pet:o,petRef:s,onSend:a,onVetPrep:u,vet:c,styles:d,tinted:f,soft:h,centered:p}){let g=Qp(),m=lg(g.followUpInMs,{delayMs:Kp(g,i),risePx:g.promptRisePx}),b=kx(),y=b!==null?[d.chipHome,b.view(".chip")]:p&&h?d.chipNoEdge:d.chipEdge,v={backgroundColor:n?.fill??e.background},x=d.chipSlot===null?v:f?{...d.chipSlot,...v}:{...v,...d.chipSlot},w=b!==null?[d.chipLabel,b.text(".chip")]:p?[d.chipLabel,d.centerText]:[d.chipLabel],k=b!==null?jj:Sj,C=n===null?d.chipSlotLabel===null?w:[...w,d.chipSlotLabel]:f?[...w,...d.chipSlotLabel===null?[]:[d.chipSlotLabel],{color:n.ink}]:[...w,{color:n.ink},...d.chipSlotLabel===null?[]:[d.chipSlotLabel]];return e.intent==="vet_report"?u!==void 0?/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[d.chip,y,x],onPress:()=>{rh(u,o)},children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:C,children:e.label})})}):s===null?null:/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(VetVisitButtonCore,{entry:"chat",petRef:s,label:e.label,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:[d.chip,y,x],labelStyle:C})}):/* @__PURE__ */l.jsx(r.Animated.View,{style:m,children:/* @__PURE__ */l.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[d.chip,y,x],onPress:()=>a(t),children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:C,children:e.label})})})}function Oj(e){let t=jg(e.slots.chip),r=_g(t);return{chipSlot:t===void 0?null:Sg(t,_j),chipSlotLabel:r.color===void 0?null:r,...Aj(e)}}function Aj(e){let t=e.color,n=e.space,i=e.type;return r.StyleSheet.create({block:{gap:n.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:i.size.heading,lineHeight:Math.round(i.size.heading*i.lineHeight.snug),color:t.brandInk,letterSpacing:i.size.heading*zj,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:n.sm+Tj},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:_j,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:n.lg+Ij,paddingVertical:n.sm,minHeight:Cj,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:_j,borderColor:Ml(t.brandInk,Rj)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:i.size.bodyTight,lineHeight:Math.round(i.size.bodyTight*Pj),color:oj,textAlign:"left"}})}var Mj=1e3,Fj=150,Dj=.25,Lj=.5,Bj=3;function TypingIndicator({petName:e=null,inline:n=false}){let{theme:i,styles:o}=cb(),s=i.motion.reducedMotion,a=pf(df.reading,e),u=t.useRef(Array.from({length:Bj},()=>new r.Animated.Value(0))).current;return t.useEffect(()=>{if(s)return;let e=u.map((e,t)=>r.Animated.loop(r.Animated.sequence([r.Animated.delay(t*Fj),r.Animated.timing(e,{toValue:1,duration:Mj*.4,useNativeDriver:true}),r.Animated.timing(e,{toValue:0,duration:Mj*.6,useNativeDriver:true}),r.Animated.delay((Bj-t-1)*Fj)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[s,u]),/* @__PURE__ */l.jsx(r.View,{style:n?o.readingInline:o.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:a,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:u.map((e,t)=>/* @__PURE__ */l.jsx(r.Animated.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[n?o.readingDotInline:o.readingDot,s?{opacity:Lj}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[Dj,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},t))})}function Vj(e,t,r){let n=e-r,i=t!=null?Math.min(n,t):n;return Math.max(0,i)}function Hj(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function Uj(e,t,r){let n=Math.max(0,r),i=e===null?n:Math.min(Math.max(0,e),n);return i>t+1?i:null}var Nj=16;function $j(e,r,n=null){let i=t.useRef(null),l=t.useRef(true),o=t.useRef(r),s=t.useRef(0),a=t.useRef(0),u=t.useRef(0),c=t.useRef(/* @__PURE__ */new Map),d=t.useRef(null),f=t.useRef(false),h=e[0]?.id??null,p=t.useRef(h),g=t.useRef(null);t.useEffect(()=>{let t=p.current;if(p.current=h,t===null||t===h||(g.current=null,l.current||!e.some(e=>e.id===t)))return;let r=c.current.get(t);r!==void 0&&(g.current={id:t,top:r,offset:s.current})},[h,e]);let m=Hj(e),b=m===null?null:e[m.assistantIndex]?.id??null,y=m===null||m.userIndex===null?null:e[m.userIndex]?.id??null,v=t.useCallback(()=>{let e=i.current;if(e===null||!l.current||a.current===0)return;let t=null;if(b!==null){let e=c.current.get(b);if(e===void 0)return;let r=y===null?null:c.current.get(y)??null;t=Vj(e,r,96)}let r=Uj(t,s.current,u.current-a.current);if(r!==null&&(s.current=r,e.scrollTo({y:r,animated:false})),!f.current||d.current===null)return;let n=Uj(d.current+Nj-a.current,s.current,u.current-a.current);n!==null&&(s.current=n,e.scrollTo({y:n,animated:false}))},[b,y]);t.useEffect(()=>{f.current=n!==null,n===null&&(d.current=null),v()},[n,v]),t.useEffect(()=>{r&&!o.current&&(l.current=true,f.current=false),o.current=r,v()},[e,r,v]);let x=t.useCallback(e=>{a.current=e.nativeEvent.layout.height,v()},[v]),w=t.useCallback((e,t)=>{u.current=t,a.current>0&&(s.current=Math.min(s.current,Math.max(0,t-a.current))),v()},[v]),k=t.useCallback(e=>{s.current=e.nativeEvent.contentOffset.y},[]),C=t.useCallback(()=>{l.current=false,f.current=false},[]),S=t.useCallback(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;s.current=t.y,l.current=r.height-t.y-n.height<=24},[]),j=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.y;c.current.set(e,r);let n=g.current;if(n!==null&&n.id===e&&r!==n.top){g.current=null;let e=Math.max(0,n.offset+r-n.top);s.current=e,i.current?.scrollTo({y:e,animated:false})}(e===b||e===y)&&v()},[b,y,v]),_=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current=t+r,v()},[v]);return{ref:i,onLayout:x,onContentSizeChange:w,onScroll:k,onScrollBeginDrag:C,onScrollEnd:S,rowLayout:j,asideLayout:_}}function Wj(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */l.jsx(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */l.jsx(LoadingState,{})}):/* @__PURE__ */l.jsx(LoadingState,{});case"empty":/* @__PURE__ */
347
347
  return l.jsx(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
348
348
  return l.jsx(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
349
- return l.jsx(PopulatedState,{messages:t.messages,prompts:fh(t,r.followUpPolicy),actions:r.answerCards?CC(t,r.answerCards):Ej,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,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,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:n}=Ym(),[i,o]=t.useState(false);return t.useEffect(()=>{let e=setTimeout(()=>o(true),tm);return()=>clearTimeout(e)},[]),/* @__PURE__ */l.jsx(r.View,{style:n.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:Yd.loading,children:i?/* @__PURE__ */l.jsx(r.ActivityIndicator,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:n,onVetPrep:i,vet:o,top:s,topCard:a,pendingCheckin:u,starterPrompts:c,emptyState:d,centered:f,renderEmptyHeader:h}){let{styles:p}=Ym(),g=sx(),m=h===void 0?null:/* @__PURE__ */l.jsx(r.View,{testID:"everfur-empty-header",children:/* @__PURE__ */l.jsx(HostRender,{render:()=>h({ask:n}),fallback:null})});if(g!==null){let{minHeight:f,...h}=g.view(".ask-empty");/* @__PURE__ */
350
- return l.jsxs(r.ScrollView,{contentContainerStyle:[h,p.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:Aj,nestedScrollEnabled:true,accessibilityLabel:Yd.empty,children:[s!=null?/* @__PURE__ */l.jsx(r.View,{style:g.view(".ask-top"),children:s}):null,u,a??null,m,
349
+ return l.jsx(PopulatedState,{messages:t.messages,prompts:Rh(t,r.followUpPolicy),actions:r.answerCards?LC(t,r.answerCards):Gj,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,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,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:n}=cb(),[i,o]=t.useState(false);return t.useEffect(()=>{let e=setTimeout(()=>o(true),mm);return()=>clearTimeout(e)},[]),/* @__PURE__ */l.jsx(r.View,{style:n.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:df.loading,children:i?/* @__PURE__ */l.jsx(r.ActivityIndicator,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:n,onVetPrep:i,vet:o,top:s,topCard:a,pendingCheckin:u,starterPrompts:c,emptyState:d,centered:f,renderEmptyHeader:h}){let{styles:p}=cb(),g=kx(),m=h===void 0?null:/* @__PURE__ */l.jsx(r.View,{testID:"everfur-empty-header",children:/* @__PURE__ */l.jsx(HostRender,{render:()=>h({ask:n}),fallback:null})});if(g!==null){let{minHeight:f,...h}=g.view(".ask-empty");/* @__PURE__ */
350
+ return l.jsxs(r.ScrollView,{contentContainerStyle:[h,p.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:Yj,nestedScrollEnabled:true,accessibilityLabel:df.empty,children:[s!=null?/* @__PURE__ */l.jsx(r.View,{style:g.view(".ask-top"),children:s}):null,u,a??null,m,
351
351
  /* @__PURE__ */l.jsx(r.View,{style:g.view(".ask-start"),children:/* @__PURE__ */l.jsx(QuickPrompts,{pet:e,petRef:t,onSend:n,onVetPrep:i,vet:o,starterPrompts:c,emptyState:d,centered:true})})]})}
352
352
  /* @__PURE__ */
353
- return l.jsxs(r.ScrollView,{contentContainerStyle:p.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:Aj,nestedScrollEnabled:true,accessibilityLabel:Yd.empty,children:[s??null,u,a??null,m,
354
- /* @__PURE__ */l.jsx(QuickPrompts,{pet:e,petRef:t,onSend:n,onVetPrep:i,vet:o,starterPrompts:c,emptyState:d,centered:f})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:n}){let{styles:i}=Ym();return e.length===0?null:/* @__PURE__ */l.jsxs(r.View,{style:i.followUps,children:[
355
- /* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.followUpsHeading,accessibilityRole:"header",children:n??Yd.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */l.jsx(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:n}){let{theme:i,styles:o}=Ym(),s=Mp(),a=$p(s.followUpInMs,{delayMs:Op(s,t)});/* @__PURE__ */
353
+ return l.jsxs(r.ScrollView,{contentContainerStyle:p.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:Yj,nestedScrollEnabled:true,accessibilityLabel:df.empty,children:[s??null,u,a??null,m,
354
+ /* @__PURE__ */l.jsx(QuickPrompts,{pet:e,petRef:t,onSend:n,onVetPrep:i,vet:o,starterPrompts:c,emptyState:d,centered:f})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:n}){let{styles:i}=cb();return e.length===0?null:/* @__PURE__ */l.jsxs(r.View,{style:i.followUps,children:[
355
+ /* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.followUpsHeading,accessibilityRole:"header",children:n??df.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */l.jsx(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:n}){let{theme:i,styles:o}=cb(),s=Qp(),a=lg(s.followUpInMs,{delayMs:Kp(s,t)});/* @__PURE__ */
356
356
  return l.jsx(r.Animated.View,{style:a,children:/* @__PURE__ */l.jsxs(PressScale,{onPress:()=>n(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[o.followUpSlot,t>0?o.followUpSlotRuled:null],style:o.followUpRow,children:[
357
357
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:o.followUpText,children:e}),
358
- /* @__PURE__ */l.jsx(PlusGlyph,{size:Mj,color:i.slots.chip?.textColor??i.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:n}){let{styles:i}=Ym(),o=vh(e)?Nf(n):void 0,s=nh(e);/* @__PURE__ */
358
+ /* @__PURE__ */l.jsx(PlusGlyph,{size:Qj,color:i.slots.chip?.textColor??i.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:n}){let{styles:i}=cb(),o=Ah(e)?ih(n):void 0,s=yh(e);/* @__PURE__ */
359
359
  return l.jsxs(r.View,{style:i.centered,accessible:true,accessibilityRole:"alert",children:[s!==null?/* @__PURE__ */l.jsx(Text,{style:i.errorText,testID:"everfur-chat-cap-reached",children:s.reached}):null,
360
- /* @__PURE__ */l.jsx(Text,{style:i.errorText,children:e.displayMessage}),s!==null&&s.guidance!==null?/* @__PURE__ */l.jsx(Text,{style:i.errorText,testID:"everfur-chat-cap-guidance",children:s.guidance}):null,o!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Yd.addPet,style:i.retryButton,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.retryLabel,children:Yd.addPet})}):null,e.retryable?/* @__PURE__ */l.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Yd.retry,style:i.retryButton,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.retryLabel,children:Yd.retry})}):null]})}function PopulatedState({messages:e,prompts:n,onSelectPrompt:i,isStreaming:o,onAnswerCheckin:s,onCopy:a,sentimentByMessage:u,onSentiment:c,feedbackNote:d,imagesByMessage:f,onPreview:h,notice:p,reconnecting:g,onRetry:m,onStartNew:b,petRef:y,onFindVet:v,vet:x,onOpenUrl:w,petName:k,actions:C,answerCards:S,threadTop:j,pendingCheckin:_,threadAside:R,threadAsideKey:T,followUpLabel:I,openingCard:P,earlier:z}){let{styles:E}=Ym(),O=Mp();Zp(e.length,O);let A=t.useMemo(()=>Zk(Xk(e)),[e]),M=oh(e,o),F=e[e.length-1],D=R??null,L=Ij(e,o,D===null?null:T??"shown"),B=Gp(e),V=e[0],H=P!==void 0&&V!==void 0&&V.role==="user"&&V.text.trim()===P.prompt?V.id:null;/* @__PURE__ */
361
- return l.jsxs(r.ScrollView,{ref:L.ref,style:E.list,contentContainerStyle:S!==null?E.listContentCards:E.listContent,accessibilityLabel:Yd.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:Aj,nestedScrollEnabled:true,onLayout:L.onLayout,onContentSizeChange:L.onContentSizeChange,onScroll:L.onScroll,scrollEventThrottle:Oj,onScrollBeginDrag:L.onScrollBeginDrag,onScrollEndDrag:L.onScrollEnd,onMomentumScrollEnd:L.onScrollEnd,children:[j??null,_,z!==null?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{z.load()},disabled:z.loading,accessibilityRole:"button",accessibilityLabel:z.loading?Zh.loadingEarlier:Zh.earlier,accessibilityState:{disabled:z.loading,busy:z.loading},hitSlop:wm,style:E.earlierButton,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:E.earlierLabel,children:z.loading?Zh.loadingEarlier:Zh.earlier})}):null,e.map(t=>t.id===H&&P!==void 0?/* @__PURE__ */l.jsx(OpeningCard,{card:P.card,onLayout:L.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */l.jsx(CheckinCard,{message:t,checkin:t.checkin,onAnswer:s,petRef:y,onFindVet:v,vet:x,onLayout:L.rowLayout(t.id)},t.id):/* @__PURE__ */l.jsx(MessageRow,{onLayout:L.rowLayout(t.id),message:t,revealing:o&&t===F&&t.role==="assistant",onCopy:a,sentiment:t.responseId===void 0?null:u[String(t.responseId)]??null,onSentiment:c,note:t.responseId!==void 0&&d?.responseId===String(t.responseId)?d.kind:null,images:f[t.id]??zj,onPreview:h,onOpenUrl:w,entering:B(t.id),answerCards:S,messages:e},t.id)),g?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:E.reconnectingCaption,accessibilityRole:"text",children:Yd.reconnecting}):null,M?/* @__PURE__ */l.jsx(TypingIndicator,{petName:k,inline:S!==null}):null,p!==null?/* @__PURE__ */l.jsx(TurnNoticeCard,{notice:p,onRetry:m,onStartNew:b}):null,S!==null?/* @__PURE__ */l.jsx(CardsFollowUps,{prompts:n,onSelectPrompt:i,label:I,actions:C,options:S}):/* @__PURE__ */l.jsx(FollowUps,{prompts:n,onSelectPrompt:i,label:I}),D!==null?/* @__PURE__ */l.jsx(r.View,{onLayout:L.asideLayout,children:D}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:n}){let{styles:i}=Ym(),o=e.tone==="error";/* @__PURE__ */
360
+ /* @__PURE__ */l.jsx(Text,{style:i.errorText,children:e.displayMessage}),s!==null&&s.guidance!==null?/* @__PURE__ */l.jsx(Text,{style:i.errorText,testID:"everfur-chat-cap-guidance",children:s.guidance}):null,o!==void 0?/* @__PURE__ */l.jsx(r.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:df.addPet,style:i.retryButton,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.retryLabel,children:df.addPet})}):null,e.retryable?/* @__PURE__ */l.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:df.retry,style:i.retryButton,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.retryLabel,children:df.retry})}):null]})}function PopulatedState({messages:e,prompts:n,onSelectPrompt:i,isStreaming:o,onAnswerCheckin:s,onCopy:a,sentimentByMessage:u,onSentiment:c,feedbackNote:d,imagesByMessage:f,onPreview:h,notice:p,reconnecting:g,onRetry:m,onStartNew:b,petRef:y,onFindVet:v,vet:x,onOpenUrl:w,petName:k,actions:C,answerCards:S,threadTop:j,pendingCheckin:_,threadAside:R,threadAsideKey:T,followUpLabel:I,openingCard:P,earlier:z}){let{styles:E}=cb(),O=Qp();hg(e.length,O);let A=t.useMemo(()=>hC(fC(e)),[e]),M=wh(e,o),F=e[e.length-1],D=R??null,L=$j(e,o,D===null?null:T??"shown"),B=ag(e),V=e[0],H=P!==void 0&&V!==void 0&&V.role==="user"&&V.text.trim()===P.prompt?V.id:null;/* @__PURE__ */
361
+ return l.jsxs(r.ScrollView,{ref:L.ref,style:E.list,contentContainerStyle:S!==null?E.listContentCards:E.listContent,accessibilityLabel:df.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:Yj,nestedScrollEnabled:true,onLayout:L.onLayout,onContentSizeChange:L.onContentSizeChange,onScroll:L.onScroll,scrollEventThrottle:Kj,onScrollBeginDrag:L.onScrollBeginDrag,onScrollEndDrag:L.onScrollEnd,onMomentumScrollEnd:L.onScrollEnd,children:[j??null,_,z!==null?/* @__PURE__ */l.jsx(r.Pressable,{onPress:()=>{z.load()},disabled:z.loading,accessibilityRole:"button",accessibilityLabel:z.loading?hp.loadingEarlier:hp.earlier,accessibilityState:{disabled:z.loading,busy:z.loading},hitSlop:Fm,style:E.earlierButton,children:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:E.earlierLabel,children:z.loading?hp.loadingEarlier:hp.earlier})}):null,e.map(t=>t.id===H&&P!==void 0?/* @__PURE__ */l.jsx(OpeningCard,{card:P.card,onLayout:L.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */l.jsx(CheckinCard,{message:t,checkin:t.checkin,onAnswer:s,petRef:y,onFindVet:v,vet:x,onLayout:L.rowLayout(t.id)},t.id):/* @__PURE__ */l.jsx(MessageRow,{onLayout:L.rowLayout(t.id),message:t,revealing:o&&t===F&&t.role==="assistant",onCopy:a,sentiment:t.responseId===void 0?null:u[String(t.responseId)]??null,onSentiment:c,note:t.responseId!==void 0&&d?.responseId===String(t.responseId)?d.kind:null,images:f[t.id]??qj,onPreview:h,onOpenUrl:w,entering:B(t.id),answerCards:S,messages:e},t.id)),g?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:E.reconnectingCaption,accessibilityRole:"text",children:df.reconnecting}):null,M?/* @__PURE__ */l.jsx(TypingIndicator,{petName:k,inline:S!==null}):null,p!==null?/* @__PURE__ */l.jsx(TurnNoticeCard,{notice:p,onRetry:m,onStartNew:b}):null,S!==null?/* @__PURE__ */l.jsx(CardsFollowUps,{prompts:n,onSelectPrompt:i,label:I,actions:C,options:S}):/* @__PURE__ */l.jsx(FollowUps,{prompts:n,onSelectPrompt:i,label:I}),D!==null?/* @__PURE__ */l.jsx(r.View,{onLayout:L.asideLayout,children:D}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:n}){let{styles:i}=cb(),o=e.tone==="error";/* @__PURE__ */
362
362
  return l.jsxs(r.View,{style:[i.turnNotice,o?i.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
363
363
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:[i.turnNoticeTitle,o?i.turnNoticeTitleError:null],children:e.title}),
364
364
  /* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
365
- /* @__PURE__ */l.jsx(r.Pressable,{onPress:e.action==="startNew"?n:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:wm,style:i.turnNoticeAction,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.turnNoticeActionLabel,children:e.actionLabel})})]})}var zj=/* @__PURE__ */Object.freeze([]),Ej=/* @__PURE__ */Object.freeze([]),Oj=16,Aj=r.Platform.OS==="ios"?"interactive":"on-drag",Mj=18;function MessageRow({message:e,revealing:n,onCopy:i,sentiment:o,onSentiment:s,note:a,images:u,onPreview:c,onOpenUrl:d,onLayout:f,entering:h,answerCards:p,messages:g}){let{theme:m,styles:b}=Ym(),y=Mp(),v=qp(h,y),x=Yp(e.text,n,y),w=e.role==="user",k=e.role==="vet",C=e.role==="assistant",S=Sp(),j=C&&!n?S:void 0,_=j!==void 0&&AC(e.text,j),R=C&&!m.meta.hidePoweredBy,T=w?Yd.senderUser:k?hh(e):R?Yd.assistantName:Yd.senderAssistant,I=k?nC(e.createdAt):null,P=t.useCallback(t=>s(e,t),[s,e]),z=e.pending!==true,E=C&&m.meta.assistantAvatarUrl!==null?/* @__PURE__ */l.jsx(AssistantSender,{avatarUrl:m.meta.assistantAvatarUrl,named:R,styles:b}):R?p!==null?/* @__PURE__ */l.jsx(CardsByline,{label:Yd.assistantName}):/* @__PURE__ */l.jsx(Text,{tier:"control",style:b.assistantName,children:Yd.assistantName}):null,O=p!==null;return C&&p!==null?/* @__PURE__ */l.jsx(r.Animated.View,{style:[b.rowBlock,v],onLayout:f,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */l.jsx(CardsAnswer,{message:e,text:x,streaming:n,messages:g,options:p,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,sender:E,onOpenUrl:d,footer:t=>/* @__PURE__ */l.jsx(MessageFooter,{message:e,onCopy:i,sentiment:o,onSentiment:t&&e.responseId!==void 0?P:void 0,note:a})})}):/* @__PURE__ */l.jsxs(r.View,{style:[b.rowBlock,w?b.rowBlockUser:b.rowBlockAssistant],onLayout:f,children:[
365
+ /* @__PURE__ */l.jsx(r.Pressable,{onPress:e.action==="startNew"?n:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Fm,style:i.turnNoticeAction,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.turnNoticeActionLabel,children:e.actionLabel})})]})}var qj=/* @__PURE__ */Object.freeze([]),Gj=/* @__PURE__ */Object.freeze([]),Kj=16,Yj=r.Platform.OS==="ios"?"interactive":"on-drag",Qj=18;function MessageRow({message:e,revealing:n,onCopy:i,sentiment:o,onSentiment:s,note:a,images:u,onPreview:c,onOpenUrl:d,onLayout:f,entering:h,answerCards:p,messages:g}){let{theme:m,styles:b}=cb(),y=Qp(),v=sg(h,y),x=cg(e.text,n,y),w=e.role==="user",k=e.role==="vet",C=e.role==="assistant",S=Bp(),j=C&&!n?S:void 0,_=j!==void 0&&YC(e.text,j),R=C&&!m.meta.hidePoweredBy,T=w?df.senderUser:k?Th(e):R?df.assistantName:df.senderAssistant,I=k?yC(e.createdAt):null,P=t.useCallback(t=>s(e,t),[s,e]),z=e.pending!==true,E=C&&m.meta.assistantAvatarUrl!==null?/* @__PURE__ */l.jsx(AssistantSender,{avatarUrl:m.meta.assistantAvatarUrl,named:R,styles:b}):R?p!==null?/* @__PURE__ */l.jsx(CardsByline,{label:df.assistantName}):/* @__PURE__ */l.jsx(Text,{tier:"control",style:b.assistantName,children:df.assistantName}):null,O=p!==null;return C&&p!==null?/* @__PURE__ */l.jsx(r.Animated.View,{style:[b.rowBlock,v],onLayout:f,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */l.jsx(CardsAnswer,{message:e,text:x,streaming:n,messages:g,options:p,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,sender:E,onOpenUrl:d,footer:t=>/* @__PURE__ */l.jsx(MessageFooter,{message:e,onCopy:i,sentiment:o,onSentiment:t&&e.responseId!==void 0?P:void 0,note:a})})}):/* @__PURE__ */l.jsxs(r.View,{style:[b.rowBlock,w?b.rowBlockUser:b.rowBlockAssistant],onLayout:f,children:[
366
366
  /* @__PURE__ */l.jsx(r.View,{style:[b.row,w?b.rowUser:b.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */l.jsxs(r.Animated.View,{style:[b.bubble,O?b.bubbleCards:null,w?b.bubbleSideUser:null,v],children:[E,k?/* @__PURE__ */l.jsxs(r.View,{style:b.vetHeader,children:[
367
367
  /* @__PURE__ */l.jsx(Text,{tier:"control",style:b.vetSender,children:T}),I!==null?/* @__PURE__ */l.jsx(Text,{tier:"compact",style:b.vetTime,children:I}):null]}):null,
368
368
  /* @__PURE__ */l.jsxs(r.View,{style:[w?b.bubbleUser:k?b.bubbleVet:b.bubbleAssistant,w&&O?b.bubbleUserCards:null,e.pending?b.bubblePending:null],children:[w&&u.length>0?/* @__PURE__ */l.jsx(SentImages,{images:u,onPreview:e=>c({uri:e.uri,label:e.filename})}):null,
369
- /* @__PURE__ */l.jsx(Text,{style:w?O?[b.bubbleTextUser,b.bubbleTextUserCards]:b.bubbleTextUser:k?b.bubbleTextVet:b.bubbleTextAssistant,children:C?MC(x,{bold:b.bubbleBold,italic:b.bubbleItalic,code:b.bubbleCode},j):e.text})]})]})}),C&&!n?/* @__PURE__ */l.jsx(CitationCards,{citations:e.citations,onOpenUrl:d}):null,z&&!(w&&p!==null)?/* @__PURE__ */l.jsx(MessageFooter,{message:e,onCopy:i,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,note:a}):null]})}var Fj=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&Fj.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function Dj(){let{runtime:e}=Lc(),r=e.entitlements??null,n=t.useCallback(e=>r===null?()=>{}:r.subscribe(e),[r]),i=r===null?NO_SNAPSHOT2:r.getSnapshot,l=t.useSyncExternalStore(n,i,i);return t.useMemo(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var Lj=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function Bj(e,r,n=false){let[i,o]=t.useState(null);if(!e)return Lj;let s=/* @__PURE__ */l.jsx(AskRunner,{ready:textingAskThreadReady(r),onAsk:o,entry:n}),a=n&&i!==null&&i.canOpen?{label:f.textingAskLines(i).accept,onOpen:i.open}:null;if(i===null||i.stage==="hidden"||i.stage==="dismissed")return{runner:s,line:null,entry:null,stage:null,headerEntry:a};let u=f.textingAskLines(i),c=/* @__PURE__ */l.jsx(AskLine,{stage:i.stage,text:i.stage==="verified"?u.verified:u.line,accept:u.accept,dismiss:u.dismiss,onAccept:i.accept,onDismiss:i.dismiss}),d=i.stage==="enrolling"?/* @__PURE__ */l.jsx(f.ChatTextingAskComposer,{ask:i}):null;return{runner:s,line:c,entry:d,stage:i.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:r,entry:n}){let{userRef:i}=Lc(),o=Dj(),s=i!==null&&o;return t.useEffect(()=>{s||r(null)},[s,r]),s?/* @__PURE__ */l.jsx(f.ChatTextingAskController,{enabled:true,ready:e,onAsk:r,entry:n}):null}function AskLine({stage:e,text:t,accept:n,dismiss:i,onAccept:o,onDismiss:s}){let{theme:a,styles:u}=Ym(),c=!a.meta.hidePoweredBy,d=c?Yd.assistantName:Yd.senderAssistant,f=a.meta.assistantAvatarUrl!==null?/* @__PURE__ */l.jsx(AssistantSender,{avatarUrl:a.meta.assistantAvatarUrl,named:c,styles:u}):c?/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.assistantName,children:Yd.assistantName}):null;/* @__PURE__ */
369
+ /* @__PURE__ */l.jsx(Text,{style:w?O?[b.bubbleTextUser,b.bubbleTextUserCards]:b.bubbleTextUser:k?b.bubbleTextVet:b.bubbleTextAssistant,children:C?QC(x,{bold:b.bubbleBold,italic:b.bubbleItalic,code:b.bubbleCode},j):e.text})]})]})}),C&&!n?/* @__PURE__ */l.jsx(CitationCards,{citations:e.citations,onOpenUrl:d}):null,z&&!(w&&p!==null)?/* @__PURE__ */l.jsx(MessageFooter,{message:e,onCopy:i,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,note:a}):null]})}var Xj=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&Xj.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function Zj(){let{runtime:e}=Hc(),r=e.entitlements??null,n=t.useCallback(e=>r===null?()=>{}:r.subscribe(e),[r]),i=r===null?NO_SNAPSHOT2:r.getSnapshot,l=t.useSyncExternalStore(n,i,i);return t.useMemo(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var Jj=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function e_(e,r,n=false){let[i,o]=t.useState(null);if(!e)return Jj;let s=/* @__PURE__ */l.jsx(AskRunner,{ready:textingAskThreadReady(r),onAsk:o,entry:n}),a=n&&i!==null&&i.canOpen?{label:h.textingAskLines(i).accept,onOpen:i.open}:null;if(i===null||i.stage==="hidden"||i.stage==="dismissed")return{runner:s,line:null,entry:null,stage:null,headerEntry:a};let u=h.textingAskLines(i),c=/* @__PURE__ */l.jsx(AskLine,{stage:i.stage,text:i.stage==="verified"?u.verified:u.line,accept:u.accept,dismiss:u.dismiss,onAccept:i.accept,onDismiss:i.dismiss}),d=i.stage==="enrolling"?/* @__PURE__ */l.jsx(h.ChatTextingAskComposer,{ask:i}):null;return{runner:s,line:c,entry:d,stage:i.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:r,entry:n}){let{userRef:i}=Hc(),o=Zj(),s=i!==null&&o;return t.useEffect(()=>{s||r(null)},[s,r]),s?/* @__PURE__ */l.jsx(h.ChatTextingAskController,{enabled:true,ready:e,onAsk:r,entry:n}):null}function AskLine({stage:e,text:t,accept:n,dismiss:i,onAccept:o,onDismiss:s}){let{theme:a,styles:u}=cb(),c=!a.meta.hidePoweredBy,d=c?df.assistantName:df.senderAssistant,f=a.meta.assistantAvatarUrl!==null?/* @__PURE__ */l.jsx(AssistantSender,{avatarUrl:a.meta.assistantAvatarUrl,named:c,styles:u}):c?/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.assistantName,children:df.assistantName}):null;/* @__PURE__ */
370
370
  return l.jsxs(r.View,{style:[u.rowBlock,u.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
371
371
  /* @__PURE__ */l.jsx(r.View,{style:[u.row,u.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${d}: ${t}`,children:/* @__PURE__ */l.jsxs(r.View,{style:u.bubble,children:[f,
372
- /* @__PURE__ */l.jsx(r.View,{style:u.bubbleAssistant,children:/* @__PURE__ */l.jsx(Text,{style:u.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */l.jsx(r.View,{style:u.askChips,children:[{label:n,onPress:o,testID:"everfur-texting-ask-accept"},{label:i,onPress:s,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */l.jsx(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:u.askChip,testID:e.testID,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.askChipText,children:e.label})},e.testID))}):null]})}function Vj(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),r=globalThis;return r[e]??(r[e]=t.createContext(null))}var Hj=/* @__PURE__ */Vj();function Uj(e){return typeof e=="object"&&e!==null&&e.ok===true}function Nj(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ze(t.error)}function $j(e){let r=t.useContext(Hj),n=r?.onMessageSent,i=r?.onFreeCapReached,l=t.useCallback((...t)=>{let r=e(...t);return Promise.resolve(r).then(e=>{try{if(Uj(e)){n?.();return}let t=i===void 0?null:Nj(e);t!==null&&i?.(t)}catch{}},()=>{}),r},[e,n,i]);return n===void 0&&i===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
373
- return l.jsx(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */l.jsx(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */l.jsx(ChatBody,{...e})})})}function Wj(){try{return Lc()}catch{return null}}function qj(e){return th({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function ChatBody(e){let t=Wj();return t===null?/* @__PURE__ */l.jsx(ChatBodyAlone,{...e}):/* @__PURE__ */l.jsx(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let r=qj(e),n=JSON.stringify(r),i=e.petRef??null,o=t.useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:r}),isLocked:()=>false,planPage:null,planPetRef:i,inProvider:false,telemetry:null}),[n,i]);/* @__PURE__ */
374
- return l.jsx(ChatSurface,{...e,settings:o})}function ChatBodyInProvider({activePet:e,telemetry:r,...n}){let{presentation:i,isLocked:isLocked}=eh(qj(n)),o=wd("healthPlan"),s=i.chatTopCard==="focus"&&n.topCard===void 0&&o,a=n.petRef??e??null,u=useHealthPlanPage({petRef:a,enabled:s}),c=s&&u.phase==="ready"?u.page:null,d=t.useMemo(()=>({presentation:i,isLocked:isLocked,planPage:c,planPetRef:a,inProvider:true,telemetry:r}),[i,isLocked,c,a,r]);/* @__PURE__ */
375
- return l.jsx(ChatSurface,{...n,settings:d})}function ChatSurface({settings:e,petRef:i,conversationId:o,style:s,renderPending:a,onCopy:u,onPetChange:c,onVetPrep:d,onFindVet:f,renderVetAction:h,attachments:p,pet:g,onAddPet:m,checkinTarget:b,handoffToken:y,initialAsk:v,initialAskKey:x,composerSeed:w,lifecycle:k,refreshIntervalMs:C,refreshesBlankThread:S,openUnreadOnRefresh:j,draftStore:_,vetReturnTo:R,vetUsState:T,vetPrefer:I,onOpenUrl:P,keyboardVerticalOffset:z,topCard:E,onOpenHealthPlan:O,answerCards:A,historySheet:M,historyBar:F,starterPrompts:D,emptyState:L,header:B=true,textingEntry:V=true,renderEmptyHeader:H,followUpPolicy:U,initialAskCard:N}){let{presentation:$,isLocked:isLocked,planPage:W,planPetRef:q}=e,{theme:G,styles:K}=Ym(),Y=ox()??($.chatAnswerStyle==="cards"?ek:null),Q=t.useMemo(()=>Y===null?null:Y(G),[Y,G]),X=useHostPoweredBy(),Z=Mp(),J=t.useMemo(()=>ph(i,o),[i,o]),ee=useEverfurChat(J),te=$j(ee.send),re=t.useMemo(()=>te===ee.send?ee:{...ee,send:te},[ee,te]),ne=rh(re),ie=Wk(),le=sp(re),oe=n.useSafeAreaInsets(),se=lh(re,"web"),ae=t.useMemo(()=>f===void 0?void 0:()=>{Hf(f,"emergency")},[f]),ue=t.useMemo(()=>R===void 0&&T===void 0&&I===void 0?void 0:{returnTo:R,usState:T,prefer:I},[R,T,I]),ce=Vv(ie.pets,re.petRef),de=t.useMemo(()=>hp(re.messages,ce?.name??null),[re.messages,ce?.name]),fe=gp(de);Gk(re),Zp(fe.showBanner,Z);let he=Wj(),pe=Yh(y,he);Xh(re.openCheckin,b??pe,{petRef:re.petRef,pinned:i!==void 0,ready:!re.isBootstrapping,selectPet:e=>{ie.setActivePet(e),Hf(c,e)}}),Ih(re.askEverfur,re.isBootstrapping,v,x);let ge=t.useMemo(()=>Th(w),[w]),me=t.useMemo(()=>Th(v),[v]),be=t.useMemo(()=>N!==void 0&&me!==null?{card:N,prompt:me}:void 0,[N,me]),ye=t.useMemo(()=>k===void 0?createAppStateLifecycle():k??void 0,[k]);Bh(ye,{conversationId:re.conversationId===null?null:String(re.conversationId),isTurnInFlight:re.isStreaming,refreshesBlankThread:S===true||j===true,refresh:re.refreshActiveThread===void 0?void 0:()=>re.refreshActiveThread?.(Ah(j===true,Mh(ye,ag)))??Promise.resolve()},{intervalMs:C===void 0?3e4:C,isVisibleFallback:ag}),Fh({isStreaming:re.isStreaming,status:re.status,conversationId:re.conversationId===null?null:String(re.conversationId),unreadCount:re.unreadCount,markRead:re.markRead},()=>Mh(ye,ag));let ve=re.pendingCheckin??null,xe=ve===null?null:/* @__PURE__ */l.jsx(r.View,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */l.jsx(CheckinCard,{message:ve.message,checkin:ve.checkin,onAnswer:re.petRef?re.answerCheckin:null,petRef:re.petRef,onFindVet:ae,vet:ue,onOpen:()=>{re.resumeConversation(ve.conversationId)}})}),we=(re.hasUnreadThreads??false)||le.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(re.unreadCount??0)>0,ke=Ch(re.messages),[Ce,Se]=t.useState(null),je=t.useCallback(()=>Se(null),[]),[_e,Re]=t.useState(null),[Te,Ie]=t.useState(null),Pe=t.useRef(null);t.useEffect(()=>()=>{Pe.current&&clearTimeout(Pe.current)},[]);let ze=t.useCallback((e,t)=>{Ie({responseId:String(e),kind:t}),Pe.current&&clearTimeout(Pe.current),Pe.current=t==="thanks"?setTimeout(()=>{Ie(null),Pe.current=null},rm):null},[]),Ee=t.useCallback((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=re.sentimentByMessage[String(r)];Ie(e=>e?.responseId===String(r)?null:e),re.feedback(r,t).then(e=>{e.ok||ze(r,"failed")}),t==="down"&&n!=="down"&&Re(r)},[re,ze]),Oe=t.useCallback(async(e,t)=>_e===null||!(e==null&&t===null?{ok:true}:await re.feedback(_e,"down",e??"other",t)).ok?false:(Re(null),ze(_e,"thanks"),true),[re,_e,ze]),Ae=t.useCallback(()=>Re(null),[]),Me=t.useCallback(e=>{re.send(e)},[re.send]),Fe=t.useMemo(()=>P===void 0?void 0:e=>{Hf(P,e,"citation")},[P]),De=r.Platform.OS==="ios"?"padding":void 0,Le=ck(z,De!==void 0),Be=Le.topInWindow===null?oe.top:Math.max(0,oe.top-Le.topInWindow),Ve=fk(),He=t.useMemo(()=>O===void 0?void 0:()=>{Hf(O,q)},[O,q]),Ue=t.useMemo(()=>E===void 0?healthPlanTopCard(W,{onOpenPlan:He}):void 0,[E,W,He]),Ne=$.chatTopCard==="focus"?E??Ue:void 0,[$e,We]=t.useState(true),qe=t.useCallback(e=>{re.send(e)},[re.send]),Ge=t.useMemo(()=>bh(U,$,isLocked("chatFollowUpCount")),[U,$,isLocked]),Ke=$.chatAnswerStyle==="cards",Ye=t.useMemo(()=>Ke&&re.messages.length===0?Yj(re.suggestedPrompts):void 0,[Ke,re.messages.length,re.suggestedPrompts]),Qe=$.chatHistoryStyle==="sheet",Xe=re.messages.length===0,Ze=Ne!==void 0?/* @__PURE__ */l.jsx(TopCardPill,{card:Ne,open:$e,onOpenChange:We}):null,Je=F??(B?void 0:Qj),et=Je!==void 0?/* @__PURE__ */l.jsx(HistoryBar,{bar:Je,history:le,empty:Xe,unread:we,extra:Ze}):null,tt=$.chatHistoryBar==="scroll"&&(ne==="empty"||ne==="populated"),rt=Ne===void 0?null:/* @__PURE__ */l.jsxs(l.Fragment,{children:[
376
- /* @__PURE__ */l.jsx(TopCard,{card:Ne,open:$e,onOpenChange:We,ask:qe}),Je===void 0?Ze:null]}),nt=Je!==void 0,it=le.load,lt=le.open;t.useEffect(()=>{nt&&!lt&&it()},[nt,lt,re.conversationId,it]);let ot={send:re.send,stop:re.stop,isStreaming:re.isStreaming,conversationId:re.conversationId,seed:ge,draftStore:_,onStage:ke.stage,onPreview:Se,petName:ce?.name??null,petBreed:ce?.breed??null,compact:$.chatComposerStyle==="compact",petPlaceholder:$.chatComposerPlaceholder==="pet_name",dimEmptySend:$.chatSendButton==="dim_when_empty",mood:Xj(ne,fe.source?.level??null),dictation:$.chatComposerMic,telemetry:e.telemetry},st=Bj($.chatTextingAsk&&e.inProvider,re,V),at=p!==void 0&&$.chatComposerUpload,ut=!$.chatGeneralBanner&&fe.source?.level==="general";
372
+ /* @__PURE__ */l.jsx(r.View,{style:u.bubbleAssistant,children:/* @__PURE__ */l.jsx(Text,{style:u.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */l.jsx(r.View,{style:u.askChips,children:[{label:n,onPress:o,testID:"everfur-texting-ask-accept"},{label:i,onPress:s,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */l.jsx(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:u.askChip,testID:e.testID,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:u.askChipText,children:e.label})},e.testID))}):null]})}function t_(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),r=globalThis;return r[e]??(r[e]=t.createContext(null))}var r_=/* @__PURE__ */t_();function n_(e){return typeof e=="object"&&e!==null&&e.ok===true}function i_(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:Ee(t.error)}function l_(e){let r=t.useContext(r_),n=r?.onMessageSent,i=r?.onFreeCapReached,l=t.useCallback((...t)=>{let r=e(...t);return Promise.resolve(r).then(e=>{try{if(n_(e)){n?.();return}let t=i===void 0?null:i_(e);t!==null&&i?.(t)}catch{}},()=>{}),r},[e,n,i]);return n===void 0&&i===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
373
+ return l.jsx(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */l.jsx(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */l.jsx(ChatBody,{...e})})})}function o_(){try{return Hc()}catch{return null}}function s_(e){return mh({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function ChatBody(e){let t=o_();return t===null?/* @__PURE__ */l.jsx(ChatBodyAlone,{...e}):/* @__PURE__ */l.jsx(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let r=s_(e),n=JSON.stringify(r),i=e.petRef??null,o=t.useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:r}),isLocked:()=>false,planPage:null,planPetRef:i,inProvider:false,telemetry:null}),[n,i]);/* @__PURE__ */
374
+ return l.jsx(ChatSurface,{...e,settings:o})}function ChatBodyInProvider({activePet:e,telemetry:r,...n}){let{presentation:i,isLocked:isLocked}=gh(s_(n)),o=Sd("healthPlan"),s=i.chatTopCard==="focus"&&n.topCard===void 0&&o,a=n.petRef??e??null,u=useHealthPlanPage({petRef:a,enabled:s}),c=s&&u.phase==="ready"?u.page:null,d=t.useMemo(()=>({presentation:i,isLocked:isLocked,planPage:c,planPetRef:a,inProvider:true,telemetry:r}),[i,isLocked,c,a,r]);/* @__PURE__ */
375
+ return l.jsx(ChatSurface,{...n,settings:d})}function ChatSurface({settings:e,petRef:i,conversationId:o,style:s,renderPending:a,onCopy:u,onPetChange:c,onVetPrep:d,onFindVet:f,renderVetAction:h,attachments:p,pet:g,onAddPet:m,checkinTarget:b,handoffToken:y,initialAsk:v,initialAskKey:x,composerSeed:w,lifecycle:k,refreshIntervalMs:C,refreshesBlankThread:S,openUnreadOnRefresh:j,draftStore:_,vetReturnTo:R,vetUsState:T,vetPrefer:I,onOpenUrl:P,keyboardVerticalOffset:z,topCard:E,onOpenHealthPlan:O,answerCards:A,historySheet:M,historyBar:F,starterPrompts:D,emptyState:L,header:B=true,textingEntry:V=true,renderEmptyHeader:H,followUpPolicy:U,initialAskCard:N}){let{presentation:$,isLocked:isLocked,planPage:W,planPetRef:q}=e,{theme:G,styles:K}=cb(),Y=wx()??($.chatAnswerStyle==="cards"?mk:null),Q=t.useMemo(()=>Y===null?null:Y(G),[Y,G]),X=useHostPoweredBy(),Z=Qp(),J=t.useMemo(()=>Ih(i,o),[i,o]),ee=useEverfurChat(J),te=l_(ee.send),re=t.useMemo(()=>te===ee.send?ee:{...ee,send:te},[ee,te]),ne=bh(re),ie=oC(),le=kp(re),oe=n.useSafeAreaInsets(),se=xh(re,"web"),ae=t.useMemo(()=>f===void 0?void 0:()=>{rh(f,"emergency")},[f]),ue=t.useMemo(()=>R===void 0&&T===void 0&&I===void 0?void 0:{returnTo:R,usState:T,prefer:I},[R,T,I]),ce=tx(ie.pets,re.petRef),de=t.useMemo(()=>Tp(re.messages,ce?.name??null),[re.messages,ce?.name]),fe=Pp(de);aC(re),hg(fe.showBanner,Z);let he=o_(),pe=cp(y,he);fp(re.openCheckin,b??pe,{petRef:re.petRef,pinned:i!==void 0,ready:!re.isBootstrapping,selectPet:e=>{ie.setActivePet(e),rh(c,e)}}),$h(re.askEverfur,re.isBootstrapping,v,x);let ge=t.useMemo(()=>Nh(w),[w]),me=t.useMemo(()=>Nh(v),[v]),be=t.useMemo(()=>N!==void 0&&me!==null?{card:N,prompt:me}:void 0,[N,me]),ye=t.useMemo(()=>k===void 0?createAppStateLifecycle():k??void 0,[k]);ep(ye,{conversationId:re.conversationId===null?null:String(re.conversationId),isTurnInFlight:re.isStreaming,refreshesBlankThread:S===true||j===true,refresh:re.refreshActiveThread===void 0?void 0:()=>re.refreshActiveThread?.(Yh(j===true,Qh(ye,Cg)))??Promise.resolve()},{intervalMs:C===void 0?3e4:C,isVisibleFallback:Cg}),Xh({isStreaming:re.isStreaming,status:re.status,conversationId:re.conversationId===null?null:String(re.conversationId),unreadCount:re.unreadCount,markRead:re.markRead},()=>Qh(ye,Cg));let ve=re.pendingCheckin??null,xe=ve===null?null:/* @__PURE__ */l.jsx(r.View,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */l.jsx(CheckinCard,{message:ve.message,checkin:ve.checkin,onAnswer:re.petRef?re.answerCheckin:null,petRef:re.petRef,onFindVet:ae,vet:ue,onOpen:()=>{re.resumeConversation(ve.conversationId)}})}),we=(re.hasUnreadThreads??false)||le.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(re.unreadCount??0)>0,ke=Lh(re.messages),[Ce,Se]=t.useState(null),je=t.useCallback(()=>Se(null),[]),[_e,Re]=t.useState(null),[Te,Ie]=t.useState(null),Pe=t.useRef(null);t.useEffect(()=>()=>{Pe.current&&clearTimeout(Pe.current)},[]);let ze=t.useCallback((e,t)=>{Ie({responseId:String(e),kind:t}),Pe.current&&clearTimeout(Pe.current),Pe.current=t==="thanks"?setTimeout(()=>{Ie(null),Pe.current=null},bm):null},[]),Ee=t.useCallback((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=re.sentimentByMessage[String(r)];Ie(e=>e?.responseId===String(r)?null:e),re.feedback(r,t).then(e=>{e.ok||ze(r,"failed")}),t==="down"&&n!=="down"&&Re(r)},[re,ze]),Oe=t.useCallback(async(e,t)=>_e===null||!(e==null&&t===null?{ok:true}:await re.feedback(_e,"down",e??"other",t)).ok?false:(Re(null),ze(_e,"thanks"),true),[re,_e,ze]),Ae=t.useCallback(()=>Re(null),[]),Me=t.useCallback(e=>{re.send(e)},[re.send]),Fe=t.useMemo(()=>P===void 0?void 0:e=>{rh(P,e,"citation")},[P]),De=r.Platform.OS==="ios"?"padding":void 0,Le=jk(z,De!==void 0),Be=Le.topInWindow===null?oe.top:Math.max(0,oe.top-Le.topInWindow),Ve=Rk(),He=t.useMemo(()=>O===void 0?void 0:()=>{rh(O,q)},[O,q]),Ue=t.useMemo(()=>E===void 0?healthPlanTopCard(W,{onOpenPlan:He}):void 0,[E,W,He]),Ne=$.chatTopCard==="focus"?E??Ue:void 0,[$e,We]=t.useState(true),qe=t.useCallback(e=>{re.send(e)},[re.send]),Ge=t.useMemo(()=>Eh(U,$,isLocked("chatFollowUpCount")),[U,$,isLocked]),Ke=$.chatAnswerStyle==="cards",Ye=t.useMemo(()=>Ke&&re.messages.length===0?c_(re.suggestedPrompts):void 0,[Ke,re.messages.length,re.suggestedPrompts]),Qe=$.chatHistoryStyle==="sheet",Xe=re.messages.length===0,Ze=Ne!==void 0?/* @__PURE__ */l.jsx(TopCardPill,{card:Ne,open:$e,onOpenChange:We}):null,Je=F??(B?void 0:d_),et=Je!==void 0?/* @__PURE__ */l.jsx(HistoryBar,{bar:Je,history:le,empty:Xe,unread:we,extra:Ze}):null,tt=$.chatHistoryBar==="scroll"&&(ne==="empty"||ne==="populated"),rt=Ne===void 0?null:/* @__PURE__ */l.jsxs(l.Fragment,{children:[
376
+ /* @__PURE__ */l.jsx(TopCard,{card:Ne,open:$e,onOpenChange:We,ask:qe}),Je===void 0?Ze:null]}),nt=Je!==void 0,it=le.load,lt=le.open;t.useEffect(()=>{nt&&!lt&&it()},[nt,lt,re.conversationId,it]);let ot={send:re.send,stop:re.stop,isStreaming:re.isStreaming,conversationId:re.conversationId,seed:ge,draftStore:_,onStage:ke.stage,onPreview:Se,petName:ce?.name??null,petBreed:ce?.breed??null,compact:$.chatComposerStyle==="compact",petPlaceholder:$.chatComposerPlaceholder==="pet_name",dimEmptySend:$.chatSendButton==="dim_when_empty",mood:f_(ne,fe.source?.level??null),dictation:$.chatComposerMic,telemetry:e.telemetry},st=e_($.chatTextingAsk&&e.inProvider,re,V),at=p!==void 0&&$.chatComposerUpload,ut=!$.chatGeneralBanner&&fe.source?.level==="general";
377
377
  /* @__PURE__ */
378
- return l.jsx(lx.Provider,{value:Q,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{style:[K.container,{paddingTop:Be},s],behavior:De,...Le.avoidingProps,children:[
379
- /* @__PURE__ */l.jsx(KeyboardOffsetProbe,{probeRef:Le.probeRef}),B?/* @__PURE__ */l.jsx(ChatHeader,{pets:ie,petRef:re.petRef,historyUnread:we,onOpenHistory:le.show,onNewChat:le.newConversation,onPetChange:c,onAddPet:m,vet:ue,textingEntry:st.headerEntry}):null,g!==void 0?/* @__PURE__ */l.jsx(PetSetupNotice,{petRef:i??null,pet:g,onRegistered:ie.refresh}):null,!B&&st.headerEntry!==null?/* @__PURE__ */l.jsx(TextingEntryRow,{entry:st.headerEntry,place:"thread"}):null,tt?null:et,ut?null:/* @__PURE__ */l.jsx(UrgencyBanner,{surface:fe,petRef:re.petRef,renderVetAction:h,onFindVet:f,vet:ue,compact:Ve}),
380
- /* @__PURE__ */l.jsx(r.View,{style:K.body,children:Pj(ne,re,{notice:se,vet:ue,onCheckinFindVet:ae,onSelectPrompt:Me,renderPending:a,shownPet:ce,onVetPrep:d,onCopy:u,onSentiment:Ee,feedbackNote:Te,imagesByMessage:ke.byMessage,onPreview:Se,onAddPet:m,onOpenUrl:Fe,threadTop:tt?et:null,pendingCheckin:xe,topCard:rt,starterPrompts:D??Ye,emptyState:L,emptyCentered:$.chatAnswerStyle==="cards",followUpPolicy:Ge,answerCards:$.chatAnswerStyle==="cards"?A??Gj:null,threadAside:st.line,threadAsideKey:st.stage,renderEmptyHeader:H,openingCard:be})}),st.runner,st.entry!==null?/* @__PURE__ */l.jsx(r.View,{style:K.composerOuter,children:/* @__PURE__ */l.jsx(r.View,{style:K.askEntry,children:st.entry})}):at&&p!==void 0?/* @__PURE__ */l.jsx(ComposerWithAttachments,{...ot,attachments:p}):/* @__PURE__ */l.jsx(Composer,{...ot,attachments:null}),G.meta.hidePoweredBy||X?null:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:K.poweredBy,accessibilityRole:"text",accessibilityLabel:Yd.poweredBy,children:Yd.poweredBy}),Qe?/* @__PURE__ */l.jsx(HistorySheet,{chat:re,history:le,sheet:M}):/* @__PURE__ */l.jsx(HistoryDrawer,{chat:re,history:le}),
378
+ return l.jsx(xx.Provider,{value:Q,children:/* @__PURE__ */l.jsxs(r.KeyboardAvoidingView,{style:[K.container,{paddingTop:Be},s],behavior:De,...Le.avoidingProps,children:[
379
+ /* @__PURE__ */l.jsx(KeyboardOffsetProbe,{probeRef:Le.probeRef}),
380
+ /* @__PURE__ */l.jsxs(SdkTabletColumn,{children:[B?/* @__PURE__ */l.jsx(ChatHeader,{pets:ie,petRef:re.petRef,historyUnread:we,onOpenHistory:le.show,onNewChat:le.newConversation,onPetChange:c,onAddPet:m,vet:ue,textingEntry:st.headerEntry}):null,g!==void 0?/* @__PURE__ */l.jsx(PetSetupNotice,{petRef:i??null,pet:g,onRegistered:ie.refresh}):null,!B&&st.headerEntry!==null?/* @__PURE__ */l.jsx(TextingEntryRow,{entry:st.headerEntry,place:"thread"}):null,tt?null:et,ut?null:/* @__PURE__ */l.jsx(UrgencyBanner,{surface:fe,petRef:re.petRef,renderVetAction:h,onFindVet:f,vet:ue,compact:Ve}),
381
+ /* @__PURE__ */l.jsx(r.View,{style:K.body,children:Wj(ne,re,{notice:se,vet:ue,onCheckinFindVet:ae,onSelectPrompt:Me,renderPending:a,shownPet:ce,onVetPrep:d,onCopy:u,onSentiment:Ee,feedbackNote:Te,imagesByMessage:ke.byMessage,onPreview:Se,onAddPet:m,onOpenUrl:Fe,threadTop:tt?et:null,pendingCheckin:xe,topCard:rt,starterPrompts:D??Ye,emptyState:L,emptyCentered:$.chatAnswerStyle==="cards",followUpPolicy:Ge,answerCards:$.chatAnswerStyle==="cards"?A??a_:null,threadAside:st.line,threadAsideKey:st.stage,renderEmptyHeader:H,openingCard:be})}),st.runner,st.entry!==null?/* @__PURE__ */l.jsx(r.View,{style:K.composerOuter,children:/* @__PURE__ */l.jsx(r.View,{style:K.askEntry,children:st.entry})}):at&&p!==void 0?/* @__PURE__ */l.jsx(ComposerWithAttachments,{...ot,attachments:p}):/* @__PURE__ */l.jsx(Composer,{...ot,attachments:null}),G.meta.hidePoweredBy||X?null:/* @__PURE__ */l.jsx(Text,{tier:"compact",style:K.poweredBy,accessibilityRole:"text",accessibilityLabel:df.poweredBy,children:df.poweredBy})]}),Qe?/* @__PURE__ */l.jsx(HistorySheet,{chat:re,history:le,sheet:M}):/* @__PURE__ */l.jsx(HistoryDrawer,{chat:re,history:le}),
381
382
  /* @__PURE__ */l.jsx(FeedbackReasons,{visible:_e!==null,onSubmit:Oe,onSkip:Ae}),
382
383
  /* @__PURE__ */l.jsx(AttachmentImageLightbox,{uri:Ce?.uri??null,label:Ce?.label??"",onClose:je}),
383
- /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:n}){let{styles:i}=Ym(),o=wh(e,t,n);return o.status!=="failed"||o.error===null?null:/* @__PURE__ */l.jsxs(r.View,{style:i.setupNotice,accessible:true,accessibilityRole:"alert",children:[
384
+ /* @__PURE__ */l.jsx(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:n}){let{styles:i}=cb(),o=Fh(e,t,n);return o.status!=="failed"||o.error===null?null:/* @__PURE__ */l.jsxs(r.View,{style:i.setupNotice,accessible:true,accessibilityRole:"alert",children:[
384
385
  /* @__PURE__ */l.jsx(Text,{tier:"compact",style:i.setupNoticeText,children:o.error.displayMessage}),
385
- /* @__PURE__ */l.jsx(r.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:Yd.retry,hitSlop:wm,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.setupNoticeAction,children:Yd.retry})})]})}var Gj=/* @__PURE__ */Object.freeze({}),Kj=3;function Yj(e){let t=[];for(let r of e){let e=r.trim();if(e.length>0&&!t.some(t=>t.label===e)&&t.push(/* @__PURE__ */Object.freeze({label:e})),t.length===Kj)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var Qj=/* @__PURE__ */Object.freeze({chats:Zh.heading,newChat:Zh.newChat});function Xj(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
386
- return l.jsx(Od.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */l.jsx(EverfurChatCore,{...e})})}var Zj=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function Jj(e,r){let{runtime:n,userRef:i,activePet:l,scopeEpoch:o}=Lc(),s=n.unread??null,a=e===void 0?l:e,u=t.useCallback(e=>s===null?NO_SUBSCRIPTION():s.subscribe(e),[s]),c=t.useCallback(()=>s===null||i===null?Zj:s.get(a),[s,i,a]),d=t.useSyncExternalStore(u,c,c),f=t.useCallback(()=>s===null||i===null?Promise.resolve():s.refresh(a),[s,i,a]);return t.useEffect(()=>{f()},[f,o]),Bh(r,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:f}),t.useMemo(()=>({...d,refresh:f}),[d,f])}function useEverfurUnread(e={}){let{lifecycle:r}=e,n=t.useMemo(()=>r===void 0?createAppStateLifecycle():r??void 0,[r]);return Jj(e.petRef,n)}function useEverfurPetProfile(e){let{runtime:r,userRef:n,scopeEpoch:i}=Lc(),l=t.useMemo(()=>createPetsRepository(r.registry.services.authFor(n)),[r,n,i]),o=t.useMemo(()=>({repository:l,petRef:e}),[l,e]),[s,a]=t.useState({key:o,profile:null,loading:e!==null,error:null}),u=s.key===o?s:{profile:null,loading:e!==null,error:null},c=t.useRef(0),d=t.useCallback(async()=>{let e=++c.current;if(o.petRef===null){a({key:o,profile:null,loading:false,error:null});return}a(e=>({key:o,profile:e.key===o?e.profile:null,loading:true,error:null}));let t=await o.repository.getPetProfile(o.petRef);e===c.current&&a(t.ok?{key:o,profile:t.value,loading:false,error:null}:{key:o,profile:null,loading:false,error:t.error})},[o]);return t.useEffect(()=>(d(),()=>{c.current+=1}),[d]),t.useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:d}),[u.profile,u.loading,u.error,d])}function EverfurThemeProvider(e){return t.createElement(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:yd,children:e.children})}exports.APPEARANCE_PRESETS=Ms;exports.APPEARANCE_PRESET_NAMES=As;exports.APPEARANCE_SIZE_RANGES=Fs;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=m;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=g;exports.PHONE_TEXT_SCALE_CAPS=ao;exports.THEME_SLOT_KEYS=Bl;exports.THEME_SLOT_KEYS_BY_SLOT=Vl;exports.THEME_SLOT_NAMES=Ll;exports.TYPE_ROLE_DEFAULTS=lo;exports.TYPE_ROLE_NAMES=io;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.chatHandoffTokenFromUrl=chatHandoffTokenFromUrl;exports.conversationId=conversationId;exports.createAppStateLifecycle=createAppStateLifecycle;exports.createRnRecordsUploadTransport=createRnRecordsUploadTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.headingFace=headingFace;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.registerEverfurDictation=registerEverfurDictation;exports.textRole=textRole;exports.themeAdjustments=themeAdjustments;exports.themeSlotKeysFor=themeSlotKeysFor;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.useEverfurUnread=useEverfurUnread;exports.userFacingError=userFacingError;exports.userRef=userRef;
386
+ /* @__PURE__ */l.jsx(r.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:df.retry,hitSlop:Fm,children:/* @__PURE__ */l.jsx(Text,{tier:"control",style:i.setupNoticeAction,children:df.retry})})]})}var a_=/* @__PURE__ */Object.freeze({}),u_=3;function c_(e){let t=[];for(let r of e){let e=r.trim();if(e.length>0&&!t.some(t=>t.label===e)&&t.push(/* @__PURE__ */Object.freeze({label:e})),t.length===u_)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var d_=/* @__PURE__ */Object.freeze({chats:hp.heading,newChat:hp.newChat});function f_(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
387
+ return l.jsx(Fd.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */l.jsx(EverfurChatCore,{...e})})}var h_=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function p_(e,r){let{runtime:n,userRef:i,activePet:l,scopeEpoch:o}=Hc(),s=n.unread??null,a=e===void 0?l:e,u=t.useCallback(e=>s===null?NO_SUBSCRIPTION():s.subscribe(e),[s]),c=t.useCallback(()=>s===null||i===null?h_:s.get(a),[s,i,a]),d=t.useSyncExternalStore(u,c,c),f=t.useCallback(()=>s===null||i===null?Promise.resolve():s.refresh(a),[s,i,a]);return t.useEffect(()=>{f()},[f,o]),ep(r,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:f}),t.useMemo(()=>({...d,refresh:f}),[d,f])}function useEverfurUnread(e={}){let{lifecycle:r}=e,n=t.useMemo(()=>r===void 0?createAppStateLifecycle():r??void 0,[r]);return p_(e.petRef,n)}function useEverfurPetProfile(e){let{runtime:r,userRef:n,scopeEpoch:i}=Hc(),l=t.useMemo(()=>createPetsRepository(r.registry.services.authFor(n)),[r,n,i]),o=t.useMemo(()=>({repository:l,petRef:e}),[l,e]),[s,a]=t.useState({key:o,profile:null,loading:e!==null,error:null}),u=s.key===o?s:{profile:null,loading:e!==null,error:null},c=t.useRef(0),d=t.useCallback(async()=>{let e=++c.current;if(o.petRef===null){a({key:o,profile:null,loading:false,error:null});return}a(e=>({key:o,profile:e.key===o?e.profile:null,loading:true,error:null}));let t=await o.repository.getPetProfile(o.petRef);e===c.current&&a(t.ok?{key:o,profile:t.value,loading:false,error:null}:{key:o,profile:null,loading:false,error:t.error})},[o]);return t.useEffect(()=>(d(),()=>{c.current+=1}),[d]),t.useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:d}),[u.profile,u.loading,u.error,d])}function EverfurThemeProvider(e){return t.createElement(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:wd,children:e.children})}exports.APPEARANCE_PRESETS=Ls;exports.APPEARANCE_PRESET_NAMES=Ds;exports.APPEARANCE_SIZE_RANGES=Bs;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=b;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=m;exports.PHONE_TEXT_SCALE_CAPS=fo;exports.THEME_SLOT_KEYS=Ul;exports.THEME_SLOT_KEYS_BY_SLOT=Nl;exports.THEME_SLOT_NAMES=Hl;exports.TYPE_ROLE_DEFAULTS=ao;exports.TYPE_ROLE_NAMES=so;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.chatHandoffTokenFromUrl=chatHandoffTokenFromUrl;exports.conversationId=conversationId;exports.createAppStateLifecycle=createAppStateLifecycle;exports.createRnRecordsUploadTransport=createRnRecordsUploadTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.headingFace=headingFace;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.registerEverfurDictation=registerEverfurDictation;exports.textRole=textRole;exports.themeAdjustments=themeAdjustments;exports.themeSlotKeysFor=themeSlotKeysFor;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.useEverfurUnread=useEverfurUnread;exports.userFacingError=userFacingError;exports.userRef=userRef;