@everfur/sdk 1.6.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-cards/index.cjs +2 -2
- package/dist/chat-cards/index.js +9 -9
- package/dist/{chunk-6AIEUA4V.js → chunk-CQUKIPRU.js} +1 -1
- package/dist/{chunk-IXHLESYC.js → chunk-DBQYQLJT.js} +1 -1
- package/dist/{chunk-BN7OAFBS.js → chunk-RF4N4WUN.js} +25 -25
- package/dist/{chunk-LMIBOI3I.js → chunk-ZSCVH4UW.js} +14 -14
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/core/index.cjs +21 -21
- package/dist/core/index.d.cts +6 -0
- package/dist/core/index.d.ts +6 -0
- package/dist/core/index.js +31 -31
- package/dist/index.cjs +359 -359
- package/dist/index.js +234 -234
- package/dist/records/index.cjs +1 -1
- package/dist/records/index.js +1 -1
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/web/health-plan/index.cjs +1 -1
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/index.cjs +172 -172
- package/dist/web/index.js +182 -182
- package/dist/web/records-sheet/index.cjs +1 -1
- package/dist/web/records-sheet/index.js +1 -1
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.js +1 -1
- package/dist/web/televet/booking/index.cjs +1 -1
- package/dist/web/televet/booking/index.js +1 -1
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +41 -41
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
2
|
import{z as e}from"zod";import{createContext,forwardRef as t,createElement as r,useEffect as n,useState as l,useSyncExternalStore as i,useContext as o,useMemo as a,lazy as s,useCallback as u,useRef as c,useReducer as d,useLayoutEffect as f,Component as h,Fragment as p,Suspense as g}from"react";import*as b from"react-native";import{Platform as m,TextInput as y,StyleSheet as v,AccessibilityInfo as k,useColorScheme as w,Dimensions as C,PixelRatio as S,View as x,AppState as _,Text as R,Linking as T,KeyboardAvoidingView as I,Pressable as z,Keyboard as P,Modal as O,ScrollView as E,ActivityIndicator as j,Image as F,UIManager as A,LayoutAnimation as D,Animated as M,useWindowDimensions as L,FlatList as B}from"react-native";import{SafeAreaProvider as H,useSafeAreaInsets as U}from"react-native-safe-area-context";import N from"react-native-sse";import{jsx as $,jsxs as W,Fragment as V}from"react/jsx-runtime";import*as q from"@everfur/sdk/televet/booking";import*as G from"@everfur/sdk/texting";function K(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 Y(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 Q=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 Q(e.error)}var J=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var X=128,Z=128,ee=/[\u0000-\u001F\u007F]/,te=/^[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=Y(t);if(r===0||r>Z)throw new J("invalid-argument",`petRef must be 1..${Z} characters`);if(ee.test(t))throw new J("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=Y(t);if(r===0||r>X)throw new J("invalid-argument",`userRef must be 1..${X} characters`);if(t.includes("@"))throw new J("invalid-argument","userRef must not contain '@'");if(ee.test(t))throw new J("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!te.test(e))throw new J("invalid-argument","conversationId must be a UUID");return e}var re=[{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}],ne=/* @__PURE__ */Object.freeze(re.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ne.map(e=>e.wireCode));var le=/* @__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"}),ie=/* @__PURE__ */Object.freeze(ne.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:le[e.wireCode]}))),oe=new Map(ie.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ae=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(ie.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",...ae]){let t=oe.get(e+r);if(t)return t}}var se=/* @__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 se[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 ue=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return ue.has(e)}var ce=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ce.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var de=500,fe=8e3,he=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(de*2**r,fe);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var pe="This feature isn't available on your account right now.",ge="Something in that request was not right. Check the details and try again.",be=/* @__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:pe,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:ge,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:pe,runtimeDisposed:ge,unknown:"Something went wrong. Please try again."}),me="This session has ended. Please sign in again.",ye="linked_account_read_only";function ve(e,t,r){return e==="conflict"&&r===ye?pe:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?me:userFacingError(e)}function userFacingError(e){return be[e]}function ke(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var we=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ye,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:ve(e,t?.wireCode,n?ye:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&we.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&ke(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ke(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var Ce=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Se(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 Te(e)}var xe=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,_e=/[\s\u0000-\u001f\u007f\\]/,Re={"http:":"80","https:":"443"};function Te(e,t){let r=e.trim();let n=_e.test(r)?null:xe.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Re[f]?"":String(h),g=Re[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var Ie="application/pdf",ze=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Pe=e=>ze.includes(e);function Oe(e,t){return e===Ie||t!==void 0&&Pe(e)&&t.includes(e)}var Ee=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function je(e){return Oe(e,ze)?Ee[e]:Ee["application/pdf"]}var Fe="file",Ae="multipart upload failed";function De(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Fe,e.file)}catch{return Promise.reject(new Error(Ae))}return e.fetch!==void 0?Be(e.fetch,e.url,t,e.signal):Le(e.url,t,e.signal)}function Me(e){return e>=200&&e<300}function Le(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ae));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ae))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Me(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function Be(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var He="records upload: the file handle has no uri",Ue="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
4
|
+
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var Q=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 Q(e.error)}var Z=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var J=128,X=128,ee=/[\u0000-\u001F\u007F]/,te=/^[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=Y(t);if(r===0||r>X)throw new Z("invalid-argument",`petRef must be 1..${X} characters`);if(ee.test(t))throw new Z("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=Y(t);if(r===0||r>J)throw new Z("invalid-argument",`userRef must be 1..${J} characters`);if(t.includes("@"))throw new Z("invalid-argument","userRef must not contain '@'");if(ee.test(t))throw new Z("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!te.test(e))throw new Z("invalid-argument","conversationId must be a UUID");return e}var re=[{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}],ne=/* @__PURE__ */Object.freeze(re.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ne.map(e=>e.wireCode));var le=/* @__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"}),ie=/* @__PURE__ */Object.freeze(ne.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:le[e.wireCode]}))),oe=new Map(ie.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ae=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(ie.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",...ae]){let t=oe.get(e+r);if(t)return t}}var se=/* @__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 se[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 ue=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return ue.has(e)}var ce=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ce.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var de=500,fe=8e3,he=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(de*2**r,fe);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var pe="This feature isn't available on your account right now.",ge="Something in that request was not right. Check the details and try again.",be=/* @__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:pe,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:ge,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:pe,runtimeDisposed:ge,unknown:"Something went wrong. Please try again."}),me="This session has ended. Please sign in again.",ye="linked_account_read_only";function ve(e,t,r){return e==="conflict"&&r===ye?pe:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?me:userFacingError(e)}function userFacingError(e){return be[e]}function ke(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var we=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ye,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:ve(e,t?.wireCode,n?ye:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&we.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&ke(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ke(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var Ce=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Se(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 Te(e)}var xe=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,_e=/[\s\u0000-\u001f\u007f\\]/,Re={"http:":"80","https:":"443"};function Te(e,t){let r=e.trim();let n=_e.test(r)?null:xe.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Re[f]?"":String(h),g=Re[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var Ie="application/pdf",ze=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Pe=e=>ze.includes(e);function Oe(e,t){return e===Ie||t!==void 0&&Pe(e)&&t.includes(e)}var Ee=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function je(e){return Oe(e,ze)?Ee[e]:Ee["application/pdf"]}var Fe="file",Ae="multipart upload failed";function De(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Fe,e.file)}catch{return Promise.reject(new Error(Ae))}return e.fetch!==void 0?Be(e.fetch,e.url,t,e.signal):Le(e.url,t,e.signal)}function Me(e){return e>=200&&e<300}function Le(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ae));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ae))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Me(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function Be(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var He="records upload: the file handle has no uri",Ue="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
5
5
|
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(He));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Ue));return l?.aborted===true?o():De({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:je(r.mimeType),type:Ne(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function Ne(e){return Oe(e,ze)?e:"application/pdf"}var $e=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var We=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<he},maxAttempts(){return he}});var Ve=/* @__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 Ge(`optional peer '${e}' is not installed: ${Ke(t)}`)}let l=qe(n);return l==null?Ge(`optional peer '${e}' resolved to no module`):r&&!r(l)?Ge(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function qe(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function Ge(e){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({available:false,module:null,reason:e})}function Ke(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__ */
|
|
@@ -11,15 +11,15 @@ 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 Ye="/widget/v1/anon-identity",Qe="x-everfur-anon-token",
|
|
15
|
-
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ft(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:dt(t)}function ht(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=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&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function pt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ht()}var gt=`\n\n`,bt=1048576,mt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),yt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=pt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(gt,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+gt.length),o=0;let r=vt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>bt){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=vt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function vt(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 l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=mt.safeParse(l);return i.success?kt(i.data,r,t):null}function kt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:wt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:wt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:dt(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:wt(e.conversation_id)??"",messageId:wt(e.message_id),title:wt(e.title),followUpQuestions:_t(e.follow_up_questions),citations:Tt(e.citations),citationStatus:wt(e.citation_status),urgencyLevel:St(e.urgency_level),urgencyReason:wt(e.urgency_reason),urgencyProvided:xt(e),resultId:wt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(wt(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=wt(e.delta)??wt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(wt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:wt(e.result_id),analysisType:wt(e.analysis_type),modelVersion:wt(e.model_version),confidence:Ct(e.confidence),detections:Tt(e.detections),interpretation:wt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function wt(e){return typeof e=="string"?e:null}function Ct(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function St(e){return typeof e=="string"&&yt.includes(e)?e:null}function xt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||St(t)!==null}function _t(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e){return Array.isArray(e)?e.filter(Rt):[]}function It(e,t,r){return{...e,surface:t,requestId:r||null}}var zt=64,Pt=/^[A-Za-z0-9._+() -]+$/;function Ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>zt?null:Pt.test(t)?t:null}var Et="1.6.
|
|
14
|
+
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var Ye="/widget/v1/anon-identity",Qe="x-everfur-anon-token",Ze="anonTokenInvalid";function Je(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 l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:Ye,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:Je(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function Xe(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function et(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 l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new Z("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:tt(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new Z("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function tt(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[Qe]=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:{...rt(e.headers),...authHeaders(t)}}}function rt(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===Qe||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await Xe(t),n=await t.transport.request(withAuthHeaders(e,nt(t,r)));if(n.ok||it(n.error.raw)!==Ze||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,nt(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(et(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 l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(et(e,{wireCode:it(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(lt(i.error))):i}function nt(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function lt(e){let t=e.raw,r=it(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 it(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 ot="DAILY_QUOTA_EXCEEDED",at=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function st(e,t){if(!at.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)?ot:e}var ut="free_cap_reached";function ct(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function dt(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!==ut&&n.code!==ut)return null;let l=ct(n.limit),i=ct(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
|
|
15
|
+
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ft(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:dt(t)}function ht(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=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&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function pt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ht()}var gt=`\n\n`,bt=1048576,mt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),yt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=pt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(gt,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+gt.length),o=0;let r=vt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>bt){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=vt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function vt(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 l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=mt.safeParse(l);return i.success?kt(i.data,r,t):null}function kt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:wt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:wt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:dt(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:wt(e.conversation_id)??"",messageId:wt(e.message_id),title:wt(e.title),followUpQuestions:_t(e.follow_up_questions),citations:Tt(e.citations),citationStatus:wt(e.citation_status),urgencyLevel:St(e.urgency_level),urgencyReason:wt(e.urgency_reason),urgencyProvided:xt(e),resultId:wt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(wt(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=wt(e.delta)??wt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(wt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:wt(e.result_id),analysisType:wt(e.analysis_type),modelVersion:wt(e.model_version),confidence:Ct(e.confidence),detections:Tt(e.detections),interpretation:wt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function wt(e){return typeof e=="string"?e:null}function Ct(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function St(e){return typeof e=="string"&&yt.includes(e)?e:null}function xt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||St(t)!==null}function _t(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e){return Array.isArray(e)?e.filter(Rt):[]}function It(e,t,r){return{...e,surface:t,requestId:r||null}}var zt=64,Pt=/^[A-Za-z0-9._+() -]+$/;function Ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>zt?null:Pt.test(t)?t:null}var Et="1.6.1";var jt="react-native",Ft="2026-09-19",At="EVERFUR_API_BASE_URL";function Dt(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
17
|
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||Ft,o=Ot(e.appVersion);/* @__PURE__ */
|
|
18
18
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:Et,platform:t?.platform??jt,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:$t(At);return r?Ut(r):Dt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${At}. 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 Mt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Lt(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Bt(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Lt(t)}function Ht(e,t){return`${e}://${t}`}function Ut(e){let t=e.trim(),r=Ce.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Dt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=Mt(r[2]);if(l.length===0)return Dt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Bt(t,l)?`: ${Ht(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Nt(l)))return n==="http"?Dt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):Dt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
19
|
-
return Object.freeze({ok:true,value:o})}function Nt(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function $t(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Wt(e,t){if(e.status!==429&&e.status!==503)return t;let r=qt(e.headers.get(Vt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&Gt(n)?t:{...n??{},retry_after_seconds:r}}var Vt="retry-after";function qt(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 Gt(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var Kt=3e4,Yt="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=
|
|
19
|
+
return Object.freeze({ok:true,value:o})}function Nt(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function $t(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Wt(e,t){if(e.status!==429&&e.status!==503)return t;let r=qt(e.headers.get(Vt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&Gt(n)?t:{...n??{},retry_after_seconds:r}}var Vt="retry-after";function qt(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 Gt(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var Kt=3e4,Yt="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=Zt(),n=false,l=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let l=e.data??"";for(let e of l.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},i=()=>{a(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let l=nr(e.message);if(l!==null){let e={type:"error",code:ut,retryable:false,limit:l.limit,used:l.used,resets_at:l.resetsAt,emergency_guidance:l.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=tr(n),l=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:l})}\n\n`))}}a(),r.end()};e.addEventListener("message",l),e.addEventListener("done",i),e.addEventListener("error",o);function a(){if(!n){n=true,e.removeEventListener("message",l),e.removeEventListener("done",i),e.removeEventListener("error",o);try{e.close()}catch{}}}return Qt(r.source,a)}async function*Qt(e,t){try{yield*e}finally{t()}}function Zt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*l(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:l(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=lr(t.config.apiBaseUrl,e.path,e.query),l=ir(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),i=sr(Kt),o=ur(i.signal,e.signal),a;try{a=await r(n,or({...e,signal:o},l))}catch(e){return err(networkError(e))}finally{i.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>a.headers.get(e))}catch{}if(e.rawText&&a.ok)try{return ok(Number(a.headers.get("content-length"))>e.rawText?null:await a.text())}catch(e){return err(networkError(e))}let s=await cr(a);return a.ok?ok(s):err(errorFromResponse(a.status,Wt(a,s),requestIdOf(a)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>Jt(ar(t,r),e)}}async function*Jt(e,t){let r=lr(t.config.apiBaseUrl,e.path,e.query),n=ir(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Xt(e,n));yield*parseSse(eventSourceByteSource(l),()=>eventSourceRequestId(l));return}let l=t.fetchImpl??getGlobalFetch(),i;try{i=await l(r,or(e,n))}catch(e){yield rr("",true,gr(e));return}let o=requestIdOf(i);if(!i.ok){let e=await cr(i),t=fr(e)??tr(i.status),r=pr(e)||isAutoRetryable(fromWire(t));yield rr(t,r,hr(e),o,dt(e));return}if(i.body){yield*parseSse(fetchByteSource(i.body),o);return}yield*parseSse(fetchByteSource(null),o)}function Xt(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=fr(t),l=n?fromWire(n):fromHttpStatus(e),i=hr(t);return makeEverfurError(l,{httpStatus:e,...pr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...dr(t)?{reasonCode:dr(t)}:{},...er(t)!==null?{retryAfterSeconds:er(t)}:{},...i?{wireMessage:i}:{},...t!=null?{raw:t}:{}})}function er(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:gr(e)})}function requestIdOf(e){let t=e.headers.get(Yt);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(Yt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function tr(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 rr(e,t,r,n=null,l=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:l})}function nr(e){if(typeof e!="string"||e.length===0)return null;try{return dt(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new Z("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function lr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,l=`${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&&(l+=`?${e}`)}return l}function ir(e,t,r,n){let l={...buildBaseHeaders(e),accept:r};return n&&(l["content-type"]="application/json"),t&&Object.assign(l,t),l}function or(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 ar(e,t){return e.signal?e:{...e,signal:t}}function sr(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function ur(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 cr(e){try{return await e.json()}catch{return null}}function dr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function fr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?st(r,e):dt(e)!==null?ut:null}function hr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function pr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function gr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var br=3e4,mr=fe*2,yr="idempotency-key",vr=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),kr=/* @__PURE__ */Object.freeze({onEvent(){}}),wr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Cr(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??kr,r=e.timers??wr,n=e.rng??Math.random,l=e.sleep??((e,t)=>Lr(e,r,t)),i=e.maxAttempts??he,o=e.unaryTimeoutMs??br,a=e.newIdempotencyKey??xr(),s=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??i),h=c?.idempotent??vr.has(u.method),p=c?.idempotencyKey===void 0?null:Cr(c.idempotencyKey),g=h?p??a():null,b=Sr(u,g),m=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:m,...g?{idempotencyKey:g}:{},...e});s(i({phase:"attempt"}));let a=Dr(o,r),c=Mr(a.signal,u.signal),h;try{h=await authedSend({...b,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),a.cancel()}if(h.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=Rr(p,m,{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 s(i({phase:"settled",...v})),err(p);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,u.signal),u.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(p);m+=1}}async function c(t){return withAuthHeaders(t,await Ar(e.auth))}async function*d(t,r,n){s(
|
|
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 Sr(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==yr&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function xr(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var _r=10;function Rr(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Tr(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=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 i=()=>{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(_r,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let a=Ir(e,r.now);return a!==null?a>mr?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:a}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function Tr(e){let t=e.code==="unknown"?fromWire(jr(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Ir(e,t){let r=Pr(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=zr(e.raw);return n===null?null:Math.round(n*1e3)}function zr(e){for(let t of Or(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Pr(e){for(let t of Or(e)){let e=t.resets_at,r=Er(e);if(r!==null)return r}return null}function Or(e){if(!Fr(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Fr(n)&&t.push(n)}return t}function Er(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 jr(e){for(let t of Or(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Fr(e){return typeof e=="object"&&e!==null}async function Ar(e){if(e.mode==="anonymous"){let t=await
|
|
22
|
-
return Object.freeze({caseId:r,status:n,bodyLocation:Wr(t.body_location),lastResponse:l!==null&&Br.includes(l)?l:null,checkInDueAt:Wr(t.check_in_due_at),openedAt:Wr(t.opened_at),resolvedAt:Wr(t.resolved_at),resolutionText:Wr(t.resolution_text),checkinAskCount:Vr(t.checkin_ask_count),checkinAnswerCount:Vr(t.checkin_answer_count)})}function Gr(e){return{async list(t,r){let n=$r(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return Nr();let o=i.map(qr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):Nr()},async checkin(t,r,n,l){let i=$r(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!Hr.test(r))return Ur("case_id must be a UUID");if(!Br.includes(n))return Ur("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value:{},s=qr(a.case);return s===null?Nr():ok(/* @__PURE__ */Object.freeze({case:s,ctaDeepLink:Wr(a.cta_deep_link)}))}}}function Kr(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 Yr(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"}:Kr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var Qr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var
|
|
21
|
+
return Object.freeze({send:u,authorize:c,stream:d})}function Sr(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==yr&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function xr(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var _r=10;function Rr(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Tr(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=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 i=()=>{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(_r,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let a=Ir(e,r.now);return a!==null?a>mr?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:a}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function Tr(e){let t=e.code==="unknown"?fromWire(jr(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Ir(e,t){let r=Pr(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=zr(e.raw);return n===null?null:Math.round(n*1e3)}function zr(e){for(let t of Or(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Pr(e){for(let t of Or(e)){let e=t.resets_at,r=Er(e);if(r!==null)return r}return null}function Or(e){if(!Fr(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Fr(n)&&t.push(n)}return t}function Er(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 jr(e){for(let t of Or(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Fr(e){return typeof e=="object"&&e!==null}async function Ar(e){if(e.mode==="anonymous"){let t=await Xe(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 Dr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function Mr(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 l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function Lr(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",i),n()},e),i=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",i,{once:true})})}var Br=/* @__PURE__ */Object.freeze(["better","same","worse"]),Hr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ur(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Nr(){return err(makeEverfurError("internalError",{retryable:false}))}function $r(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):K(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var Wr=e=>typeof e=="string"?e:null,Vr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function qr(e){if(typeof e!="object"||e===null)return null;let t=e,r=Wr(t.case_id),n=Wr(t.status);if(r===null||n===null)return null;let l=Wr(t.last_response);/* @__PURE__ */
|
|
22
|
+
return Object.freeze({caseId:r,status:n,bodyLocation:Wr(t.body_location),lastResponse:l!==null&&Br.includes(l)?l:null,checkInDueAt:Wr(t.check_in_due_at),openedAt:Wr(t.opened_at),resolvedAt:Wr(t.resolved_at),resolutionText:Wr(t.resolution_text),checkinAskCount:Vr(t.checkin_ask_count),checkinAnswerCount:Vr(t.checkin_answer_count)})}function Gr(e){return{async list(t,r){let n=$r(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return Nr();let o=i.map(qr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):Nr()},async checkin(t,r,n,l){let i=$r(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!Hr.test(r))return Ur("case_id must be a UUID");if(!Br.includes(n))return Ur("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value:{},s=qr(a.case);return s===null?Nr():ok(/* @__PURE__ */Object.freeze({case:s,ctaDeepLink:Wr(a.cta_deep_link)}))}}}function Kr(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 Yr(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"}:Kr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var Qr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var Zr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Jr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let l={handle:void 0},i=()=>{r.clearTimeout(l.handle),t.removeEventListener("abort",i),n()};l.handle=r.setTimeout(i,e),t.addEventListener("abort",i,{once:true})})}function Xr(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 en=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?Xr(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 tn(e,t,r){/* @__PURE__ */
|
|
23
23
|
return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function rn(e,t,r){/* @__PURE__ */
|
|
24
24
|
return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function nn(e){/* @__PURE__ */
|
|
25
25
|
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function ln(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 on(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 an(e){/* @__PURE__ */
|
|
@@ -27,361 +27,361 @@ return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...
|
|
|
27
27
|
return Object.freeze(r)}function hn(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 pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gn(e){return typeof e=="string"?e:null}function bn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(pn(r)){let e=gn(r.text)??gn(r.prompt)??gn(r.title);e!==null&&t.push(e)}return t}function mn(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function yn(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function vn(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function kn(e){let t=e,r=vn(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let l=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof l=="function"){let t=l.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var wn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Cn(e,t,r,n){let l=kn(e);if(l===null){yield xn();return}let i=_n(t.overallMs,n),o=_n(t.idleMs,n),a=Rn(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),a.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield xn();return}if(n.tag==="idle"||n.tag==="overall"){yield Sn();return}let s=n.value;if(s.done||(o.reset(t.idleMs),yield s.value,s.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function Sn(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function xn(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function _n(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function Rn(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var Tn="checkin",In=/^\d{4}-\d{2}-\d{2}$/,zn="watching";function Pn(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 On(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,a=jn(o),s=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.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:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...s===null?{}:{checkin:s}});/* @__PURE__ */
|
|
28
28
|
return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==zn}function En(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 jn(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==Tn||n===void 0||l===void 0||!Hr.test(n)||!In.test(l)?null:{caseId:n,dueDay:l}}function Fn(e){return jn(e)?.caseId??null}function An(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||K(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 Dn(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 Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ln(e){return e==null||typeof e=="string"&&e.length>0&&!K(e)}function Bn(){return err(makeEverfurError("internalError",{retryable:false}))}function Hn(e){let t=Mn(e);if(!t||!Array.isArray(t.conversations)||!Ln(t.next_cursor))return Bn();let r=[];for(let e of t.conversations){let t=Mn(e);if(!t||typeof t.conversation_id!="string"||!Dn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Bn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Bn();let l=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,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Un(e){let t=Mn(e);if(!t||!Array.isArray(t.messages)||!Ln(t.next_cursor))return Bn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=Mn(e);if(!t||typeof t.message_id!="string"||!Dn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Bn();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(Nn(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?Fn(l):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:Wn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Vn(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Nn(e,t,r,n){let l=Mn(e.sender),i=$n(l?.display_name)??$n(e.sender_display_name),o=$n(l?.specialty);/* @__PURE__ */
|
|
29
29
|
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function $n(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!K(t)?t:null}function Wn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Vn(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=Mn(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 qn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Gn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Kn=4e3;var Yn=4e3;function Qn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:sn("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:sn("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Jn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:sn("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Yn?{reason:"too_long",error:sn("validationFailed",false,`message is ${r} characters; the server accepts at most ${Yn}`)}:null}function Xn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Zn(e){yield e}async function*el(){}var tl=6e4,rl=18e4,nl=24,ll=512,il=false;function createChatController(e){return new ul(e)}function ol(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 al(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function sl(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 ul=class extends en{constructor(e){super(an({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=Gr(this.funnel),this.telemetry=e.telemetry??$e,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??We,this.timers=e.timers??wn,this.rng=e.rng??Math.random,this.newId=e.newId??mn(),this.makeIdempotencyKey=e.makeIdempotencyKey??yn(),this.budget={idleMs:e.budget?.idleMs??tl,overallMs:e.budget?.overallMs??rl}}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=sn(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Zn(cn(e))}let l=Jn(e)??Qn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Zn(cn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Zn(cn(sn("accessDenied",false)));let r=Jn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Zn(cn(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):el()}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,tn(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?nn(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(hn(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=An(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(sn("accessDenied",false));if(!l.ok)return l;let i=Hn(l.value);if(i.ok){for(let e of i.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=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.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 i}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=On(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"),al(n.error)?n.error:null;if(n.error.category==="notFound"&&sl(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 l=Pn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.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)}ol(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(sn("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 l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(sn("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(sn("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(sn("accessDenied",false));if(typeof e!="string"||e.trim().length===0||K(e))return err(sn("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Gn.includes(t))return err(sn("validationFailed",false,`feedback_type must be one of ${Gn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Kn)return err(sn("validationFailed",false,`notes is over ${Kn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(sn("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(sn("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(sn("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Dn(e))return err(sn("validationFailed",false));let r=An(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(sn("accessDenied",false)):l.ok?Un(l.value):l}async resumeConversation(e){if(this.disposed)return err(sn("accessDenied",false));if(!Dn(e))return err(sn("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(sn("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===zn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||En({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
-
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?zn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(sn("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}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;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 i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return err(i.error);let o=qn(this.snapshot.messages,i.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&&al(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(sn("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(sn("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...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 cn(t.error))}async primeConversation(e){if(this.disposed)return err(sn("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(sn("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(sn("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}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 l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(sn("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let r=e?.petRef??null;if(r!==null&&K(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)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):l.ok?ok(fn(l.value)):err(l.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,l=Zr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}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,tn(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,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.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,cn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=sn("internalError",!0);yield*this.emitTerminal(e,t,cn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Zr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,cn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Qe]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Cn(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=sn("streamIncomplete",!0);yield*this.emitTerminal(e,t,cn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!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===Je||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,un(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!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(il&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,un(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?nn(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,rn(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=ll){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)},nl)}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?ln(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?on(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?nn(e):e),on(rn(r,"",this.stamp()),e)]}let l=hn([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):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,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=Xn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?nn(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?sn("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,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):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&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,dl(e)?(a=true,u=e):(fl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){dl(e)?(a=true,u===null&&(u=e)):fl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
30
|
+
return Object.freeze(e.flatMap(e=>{let r=Mn(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 qn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Gn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Kn=4e3;var Yn=4e3;function Qn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:sn("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:sn("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Zn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:sn("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Yn?{reason:"too_long",error:sn("validationFailed",false,`message is ${r} characters; the server accepts at most ${Yn}`)}:null}function Jn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Xn(e){yield e}async function*el(){}var tl=6e4,rl=18e4,nl=24,ll=512,il=false;function createChatController(e){return new ul(e)}function ol(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 al(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function sl(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 ul=class extends en{constructor(e){super(an({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=Gr(this.funnel),this.telemetry=e.telemetry??$e,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??We,this.timers=e.timers??wn,this.rng=e.rng??Math.random,this.newId=e.newId??mn(),this.makeIdempotencyKey=e.makeIdempotencyKey??yn(),this.budget={idleMs:e.budget?.idleMs??tl,overallMs:e.budget?.overallMs??rl}}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=sn(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Xn(cn(e))}let l=Zn(e)??Qn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Xn(cn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Xn(cn(sn("accessDenied",false)));let r=Zn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Xn(cn(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):el()}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,tn(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?nn(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(hn(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=An(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(sn("accessDenied",false));if(!l.ok)return l;let i=Hn(l.value);if(i.ok){for(let e of i.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=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.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 i}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=On(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"),al(n.error)?n.error:null;if(n.error.category==="notFound"&&sl(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 l=Pn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.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)}ol(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(sn("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 l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(sn("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(sn("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(sn("accessDenied",false));if(typeof e!="string"||e.trim().length===0||K(e))return err(sn("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Gn.includes(t))return err(sn("validationFailed",false,`feedback_type must be one of ${Gn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Kn)return err(sn("validationFailed",false,`notes is over ${Kn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(sn("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(sn("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(sn("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Dn(e))return err(sn("validationFailed",false));let r=An(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(sn("accessDenied",false)):l.ok?Un(l.value):l}async resumeConversation(e){if(this.disposed)return err(sn("accessDenied",false));if(!Dn(e))return err(sn("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(sn("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===zn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||En({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
+
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?zn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(sn("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}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;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 i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return err(i.error);let o=qn(this.snapshot.messages,i.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&&al(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(sn("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(sn("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...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 cn(t.error))}async primeConversation(e){if(this.disposed)return err(sn("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(sn("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(sn("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}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 l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(sn("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let r=e?.petRef??null;if(r!==null&&K(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)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):l.ok?ok(fn(l.value)):err(l.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,l=Xr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}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,tn(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,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.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,cn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=sn("internalError",!0);yield*this.emitTerminal(e,t,cn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Xr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,cn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Qe]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Cn(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=sn("streamIncomplete",!0);yield*this.emitTerminal(e,t,cn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!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===Ze||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,un(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!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(il&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,un(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?nn(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,rn(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=ll){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)},nl)}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?ln(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?on(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?nn(e):e),on(rn(r,"",this.stamp()),e)]}let l=hn([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):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,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=Jn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?nn(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?sn("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,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):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&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,dl(e)?(a=true,u=e):(fl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){dl(e)?(a=true,u===null&&(u=e)):fl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
32
|
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?cl:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:a,sawConversationInitFailure:s})})}var cl="Chat is ready. Your first message will start the conversation.";function dl(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function fl(e){return e.httpStatus===403||e.code==="accessDenied"}var hl=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function pl(e){return e!==hl}var gl=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var bl=10*1024*1024,ml=5,yl=120,vl="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&gl.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<=yl)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,yl);let n=t.slice(r);return n.length>=yl?t.slice(0,yl):`${t.slice(0,r).slice(0,yl-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 kl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),wl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function Cl(e,t,r,n){/* @__PURE__ */
|
|
33
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 wl(Cl("unsupported_type",false,t));let n=attachmentSize(e);return n===null?wl(Cl("unknown",false,t)):n>bl?wl(Cl("too_large",false,t,{sizeBytes:n})):kl(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function Sl(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,l=r(t.upload_id),i=r(t.upload_url),o=r(t.s3_key);if(l===null||i===null||o===null)return null;let a={},s=t.upload_fields;if(typeof s=="object"&&s!==null)for(let[e,t]of Object.entries(s))typeof t=="string"&&(a[e]=t);/* @__PURE__ */
|
|
34
|
-
return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??bl,s3_key:o,purpose:r(t.purpose)})}function xl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Cl("quota_exceeded",false,t,{cause:e});case"rateLimited":return Cl("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Cl("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Cl("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Cl("network",true,t,{cause:e});default:return r===429?Cl("rate_limited",true,t,{cause:e}):r===503?Cl("network",true,t,{cause:e}):r===void 0?Cl("network",true,t,{cause:e}):Cl("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:vl,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return wl(xl(n.error,t.filename));let l=Sl(n.value);return l===null?wl(Cl("server",false,t.filename)):kl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return wl(Cl("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),kl(void 0)}catch{return l()?wl(Cl("cancelled",true,r.filename)):wl(Cl("server",true,r.filename))}}var _l=2,Rl=3,Tl=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Il=0;function zl(){return Il+=1,`attachment-${Il}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??_l),r=Math.max(1,e.maxAttempts??Rl),n=e.backoffMs??Tl,l=Math.max(1,e.maxPerMessage??ml),i=e.timers??
|
|
34
|
+
return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??bl,s3_key:o,purpose:r(t.purpose)})}function xl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Cl("quota_exceeded",false,t,{cause:e});case"rateLimited":return Cl("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Cl("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Cl("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Cl("network",true,t,{cause:e});default:return r===429?Cl("rate_limited",true,t,{cause:e}):r===503?Cl("network",true,t,{cause:e}):r===void 0?Cl("network",true,t,{cause:e}):Cl("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:vl,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return wl(xl(n.error,t.filename));let l=Sl(n.value);return l===null?wl(Cl("server",false,t.filename)):kl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return wl(Cl("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),kl(void 0)}catch{return l()?wl(Cl("cancelled",true,r.filename)):wl(Cl("server",true,r.filename))}}var _l=2,Rl=3,Tl=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Il=0;function zl(){return Il+=1,`attachment-${Il}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??_l),r=Math.max(1,e.maxAttempts??Rl),n=e.backoffMs??Tl,l=Math.max(1,e.maxPerMessage??ml),i=e.timers??Zr,o=e.newId??zl,a=pl(e.transport),s=/* @__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=s.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},b=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},m=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=s.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),m()}))}},y=async t=>{let{attachment:l}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;b(t,{status:"uploading",error:null,progress:0});let a=await initiateAttachmentUpload(e.funnel,l,{signal:o});if(p||o.aborted)return;let s;if(!a.ok)s=wl(a.error);else{let r=await uploadAttachmentBytes(e.transport,a.value,l,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&b(t,{progress:Pl(e)})}});if(p||o.aborted)return;s=r.ok?kl(a.value.s3_key):wl(r.error)}if(s.ok){b(t,{status:"uploaded",s3Key:s.value,error:null,progress:1});return}let u=s.error,c=u.retryable&&t.attempts<r;if(b(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await Jr(d,o,i)}},v=e=>{c.push(e.state.id),m()},k={available:a,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>=l)return wl(Cl("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 s.set(r,n),u.push(r),g(),v(n),kl(n.state)},retry(e){let t=s.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,b(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=s.get(e);if(t===void 0)return;t.controller.abort(),s.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])k.remove(e)},dispose(){p=true;for(let e of s.values())e.controller.abort();s.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return k}function Pl(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Ol=/* @__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(Ol,t)?Ol[t]:null}var El=50,jl=128,Fl=120,Al=120,Dl=2e3,Ml=120,Ll=80,Bl=/* @__PURE__ */new Set(["male","female","unknown"]),Hl=/* @__PURE__ */new Set(["day","month","year"]),Ul=/* @__PURE__ */new Set(["low","medium","high","athletic"]),Nl=/* @__PURE__ */new Set(["indoor","outdoor","both"]),$l=/* @__PURE__ */new Set(["mild","moderate","severe"]),Wl=/^(\d{4})-(\d{2})-(\d{2})$/,Vl=[["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"]],ql=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...Vl,...ql].map(([e])=>e));function Gl(e){let t=Wl.exec(e);if(t===null)return false;let[r,n,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(r,n-1,l));return i.getUTCFullYear()===r&&i.getUTCMonth()===n-1&&i.getUTCDate()===l}var Kl=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,Yl=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,Ql=(e,t)=>typeof t=="string"&&Gl(t)?null:`${e} must be a real date written YYYY-MM-DD`,Zl=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(K(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=Y(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},Jl={sex:Kl(Bl),spayedNeutered:Yl,birthDate:Ql,birthDatePrecision:Kl(Hl),activityLevel:Kl(Ul),indoorOutdoor:Kl(Nl),foodBrand:Zl(Ml),foodType:Zl(Ml),microchipId:Zl(Ll)},Xl=["ref","ref",false,Zl(jl,{required:true,trimmed:true})],ei=["notes","notes",false,Zl(Dl,{trimmed:true})],ti=[Xl,["name","name",true,Zl(Fl,{required:true,trimmed:true})],["dose","dose",false,Zl(Al,{trimmed:true})],["frequency","frequency",false,Zl(Al,{trimmed:true})],["startDate","start_date",false,Ql],["endDate","end_date",false,Ql],ei],ri={allergies:[Xl,["allergen","allergen",true,Zl(Fl,{required:true,trimmed:true})],["severity","severity",false,Kl($l)],ei],medications:ti,supplements:ti,conditions:[Xl,["conditionName","condition_name",true,Zl(Fl,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ql],ei]};function ni(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let l=r,i={};for(let[t,r,o,a]of ri[e]){let e=l[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(i[r]=null);continue}let s=a(`${n}.${t}`,e);if(s!==null)return{error:s};i[r]=e}let o=i.start_date,a=i.end_date;return typeof o=="string"&&typeof a=="string"&&a<o?{error:`${n}.endDate must not be before startDate`}:{item:i}}function li(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>El)return{error:`${e} has ${t.length} items; the server accepts at most ${El}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=ni(e,l,t[l]);if("error"in i)return i;let o=i.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(i.item)}return{items:r}}function ii(e,t){let r=e,n={};for(let[e,t]of Vl){let l=r[e];if(l!==void 0){if(l!==null){let t=Jl[e](e,l);if(t!==null)return{error:t}}n[t]=l}}let l=r.birthDate!==void 0,i=r.birthDatePrecision!==void 0;if(l!==i||l&&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 ql){let l=r[e];if(l===void 0)continue;let i=li(e,l);if("error"in i)return i;n[t]=i.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 oi=e=>typeof e=="string"?e:null,ai=(e,t)=>typeof t=="string"&&e.has(t)?t:null,si=e=>typeof e=="boolean"?e:null;function ui(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 ci(e){let t=oi(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),name:t,dose:oi(e.dose),frequency:oi(e.frequency),startDate:oi(e.start_date),endDate:oi(e.end_date),notes:oi(e.notes)})}function di(e){let t=e.profile_version;/* @__PURE__ */
|
|
35
35
|
return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ai(Bl,e.sex),spayedNeutered:si(e.spayed_neutered),birthDate:oi(e.birth_date),birthDatePrecision:ai(Hl,e.birth_date_precision),activityLevel:ai(Ul,e.activity_level),indoorOutdoor:ai(Nl,e.indoor_outdoor),foodBrand:oi(e.food_brand),foodType:oi(e.food_type),microchipId:oi(e.microchip_id),allergies:ui(e.allergies,e=>{let t=oi(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),allergen:t,severity:ai($l,e.severity),notes:oi(e.notes)})}),medications:ui(e.medications,ci),supplements:ui(e.supplements,ci),conditions:ui(e.conditions,e=>{let t=oi(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),conditionName:t,diagnosedDate:oi(e.diagnosed_date),notes:oi(e.notes)})})})}var fi=100,hi=50,pi=100,gi=50,bi=500,mi=128,yi=6e4;function vi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function ki(e,t,r){if(typeof t!="string")return vi(`${e} must be a string`);let n=Y(t);return n<=r?null:vi(`${e} is ${n} characters; the server accepts at most ${r}`)}function wi(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:vi(`${e} must be a finite number between 0 and ${r}`)}function Ci(e,t){if(typeof e!="string")return vi("pet_ref must be a string");if(e.trim().length===0)return vi("pet_ref must not be blank");if(K(e))return vi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return vi("profile must be an object");let r=[ki("pet_ref",e,mi)];return t?.name!==void 0&&r.push(ki("name",t.name,fi)),t?.species!==void 0&&r.push(ki("species",t.species,hi)),t?.breed!==void 0&&r.push(ki("breed",t.breed,pi)),t?.ageYears!==void 0&&r.push(wi("age_years",t.ageYears,gi)),t?.weightKg!==void 0&&r.push(wi("weight_kg",t.weightKg,bi)),r.find(e=>e!==null)??null}function Si(e,t){let r=ii(e,t);return"error"in r?{error:vi(r.error)}:r}function xi(e){if(typeof e!="object"||e===null)return{error:vi("patch must be an object")};let t=e,r=[["name","name",e=>ki("name",e,fi)],["species","species",e=>ki("species",e,hi)],["breed","breed",e=>ki("breed",e,pi)],["ageYears","age_years",e=>wi("age_years",e,gi)],["weightKg","weight_kg",e=>wi("weight_kg",e,bi)]],n={};for(let[e,l,i]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=i(r);if(e!==null)return{error:e}}n[l]=r}}let l=Si(t,t.species);return"error"in l?l:(Object.assign(n,l.body),Object.keys(n).length===0?{error:vi("patch must change at least one field")}:{body:n})}function _i(e){if(e==null)return{body:{}};let t=Si(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 Ri=e=>typeof e=="string"?e:null,Ti=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ii(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
|
|
36
36
|
return Object.freeze({petRef:Ri(r.pet_ref)??t,name:Ri(r.name),species:Ri(r.species),breed:Ri(r.breed),ageYears:Ti(r.age_years),weightKg:Ti(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ri(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:Ri(t.pet_id),petRef:r,name:Ri(t.name),species:Ri(t.species),breed:Ri(t.breed),ageYears:Ti(t.age_years),weightKg:Ti(t.weight_kg),updatedAt:Ri(t.updated_at)})}function zi(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...di(e)})}function Pi(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
|
|
37
37
|
return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Oi(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:yi}))}function Oi(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>Ci(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(Pi(n.value)):err(n.error)},async registerPet(t,r,n){let l=Ci(t,r);if(l!==null)return err(l);let i=_i(r);if("error"in i)return err(i.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:i.body},a=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return a.ok?ok(Ii(a.value,t)):err(a.error)},async updatePet(t,l,i){let o=n(t);if(typeof o!="string")return err(o);let a=xi(l);if("error"in a)return err(a.error);let s=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:a.body},i?.signal));return s.ok?ok(Ii(s.value,t)):err(s.error)},async getPetProfile(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${i}/profile`},l?.signal));if(!o.ok)return err(o.error);let a=zi(o.value);return a===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(a)},async deletePet(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.deletePet",r({method:"DELETE",path:i},l?.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 Ei=/* @__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 Ei[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],l=/* @__PURE__ */new Set;for(let e of Object.keys(Ei))for(let t of Ei[e])l.has(t)||(l.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),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!l.has(e)))return Ai({name:e,enabled:false,isPending:true,limits:{}});let i=ji(n,l);return n.filter(e=>l.get(e)?.granted!==true).length===0?Ai({name:e,enabled:true,isPending:false,limits:i}):Ai({name:e,enabled:false,isPending:false,limits:i,disabled:Fi(n,l)})}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 Fi(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 Ai(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 Di(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Mi)}catch(e){Mi(e)}}function Mi(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var Li=/* @__PURE__ */new WeakMap,Bi=/* @__PURE__ */new Map;function Hi(e,t){Li.set(e,t)}function Ui(e,t,r,n){let l=Li.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${$i(n)}`}function Ni(e,t){if(e===null)return t();let r=Bi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Bi.get(e)===n&&Bi.delete(e)});return Bi.set(e,n),n}function $i(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map($i).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)}:${$i(t)}`).join(",")}}`}var Wi=/* @__PURE__ */new WeakMap;function Vi(e,t){let r=Wi.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Wi.set(e,r)),r.add(t),()=>{r?.delete(t)}}function qi(e){let t=Wi.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Gi=/* @__PURE__ */new Map;function Ki(e,t){return()=>{let r=Gi.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Gi.get(e)===l&&Gi.delete(e)});return Gi.set(e,l),l}}function parseColor(e){let t=Yi(e);return t===null?null:ro(t)}function Yi(e){if(typeof e=="number")return Xi(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Qi(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Qi(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ji(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=Qi(t);if(e!==null)return e}return/^\d+$/.test(t)?Xi(Number.parseInt(t,10)):null}function Qi(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:eo(t[0]),g:eo(t[1]),b:eo(t[2]),a:1};if(t.length===6)return{r:Zi(t,0),g:Zi(t,2),b:Zi(t,4),a:1};if(t.length===8){let e=Zi(t,0);return{r:Zi(t,2),g:Zi(t,4),b:Zi(t,6),a:e/255}}return null}function Ji(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 l=to(Number(n[0])),i=to(Number(n[1])),o=to(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function Xi(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 Zi(e,t){return Number.parseInt(e.slice(t,t+2),16)}function eo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function to(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function ro(e){if(e.a>=1)return no(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function no(e,t,r){return`#${lo(e)}${lo(t)}${lo(r)}`.toUpperCase()}function lo(e){return e.toString(16).padStart(2,"0")}var io="#111111",oo="#FFFFFF",ao="#000000";function readableOn(e){let t=Yi(e);if(t===null)return oo;let r=co(t),n=co({r:17,g:17,b:17}),l=co({r:255,g:255,b:255});return ho(r,l)>=ho(r,n)?oo:io}function so(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(oo,e)>=contrastRatio(ao,e)?oo:ao}function uo(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(oo)>=t(ao)?oo:ao}function co(e){let t=fo(e.r/255),r=fo(e.g/255),n=fo(e.b/255);return.2126*t+.7152*r+.0722*n}function fo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function ho(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=Yi(e),n=Yi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:po(r,l);return ho(co(i),co(l))}function po(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 go(e,t){let r=Yi(e),n=Yi(t);if(r===null||n===null)return null;let l=r.a>=1?r:po(r,{...n});return no(l.r,l.g,l.b)}function bo(e,t){let r=Yi(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 mo=.05;function yo(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(Yi(e)===null)return r;if(i(e))return e;let o=go(e,l),a=o===null?null:Yi(o),s=Yi(r);if(a===null||s===null)return r;for(let e=1;e<1/mo;e+=1){let t=e*mo,r=(e,r)=>Math.round(e+(r-e)*t),n=no(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function vo(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function ko(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:wo(c+a),g:wo(d+a),b:wo(f+a)}}function wo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var Co=/* @__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"]),So=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),xo=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return xo[e]??So}var _o=4.5,Ro=/* @__PURE__ */Object.freeze({});function To(e){return Co.includes(e)}function Io(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,l]of Object.entries(e)){if(!To(n)||l===null||typeof l!="object")continue;let e=Oo(l);if(e===null)continue;let i=zo(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function zo(e,t){let r=xo[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 Po(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Oo(e){let t={},r=parseColor(Po(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(Po(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=Io(Po(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(Po(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Ro:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Eo(e){let t=Yi(e);return t!==null&&t.a>=1}var jo=3,Fo=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Ao(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Do(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>go(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=jo))return null;let l=[...t,...n,...r];return yo(n[0],l,uo(l),jo)}function Mo(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>go(e,t)??t)}function Lo(e,t){let r=uo(e);return e.every(e=>contrastRatio(r,e)>=t)}function Bo(e,t){let r=t[0];return r===void 0?null:go(e,r)}function Ho(e){let t=so(e[0],_o);return e.every(e=>contrastRatio(t,e)>=_o)?t:uo(e)}function Uo(e,t,r,n,l){return Fo.has(e)?false:l?true:r!==void 0&&Ao(t,r)?false:!(n!==void 0&&r!==void 0&&Eo(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of Co){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=Mo(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!Lo(u,_o)){let e=Bo(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Eo(h)&&Do(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<_o))&&(c.textColor=Ho(u),d=true);else if(e!==void 0){let t=yo(e,u,uo(u),_o);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&Uo(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=yo(o.borderColor,e,uo(e),jo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Do(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var No=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),$o=/* @__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 Wo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Wo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var Vo=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),qo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),Go={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Ko={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Yo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Qo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Jo={regular:"400",medium:"500",bold:"700"},Xo={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},Zo=0,ea="System",ta="monospace",ra=["content","heading","control","compact","badge"];function na(e){let t={};for(let r of ra)t[r]=e;return t}var la=[];function ia(){return{family:ea,mono:ta,fontUrl:null,families:{regular:ea,medium:ea,bold:ea,mono:ta,monoMedium:ta,monoBold:ta},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Yo,tierSizes:na(Yo),lineHeight:Qo,weight:Jo,letterSpacing:Xo,scale:1,maxScale:Zo,scaleCaps:Vo,headingFamily:null,headingWeight:null,fontSources:la,roles:$o,typeScale:1}}var oa={},aa=/* @__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 sa={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(aa.standard),emphasized:cssCubicBezier(aa.emphasized),exit:cssCubicBezier(aa.exit)},reducedMotion:false},ua={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)"},ca=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ua,space:Go,radius:Ko,type:ia(),motion:sa,slots:oa}),da={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)"},fa=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:da,space:Go,radius:Ko,type:ia(),motion:sa,slots:oa});function ha(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function pa(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function ga(e){return pa(e).every(t=>contrastRatio(e.brand,t)>=jo)}function ba(e){return[e.chatGround,e.surface,e.surfaceCream]}function ma(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...ya(e,t)]}function ya(e,t){return[go(t,e.surface)??e.surface,go(t,e.surfaceCream)??e.surfaceCream]}function va(e){return[e.composerFill,e.chatGround]}var ka=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function wa(e,t){let r=new Set(ha(t));return ha(e).every(e=>r.has(e))}function Ca(e){let t=e.color,r=(e.brightness==="dark"?fa:ca).color,n=(e.brightness==="dark"?ca:fa).color,l=ha(t),i=uo(l)!==uo(ha(r)),o=wa(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&ka.has(e)?t:yo(u&&i?n:t,l,uo(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=so(f,_o),p=c("danger",t.danger,[...l,...ya(t,t.badgeBgCritical)],_o),g={...t,onPrimary:h,onAccent:so(t.accent,_o),onDanger:contrastRatio(h,p)>=_o?h:so(p,_o),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,_o),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,ba(t),_o),text:{...t.text,primary:u("primary",l,_o),secondary:u("secondary",l,_o),muted:u("muted",l,_o),metaCool:u("metaCool",l,_o),timestamp:u("timestamp",l,_o),placeholder:u("placeholder",pa(t),jo)},danger:p,errorRed:c("errorRed",t.errorRed,ma(t,t.badgeBgCritical),_o),warningStrong:c("warningStrong",t.warningStrong,ma(t,t.badgeBgCaution),_o),composerBorder:c("composerBorder",t.composerBorder,va(t),jo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,pa(t),jo)},b={...g,...Pa(g,r,o)};return{...b,...Sa(t,b,r)}}function Sa(e,t,r){let n={},l=(e,t,r)=>yo(e,t,uo(t),r);if((!Ta(e.success,r.success)||!Ta(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,ma(t,e.badgeBgPositive),_o)),(!Ta(e.cautionAccent,r.cautionAccent)||!Ta(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,ma(t,e.badgeBgCaution),_o)),xa(e,r)){n.info=l(e.info,ma(t,e.badgeBgInfo),_o);let r=[t.surface,t.chatGround,...ya(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,jo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function xa(e,t){return!Ta(e.info,t.info)||!Ta(e.badgeBgInfo,t.badgeBgInfo)}var _a=.24,Ra=.3;function Ta(e,t){return parseColor(e)===parseColor(t)}function Ia(e,t){return Ta(e.accent,t.accent)?Ta(e.brand,t.brand)?null:e.brand:e.accent}function za(e,t,r){let n=bo(e,r);return(n===null?null:go(n,t))??t}function Pa(e,t,r){let n=Ia(e,t),l=pa(e),i=uo(l),o=uo([e.surface])===oo,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?za(ca.color.highlight,e.surface,Ra):ca.color.highlight:s=za(n,e.surface,o?Ra:_a);let u=a?t.onHighlight:yo(e.text.primary,[s],uo([s]),_o),c=n===null?t.mark:yo(n,l,i,jo),d=ga(e)?e.brand:i,f=(e,t,n)=>r&&Ta(e,t)?n:yo(e,l,d,jo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=jo)?e.primary:yo(e.primary,h,uo(h),jo);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Oa=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Ea(e,t){let r=(e.brightness==="dark"?fa:ca).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!Oa(e,t);a(n.text.primary,r.text.primary)&&!Oa(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(Oa(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),Oa(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!Oa(l.controlEdge,n.brandBorder)&&!ga({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Oa(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!Oa(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!Oa(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!Oa(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!Oa(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(Oa(l.info,n.info)||o("info_color","information text",n.info,l.info),Oa(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of Co){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!Oa(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!Oa(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!Oa(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
|
|
40
|
-
return Object.freeze(i)}var ja=/* @__PURE__ */new Set;function Fa(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(ja.has(t))return;ja.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Aa="#23272C",Da=4.5,Ma=.6,La=.9,Ba=.02,Ha="#FFFFFF",Ua="#111111";function Na(e){return contrastRatio(e,Aa)>=Da&&Math.max(contrastRatio(e,Ha),contrastRatio(e,Ua))>=Da}function deriveDarkVariant(e){let t=Yi(e);if(t===null)return null;let{h:r,s:n,l:l}=vo(t.r,t.g,t.b),i=Math.min(Math.max(l,Ma),La);for(let e=0;;e+=1){let t=i+e*Ba;if(t>La)break;let l=ko({h:r,s:n,l:t}),o=no(l.r,l.g,l.b);if(Na(o))return o}let o=ko({h:r,s:n,l:La});return no(o.r,o.g,o.b)}var $a=7,Wa=.05,Va="#000000",qa="#FFFFFF";function Ga(e,t,r,n){let l=go(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=Yi(l),o=Yi(r);if(i===null||o===null)return r;for(let e=1;e<1/Wa;e+=1){let r=e*Wa,l=(e,t)=>Math.round(e+(t-e)*r),a=no(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function Ka(e,t){let r=ha(e),n=r[0],l=Ya(n);for(let e of r){let r=Ya(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function Ya(e){let t=Yi(e);return t===null?0:co(t)}function Qa(e,t){return go(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=uo(ha(t))===qa,n=r?qa:Va,l=Ka(t,r),i=e=>Ga(e,l,n,$a),o={...t,brandSoft:Qa(t.brandSoft,t.surface),brandSofter:Qa(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:Qa(t.badgeBgPositive,t.surface),badgeBgCaution:Qa(t.badgeBgCaution,t.surface),badgeBgCritical:Qa(t.badgeBgCritical,t.surface),badgeBgNeutral:Qa(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Qa(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Qa(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:Qa(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var Ja=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Xa=Ja.cream,Za=Ja.subtle,es=Ja.ring,ts=10;function rs(e,t,r){let n=Yi(e),l=Yi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return no(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function ns(e){if(e===null)return{};let t=uo([e]),r=rs(e,t,Xa),n=rs(e,t,Za),l=rs(e,t,es);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function ls(e){if(e===null)return{};let t=Yi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function is(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(ts,Math.round(t*n*10)/10);return l}function os(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function as(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var ss=/* @__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 us(e,t){let r=Yi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function cs(e,t){if(e===null)return{};let r=us(e,t?ss.success.dark:ss.success.light),n=us(e,t?ss.successCard.dark:ss.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function ds(e,t){if(e===null)return{};let r=us(e,t?ss.warning.dark:ss.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function fs(e,t){if(e===null)return{};let r=us(e,t?ss.info.dark:ss.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function hs(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function ps(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:ba(e),header:[e.surface,e.background,e.chatGround],banner:[go(e.badgeBgInfo,e.surface)??e.surface,go(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 gs(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 bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ms=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),ys=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),vs=/* @__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 ks(e){return typeof e=="string"&&ms.includes(e.trim().toLowerCase())}function ws(e,t){let r=e[t];return r??void 0}var Cs=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Cs)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Ss=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],xs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],_s=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Rs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Ts=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!bs(e))return null;let t=ks(e.theme)?ys[e.theme.trim().toLowerCase()]:{},r=bs(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=ws(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of Ss){let r=ws(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of xs){let r=ws(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of Rs){let r=ws(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of Ts){let r=parsePx(ws(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of _s){let r=ws(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(bs(u)){let e={};for(let t of Co){let r=u[t];bs(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var Is="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function zs(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var Ps=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?zs(__EVERFUR_BRAND_CDN_ORIGIN__):Is;var Os=/* @__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}),Es=/* @__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(Es),Fs="presentation",As="presentation.";function isPresentationLockName(e){if(e===Fs)return true;if(!e.startsWith(As))return false;let t=e.slice(As.length);return Object.values(Es).includes(t)}var Ds={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"]},Ms=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function Ls(e,t){if(t==null)return;let r=Ds[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:Ms.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=Es[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=Ls(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${As}${Es[e]}`;for(let e of t)if(e===Fs||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of js){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??Os[e]}/* @__PURE__ */
|
|
41
|
-
return Object.freeze(a)}var
|
|
42
|
-
return Object.freeze(o)}function
|
|
43
|
-
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function yu(e){return e==="hide_powered_by"||gu.includes(e)||isPresentationLockName(e)?true:e.startsWith(bu)&&Co.includes(e.slice(bu.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=ku(t),n=expandAppearance(Su(t,"appearance")),l=n===null?r:vu(ku(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function vu(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 ku(e){return{displayName:xu(Su(e,"display_name","displayName")),logoUrl:xu(Su(e,"logo_url","logoUrl")),primaryColor:parseColor(Su(e,"primary_color","primaryColor")),accentColor:parseColor(Su(e,"accent_color","accentColor")),brightness:Pu(Su(e,"brightness","color_scheme","colorScheme")),fontFamily:xu(Su(e,"font_family","fontFamily")),fontUrl:xu(Su(e,"font_url","fontUrl")),fonts:Ru(Su(e,"fonts")),fontUrls:Ru(Su(e,"font_urls","fontUrls")),placeholder:xu(Su(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Cu(Su(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Su(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Su(e,"accent_color_dark","accentColorDark")),surfaceStyle:zu(Su(e,"surface_style","surfaceStyle"),Tu),radiusScale:zu(Su(e,"radius_scale","radiusScale"),Iu),logoUrlDark:xu(Su(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Su(e,"slots")),accessibilityMaxFontScale:Fu(Su(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Mu(Su(e,"locked_fields","lockedFields")),presentation:parsePresentation(Su(e,"presentation")),schemaVersion:Au(Su(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Su(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Su(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Su(e,"text_color","textColor")),textColorDark:parseColor(Su(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Su(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Su(e,"danger_color_dark","dangerColorDark")),fontSizeBase:wu(Su(e,"font_size_base","fontSizeBase"),vs.fontSizeBase),borderRadius:wu(Su(e,"border_radius","borderRadius"),vs.borderRadius),spacingUnit:wu(Su(e,"spacing_unit","spacingUnit"),vs.spacingUnit),successColor:parseColor(Su(e,"success_color","successColor")),successColorDark:parseColor(Su(e,"success_color_dark","successColorDark")),warningColor:parseColor(Su(e,"warning_color","warningColor")),warningColorDark:parseColor(Su(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Su(e,"info_color","infoColor")),infoColorDark:parseColor(Su(e,"info_color_dark","infoColorDark")),headingFontFamily:xu(Su(e,"heading_font_family","headingFontFamily")),fontWeightBody:Vs(Su(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Vs(Su(e,"font_weight_heading","fontWeightHeading")),lineHeight:qs(Su(e,"line_height","lineHeight")),fontSources:Js(Su(e,"font_sources","fontSources")),assistantAvatarUrl:xu(Su(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:au(Su(e,"text_scale_caps","textScaleCaps")),typeScale:ou(Su(e,"type_scale","typeScale")),typeRoles:uu(Su(e,"type_roles","typeRoles"))}}function wu(e,t){let r=Ou(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Cu(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 Su(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 xu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var _u=["regular","medium","bold","mono","monoMedium","monoBold"];function Ru(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of _u){let n=xu(Su(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Tu=["white","cream","subtle"],Iu=["sharp","default","round"];function zu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Pu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Ou(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 Eu=1,ju=3.1;function Fu(e){let t=Ou(e);return t===null?null:t<=0?0:Math.min(ju,Math.max(Eu,t))}function Au(e){if(e==null)return null;let t=Ou(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Du(e){let t=e.trim();return t.startsWith(bu)?t:t.startsWith(As)?As+t.slice(As.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Mu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Du(r);yu(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 Lu=/* @__PURE__ */new RegExp(`^${Ps}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&Lu.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"?fa:ca:e,n=r.brightness==="dark"?fa:ca,l=r.brightness==="dark",i=l?t.primaryColorDark??$u(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??$u(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&qu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Yi(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?Gu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=ns(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??$u(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?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,...ls(y(t.dangerColor,t.dangerColorDark)),...cs(y(t.successColor,t.successColorDark),l),...ds(y(t.warningColor,t.warningColorDark),l),...fs(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Wu(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:os(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?as(t.borderRadius,n):Yu(t.radiusScale??null,r.radius,n),type:{...r.type,...Nu(r.type,t),size:is(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:hs(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:fu(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 Bu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Hu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Uu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function Nu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of _u){let a=Bu[e].map(e=>r[e]).find(e=>e!==void 0),s=Uu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Hu)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function $u(e){return e===null?null:deriveDarkVariant(e)}function Wu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Vu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function qu(e,t,r,n){return Vu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Vu(e.primaryColor,ca.color.primary)}function Gu(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 Ku={sharp:.5,default:1,round:1.5};function Yu(e,t,r){if(e===null)return t;let n=Ku[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Qu="Everfur",Ju=.5;function resolveTheme(e){return hc(Xu(e),e)}function themeAdjustments(e){let t=Xu(e);return Ea(t,hc(t,{...e,highContrast:false}))}function Xu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=rc(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=lc((i==="auto"?l:i)==="dark"?fa:ca,e?.typeProfile),a=withServerBranding(o,nc(r));return withServerBranding(a,nc(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Zu(e){return e==="placeholder"?"chat_placeholder":Du(e)}var ec={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 tc(e,t){return t.has(Zu(e))?true:(ec[e]??[]).some(e=>t.has(e))}function rc(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(tc(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of Co){let n=l[r];n!==void 0&&(t.has(`${bu}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function nc(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function lc(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:qo}})}function ic(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function oc(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Ju,e)}var ac=["content","heading","control","compact","badge"];function sc(e,t){let r={};for(let n of ac){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Vo[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return ac.every(e=>r[e]===Vo[e])?Vo:r}function uc(e,t){return t>0?Math.min(e,t):e}function cc(e,t,r,n){let l={};for(let i of ac)l[i]=n?ic(e,uc(t,r[i])):e;return l}function dc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function fc(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 l=e.headingFamily!==null&&r!==void 0&&dc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of _u)!(i[e]===ea||i[e]===ta)&&r!==void 0&&dc(r,i[e])===false&&(i[e]=Uu(e)?ta:ea,o[e]=false),n!==null&&Uu(e)&&i[e]===ta&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function hc(e,t){let r=e.meta.displayName.trim().length===0?Qu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of _u){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.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,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Zo,s=oc(t?.textScale),u=sc(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=hu(e.type.roles,()=>d),h=c?hu(f,e=>uc(s,u[e.tier])):f,p=t?.typeProfile==="phone"?pu(e.type.size,f,d):ic(e.type.size,d),g=cc(p,s,u,c),b=Ca(e),m={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:b,space:e.space,radius:e.radius,type:{...e.type,...fc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,ps(b),gs(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var pc="/widget/v1/entitlements",gc=304,bc=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",yc(t));return n.ok?vc(n.value):n.error.httpStatus===gc?bc:{kind:"failed",error:n.error}}var mc=64;function yc(e){let t={};return _c(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=mc?{method:"GET",path:pc,headers:t,query:{region:e.region}}:{method:"GET",path:pc,headers:t}}function vc(e){if(e===null||typeof e!="object"||!_c(e.revision))return xc();let t=typeof e.region=="string"?e.region:"",r=_c(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
|
-
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:
|
|
45
|
-
return Object.freeze(t)}function
|
|
46
|
-
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function
|
|
47
|
-
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:
|
|
48
|
-
return Object.freeze({request(){return Promise.resolve(err(Xc(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 od=/* @__PURE__ */new WeakSet;function ad(){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 od.add(t),t}var sd=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new cd(e,t)}var ud=6e4,cd=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 J("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:Et,platform:t?.platform??jt,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ot(r?.appVersion)}),this.telemetry=r.telemetry?ed(r.telemetry,this.errorContext):$e,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=id(l);else if(r.transport!==void 0)o=r.transport;else{let e=Zc(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=id(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Hi(this,this.mintScope),this.transport=o,l!==null&&(ld(l,this.telemetry,t?.platform),this.emit({type:"error",code:Xc(l).code,requestId:null,context:It(this.errorContext,"runtime",null)})),this.errorPolicy=rd(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??Ve,this.upload=r.upload??Qr,this.uploadTransport=r.uploadTransport??hl,this.imageCache=r.imageCache??sd,this.kv=r.storage??ad(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Uc():Uc(()=>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:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",dd(e),()=>this.buildChatController(e),fd),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${dd(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=Pc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Oc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Yc(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=l===null?Jc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Ki(`${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-ud,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||Di(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 l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&qc(l)===qc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??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,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}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:rd(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 Bc(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 Mc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Lc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Ni(Ui(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(hd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&qi(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 l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?hd("prepare"):r===null?null:Xc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(et(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:It(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
49
|
-
return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}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",dd(t),()=>this.buildChatController(t),fd,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 dd(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function fd(e){e.dispose()}function hd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function pd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function gd(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 bd(e){return e.ok?e:err(gd(e.error))}function md(e){return{send:async(...t)=>bd(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var yd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),vd=globalThis,kd=vd[yd]??(vd[yd]=createContext(null));kd.displayName??="EverfurContext";function wd(){let e=o(kd);if(e===null)throw new J("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return wd().handle}var Cd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Sd=globalThis,xd=Sd[Cd]??(Sd[Cd]=createContext(ca));xd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(xd)}var _d=()=>()=>{},Rd=()=>null;function Td(e,t){return i(t?.subscribe??_d,t?.get??Rd,t?.get??Rd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=wd(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?Id(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=Td(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!zd(k)||Fa(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(xd.Provider,{value:v},e.children)}function Id(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function zd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:u,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=c(null),b=c(null),m=c(t?.onEvent);m.current=t?.onEvent;let y=c(e=>{m.current?.(e)}),[v,k]=d(e=>e+1,0),w=c(null),C=c(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=c(null),R=c(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:Pd(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=c(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;f(()=>{z.setUser(x)},[z,O]),f(()=>{z.setActivePet(I)},[z,I]);let E=c(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,Od(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:Ed(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:u});return r(kd.Provider,{value:F},h.wrap?h.wrap(A):A)}function Pd(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Od(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Ed(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var jd=2;function Fd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<jd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Ad(){let e=N;return(t,r)=>{let n=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]?.tap?.(t,r),l=new e(t,{method:r.method,headers:n?{...r.headers,...n.headers}:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return n?.watch(l),Object.assign(l,{getResponseHeader:e=>Fd(l,e)})}}function Dd(){let e=w();return e==="dark"?"dark":e==="light"?"light":null}function Md(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Ld(){let[e,t]=l(false);return n(()=>{let e=true,r=k?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(k);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=k?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Bd(){let e=S?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(S);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Hd(e){let t=C?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(C,"change",e);return()=>r?.remove?.()}function Ud(){return i(Hd,Bd,Bd)}function Nd(){try{let e=m?.OS;return typeof e=="string"?e:null}catch{return null}}function $d(){return Nd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Wd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=$d(),l=k?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(k);Md(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=k?.addEventListener,o=typeof i=="function"?i.call(k,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function Vd(){return Nd()==="ios"?"Menlo":ta}function qd(){return globalThis.__DEV__!==false}var Gd=/* @__PURE__ */new Set;function Kd(e){if(!qd()||Gd.has(e))return;Gd.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 Yd(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 l=n.includes(e);return l||Kd(e),l}var Qd=/* @__PURE__ */new Set;function Jd(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 Xd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Zd(e){if(!qd())return;let t=Jd(e).filter(e=>!Qd.has(e));if(t.length===0)return;for(let e of t)Qd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Xd[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 ef(e){n(()=>{try{Zd(e)}catch{}},[e])}var tf=/* @__PURE__ */Object.freeze({useColorScheme:Dd,useReducedMotion:Ld,useTextScale:Ud,useHighContrast:Wd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:Vd,isFontRegistered:Yd,useResolvedTheme:ef,isDevelopment:qd});function rf(e){return r(H,null,e)}var nf=/* @__PURE__ */Object.freeze({platform:"react-native",...m.OS==="web"?{}:{eventSourceFactory:Ad()},wrap:rf,theme:tf});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:nf})}function useCapability(e){let{runtime:t}=wd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function lf(e){let{runtime:t}=wd(),r=t.entitlements,n=u(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=u(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var of=/* @__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[of[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[of[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function af(e){return e<=450?"regular":e<=650?"medium":"bold"}var sf={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=uf.get(e);r===void 0&&(r=/* @__PURE__ */new Map,uf.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=cf(e,t);return r.set(t,l),l}var uf=/* @__PURE__ */new WeakMap;function cf(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=af(Number(n)),i=r.face==="mono"?face(e,sf[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function df(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=df(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(R,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var ff=t(function(e,t){return r(y,{...e,...t===null?{}:{ref:t}})});var hf=class extends h{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:t,resetKey:n}){return r(hf,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var pf=48;function gf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>gf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */$(HostRender,{render:l,fallback:/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */$(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */$(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */$(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>bf(r),[r]);/* @__PURE__ */
|
|
50
|
-
return $(x,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */$(x,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>
|
|
51
|
-
return $(x,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */$(Text,{style:n.offstateText,children:l}):null})}function
|
|
52
|
-
return $(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var
|
|
53
|
-
return Object.freeze(n)}function
|
|
54
|
-
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function
|
|
55
|
-
return Object.freeze({petRef:
|
|
56
|
-
return Object.freeze(n)}var
|
|
57
|
-
return Object.freeze(a)}function sp(e){return e.sender?.displayName??Vf.senderVet}function up(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var cp=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 dp(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 fp(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===rp&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>cp.test(e)||dp(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var hp="pet_not_registered";function pp(e){return e!=null&&e.reasonCode===hp}var gp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function bp(e,t,r){let{runtime:i,userRef:o,scopeEpoch:s}=wd(),d=u((e,t)=>{let r=i.registry.services.authFor(o);return Ni(Ui(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,s]),f=a(()=>t===void 0?null:$i(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=c(0),b=c(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${s}|${e}|${f}`,y=u(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=u(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?gp:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var mp=/* @__PURE__ */Object.freeze({});function yp(e){let[t,r]=l(mp),i=c(null),o=c([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===mp?e:mp);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let s=u(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:s}),[t,s])}var vp=/* @__PURE__ */new WeakSet;function kp(){let e=makeEverfurError("internalError",{retryable:true});return vp.add(e),err(e)}function wp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&vp.has(t)}var Cp=500;function Sp(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,Cp):null}function xp(e,t,r,l){let i=Sp(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=c(e);a.current=e;let s=c(null),u=c(null),d=c(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||u.current===o)return;let e=a.current;if(e===void 0)return;u.current=o;let r=e=>{u.current===o&&(u.current=null),!wp(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var _p=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Rp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Tp=/* @__PURE__ */Object.freeze({..._p,markRead:true}),Ip=/* @__PURE__ */Object.freeze({...Rp,markRead:true});function zp(e,t){return e?t?Tp:_p:t?Ip:Rp}function Pp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Dh(()=>r()!==!1)===true}function Op(e,t){let r=c({target:e,isVisible:t});r.current={target:e,isVisible:t};let l=c(e.isStreaming);n(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:n,isVisible:i}=r.current;n.status!=="complete"||n.conversationId===null||n.unreadCount===null||!i()||n.markRead()},[e.isStreaming])}var Ep=3e5;function jp(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 Fp(e,t,r){let l=c(t);l.current=t;let i=c(null),o=c(null),a=c(false),s=c(0),u=c(0),d=c(3e4),f=()=>e?.isOffline===void 0?false:Dh(()=>e.isOffline?.()===!0)===true,h=f(),p=c(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:c}=l.current,h=Yr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:c===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,jp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,Ep),u.current=Date.now()+s.current):(s.current=0,u.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=Dh(()=>e(()=>{p.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)Dh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{Date.now()<u.current||Pp(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var Ap=/^efch_[A-Za-z0-9_-]{43}$/,Dp="efch";function Mp(e){return typeof e=="string"&&Ap.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(`${Dp}=`))continue;let e=r.slice(Dp.length+1);return Mp(e)?e:null}return null}var Lp=128,Bp=/[\u0000-\u001f\u007f]/;function Hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Up(e){return typeof e!="string"||e.length===0||e.length>Lp||Bp.test(e)||e.includes("://")?null:e}function Np(e){if(e===null)return null;let t=e.conversation_id,r=Up(e.pet_ref);return typeof t!="string"||!Dn(t)||r===null?null:{conversationId:t,petRef:r}}function $p(e,t,r){return Mp(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(Np(Hp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(sn("internalError",false))):Promise.resolve(ok(null))}function Wp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=Mp(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return $p(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function Vp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function qp(e,t,r){let l=Vp(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=c({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let u=c(null),d=c(null),f=r.petRef;n(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(u.current=l);return}i&&!r.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var Gp=/* @__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 Kp(e){let t=e?.replace(/\s+/g," ").trim();return t||Gp.untitled}function Yp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function Qp(e){let t=Yp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Gp.newReply.replace("{date}",t):t}function Jp(e,t){return t?`${Gp.countLabel}${Gp.countSeparator}${e}`:Gp.countLabel}function Xp(e){return`${e.unreadCount!==null&&e.unreadCount>0?Gp.unreadPrefix:""}${Gp.openConversation} ${Kp(e.title)}`}function Zp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function eg(e,t){let r=Zp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Zp(Kp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function tg(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function rg(e){let[t,r]=l(false),[i,o]=l(""),s=e.listConversations,d=c(0),[f,h]=l(()=>tg(s)),p=f.scope===s?f:tg(s);n(()=>(d.current+=1,r(false),o(""),h(tg(s)),()=>{d.current+=1}),[s]);let g=u(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:s,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===s?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:s,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,s]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>eg(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var ng="#111111",lg="#FFFFFF",ig=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ng,pillColor:lg,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ng,pillColor:lg,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ng,pillColor:lg,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ng,pillColor:lg,showsVetAction:false})});function og(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function ag(e){return qf(Vf.urgencyGeneralReason,{petName:e?.trim()||Vf.emptyTitlePetFallback})}function sg(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 l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:ug(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:ag(t)}:null}return null}function ug(e){return typeof e=="string"&&e.trim().length>0?e:null}function cg(e){let t=e===null?null:og(e),[r,i]=l(null),[o,s]=l(false);n(()=>s(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:ig[e.level],f=e!==null&&!c&&e.level!=="general",h=u(()=>{t!==null&&i(t),s(false)},[t]),p=u(()=>s(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:qf(Vf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var dg=()=>globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]??={loader:null,lazy:null};var fg=dg;function registerEverfurChatCards(e){let t=fg();t.loader=e;let r=e&&Promise.resolve().then(e).then(e=>typeof e.ServerCards=="function"?e.ServerCards:NONE3,()=>NONE3);t.lazy=r&&s(async()=>({default:await r}))}var NONE3=()=>null,hg=createContext(null);function ServerCardsSlot({message:e}){let t=o(hg),n=fg(),l=e.a2ui??n.frames?.get(e.responseId),i=n.lazy;return l===void 0||t===null||i===null?null:r(g,{fallback:null},r(i,{message:e,a2ui:l,host:t}))}var pg="everfur.com",gg=2048,bg=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function mg(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&&bg.test(e)&&t.add(e)}/* @__PURE__ */
|
|
58
|
-
return Object.freeze([...t])}function
|
|
59
|
-
return Object.freeze({hosts:e,open:t!==void 0?e=>{
|
|
60
|
-
return W(x,{style:[
|
|
39
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function Ai(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 Di(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Mi)}catch(e){Mi(e)}}function Mi(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var Li=/* @__PURE__ */new WeakMap,Bi=/* @__PURE__ */new Map;function Hi(e,t){Li.set(e,t)}function Ui(e,t,r,n){let l=Li.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${$i(n)}`}function Ni(e,t){if(e===null)return t();let r=Bi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Bi.get(e)===n&&Bi.delete(e)});return Bi.set(e,n),n}function $i(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map($i).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)}:${$i(t)}`).join(",")}}`}var Wi=/* @__PURE__ */new WeakMap;function Vi(e,t){let r=Wi.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Wi.set(e,r)),r.add(t),()=>{r?.delete(t)}}function qi(e){let t=Wi.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Gi=/* @__PURE__ */new Map;function Ki(e,t){return()=>{let r=Gi.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Gi.get(e)===l&&Gi.delete(e)});return Gi.set(e,l),l}}var Yi="/widget/v1/me/timezone",Qi=/^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)\/[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)?$/,Zi=/* @__PURE__ */new Set;function Ji(e){return typeof e=="string"&&e.length<=64&&Qi.test(e)?e:null}function Xi(e,t){try{let r=Ji(Intl.DateTimeFormat().resolvedOptions().timeZone);if(r===null)return;let n=`${e}|${r}`;if(Zi.has(n))return;Zi.add(n),createRequestFunnel({auth:t}).send("member.deviceTimezone",{method:"PUT",path:Yi,body:{timezone:r}},{maxAttempts:1,idempotent:!1}).catch(()=>{})}catch{}}function parseColor(e){let t=eo(e);return t===null?null:ao(t)}function eo(e){if(typeof e=="number")return no(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return to(t.slice(1));if(t.toLowerCase().startsWith("0x"))return to(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return ro(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=to(t);if(e!==null)return e}return/^\d+$/.test(t)?no(Number.parseInt(t,10)):null}function to(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:io(t[0]),g:io(t[1]),b:io(t[2]),a:1};if(t.length===6)return{r:lo(t,0),g:lo(t,2),b:lo(t,4),a:1};if(t.length===8){let e=lo(t,0);return{r:lo(t,2),g:lo(t,4),b:lo(t,6),a:e/255}}return null}function ro(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 l=oo(Number(n[0])),i=oo(Number(n[1])),o=oo(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function no(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 lo(e,t){return Number.parseInt(e.slice(t,t+2),16)}function io(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function oo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function ao(e){if(e.a>=1)return so(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function so(e,t,r){return`#${uo(e)}${uo(t)}${uo(r)}`.toUpperCase()}function uo(e){return e.toString(16).padStart(2,"0")}var co="#111111",fo="#FFFFFF",ho="#000000";function readableOn(e){let t=eo(e);if(t===null)return fo;let r=bo(t),n=bo({r:17,g:17,b:17}),l=bo({r:255,g:255,b:255});return yo(r,l)>=yo(r,n)?fo:co}function po(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(fo,e)>=contrastRatio(ho,e)?fo:ho}function go(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(fo)>=t(ho)?fo:ho}function bo(e){let t=mo(e.r/255),r=mo(e.g/255),n=mo(e.b/255);return.2126*t+.7152*r+.0722*n}function mo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function yo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=eo(e),n=eo(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:vo(r,l);return yo(bo(i),bo(l))}function vo(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 ko(e,t){let r=eo(e),n=eo(t);if(r===null||n===null)return null;let l=r.a>=1?r:vo(r,{...n});return so(l.r,l.g,l.b)}function wo(e,t){let r=eo(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 Co=.05;function So(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(eo(e)===null)return r;if(i(e))return e;let o=ko(e,l),a=o===null?null:eo(o),s=eo(r);if(a===null||s===null)return r;for(let e=1;e<1/Co;e+=1){let t=e*Co,r=(e,r)=>Math.round(e+(r-e)*t),n=so(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function xo(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function _o(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:Ro(c+a),g:Ro(d+a),b:Ro(f+a)}}function Ro(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var To=/* @__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"]),Io=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),zo=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return zo[e]??Io}var Po=4.5,Oo=/* @__PURE__ */Object.freeze({});function Eo(e){return To.includes(e)}function jo(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,l]of Object.entries(e)){if(!Eo(n)||l===null||typeof l!="object")continue;let e=Do(l);if(e===null)continue;let i=Fo(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function Fo(e,t){let r=zo[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 Ao(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Do(e){let t={},r=parseColor(Ao(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(Ao(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=jo(Ao(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(Ao(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Oo:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Mo(e){let t=eo(e);return t!==null&&t.a>=1}var Lo=3,Bo=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Ho(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Uo(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>ko(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=Lo))return null;let l=[...t,...n,...r];return So(n[0],l,go(l),Lo)}function No(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>ko(e,t)??t)}function $o(e,t){let r=go(e);return e.every(e=>contrastRatio(r,e)>=t)}function Wo(e,t){let r=t[0];return r===void 0?null:ko(e,r)}function Vo(e){let t=po(e[0],Po);return e.every(e=>contrastRatio(t,e)>=Po)?t:go(e)}function qo(e,t,r,n,l){return Bo.has(e)?false:l?true:r!==void 0&&Ho(t,r)?false:!(n!==void 0&&r!==void 0&&Mo(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of To){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=No(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!$o(u,Po)){let e=Wo(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Mo(h)&&Uo(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<Po))&&(c.textColor=Vo(u),d=true);else if(e!==void 0){let t=So(e,u,go(u),Po);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&qo(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=So(o.borderColor,e,go(e),Lo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Uo(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var Go=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),Ko=/* @__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 Yo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Yo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var Qo=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Zo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),Jo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Xo={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ea={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},ta={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},ra={regular:"400",medium:"500",bold:"700"},na={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},la=0,ia="System",oa="monospace",aa=["content","heading","control","compact","badge"];function sa(e){let t={};for(let r of aa)t[r]=e;return t}var ua=[];function ca(){return{family:ia,mono:oa,fontUrl:null,families:{regular:ia,medium:ia,bold:ia,mono:oa,monoMedium:oa,monoBold:oa},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ea,tierSizes:sa(ea),lineHeight:ta,weight:ra,letterSpacing:na,scale:1,maxScale:la,scaleCaps:Qo,headingFamily:null,headingWeight:null,fontSources:ua,roles:Ko,typeScale:1}}var da={},fa=/* @__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 ha={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(fa.standard),emphasized:cssCubicBezier(fa.emphasized),exit:cssCubicBezier(fa.exit)},reducedMotion:false},pa={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)"},ga=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:pa,space:Jo,radius:Xo,type:ca(),motion:ha,slots:da}),ba={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)"},ma=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ba,space:Jo,radius:Xo,type:ca(),motion:ha,slots:da});function ya(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function va(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function ka(e){return va(e).every(t=>contrastRatio(e.brand,t)>=Lo)}function wa(e){return[e.chatGround,e.surface,e.surfaceCream]}function Ca(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...Sa(e,t)]}function Sa(e,t){return[ko(t,e.surface)??e.surface,ko(t,e.surfaceCream)??e.surfaceCream]}function xa(e){return[e.composerFill,e.chatGround]}var _a=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Ra(e,t){let r=new Set(ya(t));return ya(e).every(e=>r.has(e))}function Ta(e){let t=e.color,r=(e.brightness==="dark"?ma:ga).color,n=(e.brightness==="dark"?ga:ma).color,l=ya(t),i=go(l)!==go(ya(r)),o=Ra(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&_a.has(e)?t:So(u&&i?n:t,l,go(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=po(f,Po),p=c("danger",t.danger,[...l,...Sa(t,t.badgeBgCritical)],Po),g={...t,onPrimary:h,onAccent:po(t.accent,Po),onDanger:contrastRatio(h,p)>=Po?h:po(p,Po),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,Po),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,wa(t),Po),text:{...t.text,primary:u("primary",l,Po),secondary:u("secondary",l,Po),muted:u("muted",l,Po),metaCool:u("metaCool",l,Po),timestamp:u("timestamp",l,Po),placeholder:u("placeholder",va(t),Lo)},danger:p,errorRed:c("errorRed",t.errorRed,Ca(t,t.badgeBgCritical),Po),warningStrong:c("warningStrong",t.warningStrong,Ca(t,t.badgeBgCaution),Po),composerBorder:c("composerBorder",t.composerBorder,xa(t),Lo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,va(t),Lo)},b={...g,...Aa(g,r,o)};return{...b,...Ia(t,b,r)}}function Ia(e,t,r){let n={},l=(e,t,r)=>So(e,t,go(t),r);if((!Ea(e.success,r.success)||!Ea(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,Ca(t,e.badgeBgPositive),Po)),(!Ea(e.cautionAccent,r.cautionAccent)||!Ea(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,Ca(t,e.badgeBgCaution),Po)),za(e,r)){n.info=l(e.info,Ca(t,e.badgeBgInfo),Po);let r=[t.surface,t.chatGround,...Sa(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,Lo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function za(e,t){return!Ea(e.info,t.info)||!Ea(e.badgeBgInfo,t.badgeBgInfo)}var Pa=.24,Oa=.3;function Ea(e,t){return parseColor(e)===parseColor(t)}function ja(e,t){return Ea(e.accent,t.accent)?Ea(e.brand,t.brand)?null:e.brand:e.accent}function Fa(e,t,r){let n=wo(e,r);return(n===null?null:ko(n,t))??t}function Aa(e,t,r){let n=ja(e,t),l=va(e),i=go(l),o=go([e.surface])===fo,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?Fa(ga.color.highlight,e.surface,Oa):ga.color.highlight:s=Fa(n,e.surface,o?Oa:Pa);let u=a?t.onHighlight:So(e.text.primary,[s],go([s]),Po),c=n===null?t.mark:So(n,l,i,Lo),d=ka(e)?e.brand:i,f=(e,t,n)=>r&&Ea(e,t)?n:So(e,l,d,Lo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=Lo)?e.primary:So(e.primary,h,go(h),Lo);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Da=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Ma(e,t){let r=(e.brightness==="dark"?ma:ga).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!Da(e,t);a(n.text.primary,r.text.primary)&&!Da(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(Da(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),Da(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!Da(l.controlEdge,n.brandBorder)&&!ka({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Da(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!Da(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!Da(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!Da(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!Da(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(Da(l.info,n.info)||o("info_color","information text",n.info,l.info),Da(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of To){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!Da(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!Da(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!Da(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
|
|
40
|
+
return Object.freeze(i)}var La=/* @__PURE__ */new Set;function Ba(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(La.has(t))return;La.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Ha="#23272C",Ua=4.5,Na=.6,$a=.9,Wa=.02,Va="#FFFFFF",qa="#111111";function Ga(e){return contrastRatio(e,Ha)>=Ua&&Math.max(contrastRatio(e,Va),contrastRatio(e,qa))>=Ua}function deriveDarkVariant(e){let t=eo(e);if(t===null)return null;let{h:r,s:n,l:l}=xo(t.r,t.g,t.b),i=Math.min(Math.max(l,Na),$a);for(let e=0;;e+=1){let t=i+e*Wa;if(t>$a)break;let l=_o({h:r,s:n,l:t}),o=so(l.r,l.g,l.b);if(Ga(o))return o}let o=_o({h:r,s:n,l:$a});return so(o.r,o.g,o.b)}var Ka=7,Ya=.05,Qa="#000000",Za="#FFFFFF";function Ja(e,t,r,n){let l=ko(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=eo(l),o=eo(r);if(i===null||o===null)return r;for(let e=1;e<1/Ya;e+=1){let r=e*Ya,l=(e,t)=>Math.round(e+(t-e)*r),a=so(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function Xa(e,t){let r=ya(e),n=r[0],l=es(n);for(let e of r){let r=es(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function es(e){let t=eo(e);return t===null?0:bo(t)}function ts(e,t){return ko(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=go(ya(t))===Za,n=r?Za:Qa,l=Xa(t,r),i=e=>Ja(e,l,n,Ka),o={...t,brandSoft:ts(t.brandSoft,t.surface),brandSofter:ts(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:ts(t.badgeBgPositive,t.surface),badgeBgCaution:ts(t.badgeBgCaution,t.surface),badgeBgCritical:ts(t.badgeBgCritical,t.surface),badgeBgNeutral:ts(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:ts(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:ts(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:ts(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var rs=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),ns=rs.cream,ls=rs.subtle,is=rs.ring,os=10;function as(e,t,r){let n=eo(e),l=eo(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return so(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function ss(e){if(e===null)return{};let t=go([e]),r=as(e,t,ns),n=as(e,t,ls),l=as(e,t,is);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function us(e){if(e===null)return{};let t=eo(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function cs(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(os,Math.round(t*n*10)/10);return l}function ds(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function fs(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var hs=/* @__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 ps(e,t){let r=eo(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function gs(e,t){if(e===null)return{};let r=ps(e,t?hs.success.dark:hs.success.light),n=ps(e,t?hs.successCard.dark:hs.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function bs(e,t){if(e===null)return{};let r=ps(e,t?hs.warning.dark:hs.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function ms(e,t){if(e===null)return{};let r=ps(e,t?hs.info.dark:hs.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function ys(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function vs(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:wa(e),header:[e.surface,e.background,e.chatGround],banner:[ko(e.badgeBgInfo,e.surface)??e.surface,ko(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 ks(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 ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Cs=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),Ss=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),xs=/* @__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 _s(e){return typeof e=="string"&&Cs.includes(e.trim().toLowerCase())}function Rs(e,t){let r=e[t];return r??void 0}var Ts=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Ts)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Is=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],zs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Ps=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Os=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Es=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!ws(e))return null;let t=_s(e.theme)?Ss[e.theme.trim().toLowerCase()]:{},r=ws(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=Rs(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of Is){let r=Rs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of zs){let r=Rs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of Os){let r=Rs(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of Es){let r=parsePx(Rs(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of Ps){let r=Rs(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(ws(u)){let e={};for(let t of To){let r=u[t];ws(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var js="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function Fs(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var As=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?Fs(__EVERFUR_BRAND_CDN_ORIGIN__):js;var Ds=/* @__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}),Ms=/* @__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"}),Ls=Object.keys(Ms),Bs="presentation",Hs="presentation.";function isPresentationLockName(e){if(e===Bs)return true;if(!e.startsWith(Hs))return false;let t=e.slice(Hs.length);return Object.values(Ms).includes(t)}var Us={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"]},Ns=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function $s(e,t){if(t==null)return;let r=Us[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:Ns.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 Ls){let n=Ms[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=$s(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${Hs}${Ms[e]}`;for(let e of t)if(e===Bs||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of Ls){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??Ds[e]}/* @__PURE__ */
|
|
41
|
+
return Object.freeze(a)}var Ws=4,Vs=/* @__PURE__ */Object.freeze({min:1,max:2}),qs=100,Gs=2048,Ks=["100","200","300","400","500","600","700","800","900"];function Ys(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 Qs(e){let t=Ys(e);if(t===null)return null;let r=String(t);return Ks.includes(r)?r:null}function Zs(e){let t=Ys(e);return t===null?null:Math.min(Vs.max,Math.max(Vs.min,t))}function Js(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Gs?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function Xs(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>qs||/[\u0000-\u001F\u007F]/.test(t)?null:t}function eu(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function tu(e){if(!ws(e))return null;let t=Xs(e.family);if(t===null)return null;let r=eu(e,"src"),n=eu(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=Js(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let l=Js(r);if(l===null)return null;let i={family:t,src:l},o=Qs(e.weight);o!==null&&(i.weight=o);let a=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(a==="normal"||a==="italic")&&(i.style=a),/* @__PURE__ */Object.freeze(i)}function ru(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=Ws)break;let e=tu(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var nu=/* @__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})}),lu=["content","heading","control","compact","badge"],iu=["sans","heading","mono"],ou=/* @__PURE__ */Object.freeze({min:1,max:3.1});function au(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 su(e,t){return Math.min(t.max,Math.max(t.min,e))}function uu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function du(e){let t=au(e);return t===null?null:su(t,nu.typeScale)}function fu(e){if(!uu(e))return null;let t={};for(let r of lu){let n=au(cu(e,r));n!==null&&(t[r]=n<=0?0:su(n,ou))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function hu(e){if(!uu(e))return null;let t={},r=au(cu(e,"size","fontSize","font_size"));r!==null&&(t.size=su(r,nu.size));let n=Zs(cu(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let l=Qs(cu(e,"weight","fontWeight","font_weight"));l!==null&&(t.weight=l);let i=cu(e,"face");typeof i=="string"&&iu.includes(i.trim())&&(t.face=i.trim());let o=au(cu(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=su(o,nu.letterSpacing));let a=cu(e,"uppercase");return typeof a=="boolean"&&(t.uppercase=a),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function pu(e){if(!uu(e))return null;let t={};for(let r of Go){let n=hu(cu(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var gu=e=>Math.round(e*10)/10,bu=e=>Math.round(e*100)/100;function mu(e,t,r,n){if(t===null&&r===null&&n===null)return e;let l=t===null?null:t/Ko.body.size,i=r===null?null:r/Ko.body.lineHeight,o={};for(let t of Go){let r=e[t],a=Ko[t];o[t]=/* @__PURE__ */Object.freeze({...r,...l===null?{}:{size:gu(a.size*l)},...i===null?{}:{lineHeight:bu(a.lineHeight*i)},...n?.[t]??{}})}/* @__PURE__ */
|
|
42
|
+
return Object.freeze(o)}function yu(e,t){let r=false,n={};for(let l of Go){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:gu(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function vu(e,t,r){return{nano:gu(e.nano*r),small:gu(e.small*r),micro:gu(e.micro*r),tiny:gu(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:gu(e.verdict*r)}}var ku=/* @__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"]),wu="slots.",Cu=/* @__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||Cu.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
|
|
43
|
+
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function Su(e){return e==="hide_powered_by"||ku.includes(e)||isPresentationLockName(e)?true:e.startsWith(wu)&&To.includes(e.slice(wu.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=_u(t),n=expandAppearance(Iu(t,"appearance")),l=n===null?r:xu(_u(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function xu(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 _u(e){return{displayName:zu(Iu(e,"display_name","displayName")),logoUrl:zu(Iu(e,"logo_url","logoUrl")),primaryColor:parseColor(Iu(e,"primary_color","primaryColor")),accentColor:parseColor(Iu(e,"accent_color","accentColor")),brightness:Au(Iu(e,"brightness","color_scheme","colorScheme")),fontFamily:zu(Iu(e,"font_family","fontFamily")),fontUrl:zu(Iu(e,"font_url","fontUrl")),fonts:Ou(Iu(e,"fonts")),fontUrls:Ou(Iu(e,"font_urls","fontUrls")),placeholder:zu(Iu(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Tu(Iu(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Iu(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Iu(e,"accent_color_dark","accentColorDark")),surfaceStyle:Fu(Iu(e,"surface_style","surfaceStyle"),Eu),radiusScale:Fu(Iu(e,"radius_scale","radiusScale"),ju),logoUrlDark:zu(Iu(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Iu(e,"slots")),accessibilityMaxFontScale:Bu(Iu(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Nu(Iu(e,"locked_fields","lockedFields")),presentation:parsePresentation(Iu(e,"presentation")),schemaVersion:Hu(Iu(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Iu(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Iu(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Iu(e,"text_color","textColor")),textColorDark:parseColor(Iu(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Iu(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Iu(e,"danger_color_dark","dangerColorDark")),fontSizeBase:Ru(Iu(e,"font_size_base","fontSizeBase"),xs.fontSizeBase),borderRadius:Ru(Iu(e,"border_radius","borderRadius"),xs.borderRadius),spacingUnit:Ru(Iu(e,"spacing_unit","spacingUnit"),xs.spacingUnit),successColor:parseColor(Iu(e,"success_color","successColor")),successColorDark:parseColor(Iu(e,"success_color_dark","successColorDark")),warningColor:parseColor(Iu(e,"warning_color","warningColor")),warningColorDark:parseColor(Iu(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Iu(e,"info_color","infoColor")),infoColorDark:parseColor(Iu(e,"info_color_dark","infoColorDark")),headingFontFamily:zu(Iu(e,"heading_font_family","headingFontFamily")),fontWeightBody:Qs(Iu(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Qs(Iu(e,"font_weight_heading","fontWeightHeading")),lineHeight:Zs(Iu(e,"line_height","lineHeight")),fontSources:ru(Iu(e,"font_sources","fontSources")),assistantAvatarUrl:zu(Iu(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:fu(Iu(e,"text_scale_caps","textScaleCaps")),typeScale:du(Iu(e,"type_scale","typeScale")),typeRoles:pu(Iu(e,"type_roles","typeRoles"))}}function Ru(e,t){let r=Du(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Tu(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 Iu(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 zu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Pu=["regular","medium","bold","mono","monoMedium","monoBold"];function Ou(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Pu){let n=zu(Iu(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Eu=["white","cream","subtle"],ju=["sharp","default","round"];function Fu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Au(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Du(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 Mu=1,Lu=3.1;function Bu(e){let t=Du(e);return t===null?null:t<=0?0:Math.min(Lu,Math.max(Mu,t))}function Hu(e){if(e==null)return null;let t=Du(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Uu(e){let t=e.trim();return t.startsWith(wu)?t:t.startsWith(Hs)?Hs+t.slice(Hs.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=Uu(r);Su(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 $u=/* @__PURE__ */new RegExp(`^${As}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&$u.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"?ma:ga:e,n=r.brightness==="dark"?ma:ga,l=r.brightness==="dark",i=l?t.primaryColorDark??Ku(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??Ku(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&Zu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?eo(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?Ju(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=ss(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??Ku(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?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,...us(y(t.dangerColor,t.dangerColorDark)),...gs(y(t.successColor,t.successColorDark),l),...bs(y(t.warningColor,t.warningColorDark),l),...ms(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Yu(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:ds(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?fs(t.borderRadius,n):ec(t.radiusScale??null,r.radius,n),type:{...r.type,...Gu(r.type,t),size:cs(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:ys(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:mu(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 Wu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Vu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function qu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function Gu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of Pu){let a=Wu[e].map(e=>r[e]).find(e=>e!==void 0),s=qu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Vu)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function Ku(e){return e===null?null:deriveDarkVariant(e)}function Yu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Qu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function Zu(e,t,r,n){return Qu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Qu(e.primaryColor,ga.color.primary)}function Ju(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 Xu={sharp:.5,default:1,round:1.5};function ec(e,t,r){if(e===null)return t;let n=Xu[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var tc="Everfur",rc=.5;function resolveTheme(e){return yc(nc(e),e)}function themeAdjustments(e){let t=nc(e);return Ma(t,yc(t,{...e,highContrast:false}))}function nc(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=ac(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=uc((i==="auto"?l:i)==="dark"?ma:ga,e?.typeProfile),a=withServerBranding(o,sc(r));return withServerBranding(a,sc(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function lc(e){return e==="placeholder"?"chat_placeholder":Uu(e)}var ic={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 oc(e,t){return t.has(lc(e))?true:(ic[e]??[]).some(e=>t.has(e))}function ac(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(oc(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of To){let n=l[r];n!==void 0&&(t.has(`${wu}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function sc(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function uc(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:Zo}})}function cc(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function dc(e){return e===void 0||!Number.isFinite(e)?1:Math.max(rc,e)}var fc=["content","heading","control","compact","badge"];function hc(e,t){let r={};for(let n of fc){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Qo[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return fc.every(e=>r[e]===Qo[e])?Qo:r}function pc(e,t){return t>0?Math.min(e,t):e}function gc(e,t,r,n){let l={};for(let i of fc)l[i]=n?cc(e,pc(t,r[i])):e;return l}function bc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function mc(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 l=e.headingFamily!==null&&r!==void 0&&bc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of Pu)!(i[e]===ia||i[e]===oa)&&r!==void 0&&bc(r,i[e])===false&&(i[e]=qu(e)?oa:ia,o[e]=false),n!==null&&qu(e)&&i[e]===oa&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function yc(e,t){let r=e.meta.displayName.trim().length===0?tc:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of Pu){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.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,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:la,s=dc(t?.textScale),u=hc(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=yu(e.type.roles,()=>d),h=c?yu(f,e=>pc(s,u[e.tier])):f,p=t?.typeProfile==="phone"?vu(e.type.size,f,d):cc(e.type.size,d),g=gc(p,s,u,c),b=Ta(e),m={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:b,space:e.space,radius:e.radius,type:{...e.type,...mc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,vs(b),ks(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var vc="/widget/v1/entitlements",kc=304,wc=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",Sc(t));return n.ok?xc(n.value):n.error.httpStatus===kc?wc:{kind:"failed",error:n.error}}var Cc=64;function Sc(e){let t={};return Pc(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Cc?{method:"GET",path:vc,headers:t,query:{region:e.region}}:{method:"GET",path:vc,headers:t}}function xc(e){if(e===null||typeof e!="object"||!Pc(e.revision))return zc();let t=typeof e.region=="string"?e.region:"",r=Pc(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
|
+
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Tc(e.capabilities),branding:Rc(e),livemode:e.livemode!==false,..._c(e)})}function _c(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 Rc(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 Tc(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Ic(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
|
|
45
|
+
return Object.freeze(t)}function Ic(e){return typeof e=="object"&&e!==null&&e.enabled===true}function zc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function Pc(e){return typeof e=="number"&&Number.isFinite(e)}var Oc=30;function createEntitlementPoller(e){let t=e.scheduler??Ec,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??Oc),l=e.rng??Math.random,i=()=>n+l()*n,o=false,a=false,s=null,u=null,c=n,d=0,f=()=>{s!==null&&(t.clear(s),s=null)},h=e=>{a||!o||(c=Math.max(n,e),s=t.set(()=>{s=null,b()},c*1e3))},p=null,g=async()=>{if(a)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},l;try{l=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:jc(r)}),!a&&t===d&&(e.onSettled?.(),h(i())),null}if(a||t!==d)return null;switch(l.kind){case"updated":u=l.revision,l.smsProfilePublic!==void 0?e.update(l.decisions,l.branding??null,l.livemode!==false,l.smsProfilePublic):e.update(l.decisions,l.branding??null,l.livemode!==false),h(l.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:l.error.code}),h(i());break;default:h(i())}return e.onSettled?.(),l},b=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||a||(o=true,b())},prime(){return a?Promise.resolve(null):p??b()},stop(){a||(a=true,d++,f())},refresh(){a||!o||(d++,u=null,f(),b())}}}var Ec={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function jc(e){return e instanceof Error?e.message:"poll failed"}var Fc=20;function Ac(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},l=/* @__PURE__ */new Map,i=/* @__PURE__ */new Set,o=0,a=/* @__PURE__ */new Map,s=(r,l)=>{let o=r??"",a=t.get(o)??n(r);if(!(a.hasUnread===l.hasUnread&&a.unreadCount===l.unreadCount&&a.conversationId===l.conversationId)){t.set(o,l);for(let e of[...i])e();i.size>0&&l.hasUnread!==null&&l.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:l.conversationId,unreadCount:l.unreadCount,hasUnread:l.hasUnread})}},u=(e,t)=>{a.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)}s(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)){a.delete(e??""),s(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,Fc).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let l=new Set(n.map(e=>e.id)),i=(a.get(e??"")??[]).filter(e=>!l.has(e.id));u(e,[...n,...i].slice(0,Fc))};return{subscribe(e){return i.add(e),()=>{i.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=l.get(r);if(n!==void 0)return n;let i=e.read(t);if(i===null)return Promise.resolve();let a=o,s=i.then(e=>{a!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{l.get(r)===s&&l.delete(r)});return l.set(r,s),s},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=a.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,l.clear(),a.clear(),t.size!==0){t.clear();for(let e of[...i])e()}}}}function Dc(e,t,r){let n=An({...t===null?{}:{petRef:t},limit:Fc},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?Hn(e.value):err(e.error)):Promise.resolve(err(n.error))}var Mc="everfur.notifications.device";var Lc="everfur.slots.v2",Bc="everfur.slots.installId.v2";var Hc=3e3,Uc=/* @__PURE__ */Object.freeze([Mc,Lc,Bc]);function Nc(e){let{leaving:t,identity:r,hooks:n,telemetry:l}=e;if(t===null||r===null||n.size===0)return null;let i=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(i))}catch(e){return Promise.reject(e)}}),a=(e,t)=>{try{l.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},s=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&a("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||a("timeout",o.length),r()},Hc);s.then(r,r)})}function $c(e){let{leaving:t,identity:r,transport:n,sessionId:l}=e,i=r.currentToken();i.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>i,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:l}}async function Wc(e,t){if(Uc.length===0)return;let r=await Promise.allSettled(Uc.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 Vc(){/* @__PURE__ */
|
|
46
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function qc(e=Vc){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 Gc="everfur.branding.v1.";function Kc(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 Yc(e){let t=3421674724,r=2216829733;for(let n of Kc(e)){r=(r^n)>>>0;let e=r*435,l=Math.floor(e/4294967296),i=e>>>0;t=t*435+l+r*256>>>0,r=i}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function Qc(e){return`${Gc}${Yc(e)}`}function Zc(e){return e?JSON.stringify(e):null}async function Jc(e,t){try{let r=await e.getItem(Qc(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 Xc(e,t,r){try{r===null?await e.removeItem(Qc(t)):await e.setItem(Qc(t),r)}catch{}}function ed(e,t){let r;return{restore(r){Jc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=Zc(n);l!==r&&(r=l,Xc(e,t,l))}}}function td(){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 rd(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:td(),store:null,disposed:false}}function nd(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function ld(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 id(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:od(r,n,t))}catch{}}})}function od(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...It(r,l,i),...t}}function ad(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:(l,i)=>n.call(e,l,i??It(t,r,l.requestId))}:{}}}var sd=/* @__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 ${At} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function ud(e,t,r=jt){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. `+sd[r])}function cd(e){/* @__PURE__ */
|
|
48
|
+
return Object.freeze({request(){return Promise.resolve(err(nd(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 dd=/* @__PURE__ */new WeakSet;function fd(){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 dd.add(t),t}var hd=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new gd(e,t)}var pd=6e4,gd=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 Z("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:Et,platform:t?.platform??jt,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ot(r?.appVersion)}),this.telemetry=r.telemetry?id(r.telemetry,this.errorContext):$e,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=cd(l);else if(r.transport!==void 0)o=r.transport;else{let e=ld(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=cd(e.failure))}if(this.configFailure=l,this.reportsDeviceTimezone=l===null&&(t?.reportDeviceTimezone??!i),this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Hi(this,this.mintScope),this.transport=o,l!==null&&(ud(l,this.telemetry,t?.platform),this.emit({type:"error",code:nd(l).code,requestId:null,context:It(this.errorContext,"runtime",null)})),this.errorPolicy=ad(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??Ve,this.upload=r.upload??Qr,this.uploadTransport=r.uploadTransport??hl,this.imageCache=r.imageCache??hd,this.kv=r.storage??fd(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?qc():qc(()=>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:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",bd(e),()=>this.buildChatController(e),md),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${bd(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=Ac({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Dc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=ed(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=l===null?rd({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Ki(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,t=>{this.armTokenRefresh(r,t),this.reportsDeviceTimezone&&!this.disposed&&r===this.identity&&Xi(`${this.mintScope}|${e.userRef}`,this.buildAuth(e.userRef))},()=>{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-pd,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||Di(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 l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Zc(l)===Zc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??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,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}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:ad(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 Wc(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:()=>$c({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Ni(Ui(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(yd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&qi(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 l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?yd("prepare"):r===null?null:nd(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(et(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:It(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
49
|
+
return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}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",bd(t),()=>this.buildChatController(t),md,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 bd(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function md(e){e.dispose()}function yd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function vd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function kd(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 wd(e){return e.ok?e:err(kd(e.error))}function Cd(e){return{send:async(...t)=>wd(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Sd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),xd=globalThis,_d=xd[Sd]??(xd[Sd]=createContext(null));_d.displayName??="EverfurContext";function Rd(){let e=o(_d);if(e===null)throw new Z("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return Rd().handle}var Td=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Id=globalThis,zd=Id[Td]??(Id[Td]=createContext(ga));zd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(zd)}var Pd=()=>()=>{},Od=()=>null;function Ed(e,t){return i(t?.subscribe??Pd,t?.get??Od,t?.get??Od)??e}function EverfurThemeProviderCore(e){let{runtime:t}=Rd(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?jd(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=Ed(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!Fd(k)||Ba(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(zd.Provider,{value:v},e.children)}function jd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function Fd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:u,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=c(null),b=c(null),m=c(t?.onEvent);m.current=t?.onEvent;let y=c(e=>{m.current?.(e)}),[v,k]=d(e=>e+1,0),w=c(null),C=c(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=c(null),R=c(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:Ad(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=c(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;f(()=>{z.setUser(x)},[z,O]),f(()=>{z.setActivePet(I)},[z,I]);let E=c(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,Dd(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:Md(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:u});return r(_d.Provider,{value:F},h.wrap?h.wrap(A):A)}function Ad(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Dd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Md(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Ld=2;function Bd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Ld)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Hd(){let e=N;return(t,r)=>{let n=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]?.tap?.(t,r),l=new e(t,{method:r.method,headers:n?{...r.headers,...n.headers}:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return n?.watch(l),Object.assign(l,{getResponseHeader:e=>Bd(l,e)})}}function Ud(){let e=w();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 $d(){let[e,t]=l(false);return n(()=>{let e=true,r=k?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(k);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=k?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Wd(){let e=S?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(S);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Vd(e){let t=C?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(C,"change",e);return()=>r?.remove?.()}function qd(){return i(Vd,Wd,Wd)}function Gd(){try{let e=m?.OS;return typeof e=="string"?e:null}catch{return null}}function Kd(){return Gd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Yd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Kd(),l=k?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(k);Nd(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=k?.addEventListener,o=typeof i=="function"?i.call(k,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function Qd(){return Gd()==="ios"?"Menlo":oa}function Zd(){return globalThis.__DEV__!==false}var Jd=/* @__PURE__ */new Set;function Xd(e){if(!Zd()||Jd.has(e))return;Jd.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 ef(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 l=n.includes(e);return l||Xd(e),l}var tf=/* @__PURE__ */new Set;function rf(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 nf=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function lf(e){if(!Zd())return;let t=rf(e).filter(e=>!tf.has(e));if(t.length===0)return;for(let e of t)tf.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>nf[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 of(e){n(()=>{try{lf(e)}catch{}},[e])}var af=/* @__PURE__ */Object.freeze({useColorScheme:Ud,useReducedMotion:$d,useTextScale:qd,useHighContrast:Yd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:Qd,isFontRegistered:ef,useResolvedTheme:of,isDevelopment:Zd});function sf(e){return r(H,null,e)}var uf=/* @__PURE__ */Object.freeze({platform:"react-native",...m.OS==="web"?{}:{eventSourceFactory:Hd()},wrap:sf,theme:af});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:uf})}function useCapability(e){let{runtime:t}=Rd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function cf(e){let{runtime:t}=Rd(),r=t.entitlements,n=u(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=u(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var df=/* @__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[df[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[df[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function ff(e){return e<=450?"regular":e<=650?"medium":"bold"}var hf={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=pf.get(e);r===void 0&&(r=/* @__PURE__ */new Map,pf.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=gf(e,t);return r.set(t,l),l}var pf=/* @__PURE__ */new WeakMap;function gf(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=ff(Number(n)),i=r.face==="mono"?face(e,hf[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function bf(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=bf(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(R,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var mf=t(function(e,t){return r(y,{...e,...t===null?{}:{ref:t}})});var yf=class extends h{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:t,resetKey:n}){return r(yf,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var vf=48;function kf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>kf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */$(HostRender,{render:l,fallback:/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */$(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */$(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */$(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>wf(r),[r]);/* @__PURE__ */
|
|
50
|
+
return $(x,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */$(x,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>wf(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
|
|
51
|
+
return $(x,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */$(Text,{style:n.offstateText,children:l}):null})}function wf(e){let{color:t,space:r,radius:n,type:l}=e;return v.create({offstate:{minHeight:vf,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:v.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:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}var Cf=createContext(null);function TelevetHostOutlet(){let e=o(Cf);return e===null?null:/* @__PURE__ */$(e,{})}var Sf=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function xf(){let e=globalThis,t=e[Sf];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[Sf]=r,r}function _f(e){let t=xf();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function Rf(e){let t=xf().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 Tf(e){let t=xf();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function If(){return xf().snapshot}function zf(){return xf().hosts.length>0}function Pf(e){if(!zf())return false;let t=/* @__PURE__ */Object.freeze({...e});return _f({request:t,serial:xf().snapshot.serial+1}),true}function Of(){xf().snapshot.request!==null&&_f({request:null})}function Ef(){let e=xf(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],_f({activeHost:e.hosts[0]??null}),t}function jf(e){let t=xf();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;_f(r===null?{activeHost:r,request:null}:{activeHost:r})}function Ff(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 Af(e){let[t,r]=l(null);n(()=>{let e=Ef();return r(e),()=>{jf(e)}},[]);let o=i(Tf,If,If),a=t!==null&&o.activeHost===t?o.request:null,[s,u]=l(null),c=a!==null&&s===null;return n(()=>{if(!c)return;let t=true;return e().then(e=>{t&&u(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),Of())}),()=>{t=false}},[c,e]),a===null||s===null?null:{module:s,request:a,serial:o.serial,dismiss:Of}}var Df=Ff(()=>Promise.resolve(q));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=Af(Df);if(l===null)return null;let{EverfurTelevetModal:i}=l.module;/* @__PURE__ */
|
|
52
|
+
return $(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var Mf=640,Lf=600,Bf=/* @__PURE__ */Object.freeze({width:0,height:0}),Hf="useWindowDimensions"in b&&typeof b.useWindowDimensions=="function"?b.useWindowDimensions:()=>Bf,Uf=/* @__PURE__ */Object.freeze({width:"100%",maxWidth:Mf,alignSelf:"center"});/* @__PURE__ */Object.freeze({...Uf,flex:1});var Nf=/* @__PURE__ */Object.freeze({...Uf,flexGrow:1,flexShrink:1});function $f(){return Hf().width>=Lf}function Wf(e="flow"){let{width:t}=Hf();if(t<Lf)return null;if(e==="flow")return Uf;let r=Math.max(0,Math.round((t-Mf)/2));return{left:r,right:r}}function Vf(e,t){return t===null?e:[e,t]}var qf=/* @__PURE__ */Symbol.for("@everfur/sdk#InSdkColumn@v1"),Gf=globalThis,Kf=Gf[qf]??(Gf[qf]=createContext(false));Kf.displayName??="EverfurInSdkColumn";function SdkTabletColumn({children:e,style:t,testID:r}){let n=$f(),l=o(Kf);return!n||l?e:/* @__PURE__ */$(x,{style:t===void 0?Nf:[Nf,t],testID:r??"everfur-tablet-column",children:/* @__PURE__ */$(Kf.Provider,{value:true,children:e})})}var Yf="Go to the nearest emergency vet now.";var Qf=/* @__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:Yf,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 Zf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function Jf(e){return e?.trim()||Qf.emptyTitlePetFallback}function Xf(e,t){return Zf(e,{petName:Jf(t)})}var eh="tel:+18884264435";var th=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function rh(e){let t=th(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var nh=6;function lh(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function ih(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
|
|
53
|
+
return Object.freeze(n)}function oh(e){let t=th(e.title,80),r=th(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function ah(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=rh(e);t!==null&&r.length<nh&&r.push(t)}let n=ih(t.doses,e=>{let t=th(e.label,60),r=th(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:lh(e.minLb??e.min_lb),maxLb:lh(e.maxLb??e.max_lb)})},nh),l=ih(t.details,oh,nh),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?oh(i):null,a=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,s=/* @__PURE__ */Object.freeze({kicker:th(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:th(t.fine,300),fit:a});return s.kicker===null&&r.length===0&&n.length===0&&l.length===0&&s.fine===null&&a===null?void 0:s}var sh=128;var uh=/* @__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"]),ch=/* @__PURE__ */new Set(["y","c","g","r"]),dh=/* @__PURE__ */new Set(["done","now","next"]),fh=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,hh=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,ph=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,gh=e=>typeof e=="string"&&uh.has(e)?e:null;function bh(e){let t=hh(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var mh=e=>typeof e=="number"&&Number.isInteger(e)?String(e):hh(e,sh);function yh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function vh(e){/* @__PURE__ */
|
|
54
|
+
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function kh(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let l of e){if(n.length>=r)break;let e=t(l);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var wh=(e,t=12,r=300)=>kh(e,e=>hh(e,r),t);function Ch(e){let t=fh(e),r=hh(t?.kicker,120),n=hh(t?.title,300);if(t===null||r===null||n===null)return null;let l=fh(t.risk),i=fh(t.odds),o=fh(t.quote),a=fh(t.jump);return vh({kicker:r,title:n,sources:kh(t.sources,e=>{let t=hh(fh(e)?.label,60);return t===null?null:vh({label:t,kind:ph(fh(e)?.kind)})},6),risk:hh(l?.lead,300)===null?null:vh({lead:hh(l?.lead,300),body:hh(l?.body),kind:ph(l?.kind)}),odds:hh(i?.label,120)===null||hh(i?.from,20)===null||hh(i?.to,20)===null?null:vh({label:hh(i?.label,120),tag:hh(i?.tag,40),from:hh(i?.from,20),to:hh(i?.to,20),toLabel:hh(i?.toLabel,120)}),quote:hh(o?.text)===null?null:vh({kicker:hh(o?.kicker,120),tag:hh(o?.tag,40),text:hh(o?.text)}),jump:hh(a?.title,300)===null||hh(a?.go,60)===null?null:vh({title:hh(a?.title,300),go:hh(a?.go,60)}),report:Sh(t.report)})}function Sh(e){let t=fh(e),r=hh(t?.label,120),n=hh(t?.text,1200);return r===null||n===null?null:vh({label:r,text:n,actions:wh(t?.actions,5,300)})}function xh(e){let t=fh(e),r=hh(t?.title,300),n=kh(t?.steps,e=>{let t=fh(e),r=hh(t?.title,300),n=t?.tone;return r===null?null:vh({title:r,body:hh(t?.body),source:hh(t?.source,200),tone:typeof n=="string"&&ch.has(n)?n:null,icon:gh(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:vh({title:r,label:hh(t?.label,60),steps:n})}function _h(e){let t=fh(e),r=hh(t?.title,300);if(t===null||r===null)return null;let n=fh(t.rating),l=fh(t.reviews),i=fh(t.why),o=fh(i?.score),a=fh(t.dose),s=fh(t.ingredients),u=kh(l?.items,e=>{let t=fh(e),r=t?.stars,n=hh(t?.text),l=hh(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:vh({stars:Math.round(r),text:n,by:l})},5),c=kh(i?.rows,e=>{let t=fh(e),r=hh(t?.chip,40),n=hh(t?.title,300);return r===null||n===null?null:vh({chip:r,kind:ph(t?.kind),title:n,body:hh(t?.body)})}),d=kh(a?.stats,e=>{let t=fh(e),r=hh(t?.value,40),n=hh(t?.label,120),l=t?.kind;return r===null||n===null?null:vh({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=wh(s?.items,12,80);return vh({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:mh(t.productId),partnerSku:hh(t.partnerSku,200),rating:hh(n?.value,20)===null?null:vh({value:hh(n?.value,20),label:hh(n?.label,120)}),line:hh(t.line),reviews:hh(l?.label,200)===null||u===null?null:vh({label:hh(l?.label,200),items:u}),checkoutLine:hh(t.checkoutLine,300),why:hh(i?.title,200)===null||c===null?null:vh({title:hh(i?.title,200),rows:c,score:hh(o?.text,200)===null||hh(o?.value,20)===null?null:vh({text:hh(o?.text,200),value:hh(o?.value,20)})}),dose:hh(a?.title,200)===null||d===null?null:vh({title:hh(a?.title,200),stats:d,note:hh(a?.note)}),doseLabel:hh(t.doseLabel,120),ingredients:f===null?null:vh({label:hh(s?.label,200),items:f}),proof:hh(t.proof,300),trust:kh(t.trust,e=>{let t=fh(e),r=gh(t?.icon),n=hh(t?.label,120);return r===null||n===null?null:vh({icon:r,label:n})},6),more:hh(t.more,120),fine:hh(t.fine),checkin:hh(t.checkin,200),detail:ah(t.detail)??null})}function Rh(e){let t=fh(e),r=hh(t?.title,200),n=kh(t?.items,e=>{let t=fh(e),r=hh(t?.title,300),n=hh(t?.body);return r===null||n===null?null:vh({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:vh({title:r,items:n})}function Th(e){let t=fh(e),r=hh(t?.title,200),n=wh(t?.questions,12,300),l=hh(t?.add,80),i=hh(t?.added,80);return r===null||n===null||l===null||i===null?null:vh({title:r,questions:n,add:l,added:i})}function Ih(e){let t=fh(e),r=hh(t?.title,200),n=kh(t?.items,e=>{let t=fh(e),r=hh(t?.key,sh),n=hh(t?.title,300),l=hh(t?.action,80),i=mh(t?.productId),o=hh(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:vh({key:r,productId:i,title:n,body:hh(t?.body),price:hh(t?.price,40),was:hh(t?.was,40),tag:hh(t?.tag,40),imageUrl:bh(t?.imageUrl),icon:gh(t?.icon),kind:ph(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:ah(t?.detail)??null})},6);return r===null||n===null?null:vh({title:r,items:n})}function zh(e){let t=fh(e),r=hh(t?.kicker,120),n=hh(t?.title,120);return t===null||r===null||n===null?null:vh({kicker:r,title:n,icon:gh(t.icon),track:kh(t.track,e=>{let t=fh(e),r=hh(t?.title,120),n=t?.state;return r===null?null:vh({title:r,detail:hh(t?.detail,120),state:typeof n=="string"&&dh.has(n)?n:null,tag:hh(t?.tag,40)})},6),heading:hh(t.heading,200),rows:kh(t.rows,e=>{let t=fh(e),r=gh(t?.icon),n=hh(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return vh({icon:r,label:n,text:"",fromVet:true});let l=hh(t?.text,300);return l===null?null:vh({icon:r,label:n,text:l})},6),note:hh(t.note,300),action:hh(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=fh(e),r=hh(t?.title,300),n=_h(t?.pick);if(t===null||r===null||n===null)return null;let l=fh(t.byline);return vh({eyebrow:hh(t.eyebrow,120),title:r,subtitle:hh(t.subtitle,300),subtitleNoRecords:hh(t.subtitleNoRecords,300),headImageUrl:bh(t.headImageUrl),byline:hh(l?.name,120)===null?null:vh({name:hh(l?.name,120),role:hh(l?.role,120),imageUrl:bh(l?.imageUrl),shortName:hh(l?.shortName,60)}),focus:Ch(t.focus),routine:xh(t.routine),pick:n,signs:Rh(t.signs),checkup:Th(t.checkup),extras:Ih(t.extras),wait:zh(t.wait),fine:hh(t.fine),checkoutRows:kh(t.checkoutRows,e=>{let t=fh(e),r=gh(t?.icon),n=hh(t?.label,60),l=hh(t?.value,200);return r===null||n===null||l===null?null:vh({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=fh(e);if(r===null||!("page"in r))return null;let n=fh(r.pet),l=n?.sex;/* @__PURE__ */
|
|
55
|
+
return Object.freeze({petRef:hh(r.pet_ref,sh)??t,pet:/* @__PURE__ */Object.freeze({name:hh(n?.name,120),species:hh(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:hh(n?.breed,120),weightKg:yh(n?.weight_kg),weightLb:yh(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 Ph(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Oh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function Eh(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var jh=e=>typeof e=="string"&&e.length>0&&e.length<=sh;function Fh(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function Ah(e,t,r){if(!jh(t))return err(Ph("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${Fh(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(Oh("healthPlan.page.read")):ok(l)}var Dh=/* @__PURE__ */new WeakMap;function Mh(e){let t=Dh.get(e);if(t!==void 0)return t;let r=Lh(e);return Dh.set(e,r),r}function Lh(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(Eh("getPage")));let{services:n}=e.registry,l=Cd(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return Ah(l,t,r)}}}function Bh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function Hh(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Uh(e,...t){if(typeof e=="function")try{let r=e(...t);return Hh(r)&&Promise.resolve(r).then(void 0,Bh),r}catch(e){Bh(e);return}}var Nh=/* @__PURE__ */new WeakMap;function $h(e){if(typeof e!="function")return;let t=Nh.get(e);if(t!==void 0)return t;let r=(...t)=>{Uh(e,...t)};return Nh.set(e,r),r}function Wh(e,...t){let r;try{r=e(...t)}catch(e){return Bh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Vh=6e4;function qh({lifecycle:e,refreshKey:t,readyAt:r,revalidate:l,refresh:i,now:o=Date.now}){let a=c({readyAt:r,revalidate:l,refresh:i??l,now:o});a.current={readyAt:r,revalidate:l,refresh:i??l,now:o},n(()=>{if(e==null)return;let t=Uh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=a.current;e!==null&&r()-e>=Vh&&t()}));return()=>{typeof t=="function"&&Uh(t)}},[e]);let s=c(t);n(()=>{Object.is(s.current,t)||(s.current=t,a.current.refresh())},[t])}var Gh=Vh,Kh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function Yh(){let e=globalThis,t=e[Kh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[Kh]=r,r}function Qh(e,t,r,n,l){let i=Yh(),o=i.get(t);o===void 0&&(o=/* @__PURE__ */new Map,i.set(t,o));let a=o,s=`${r}\0${n}`,u=a.get(s);if(!l&&u!==void 0&&(u.at===null||Date.now()-u.at<Gh))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(a.get(s)===c&&(e.ok||vd(e.error)?c.at=Date.now():a.delete(s)),e))};return a.set(s,c),c.promise}function useHealthPlanPage(e){let{userRef:t,runtime:r}=Rd(),i=a(()=>Mh(r),[r]),o=e.repository,s=o??i,d=u((e,n)=>o!==void 0||t==null?s.getPage(e):Qh(i,r,t,e,n),[o,s,i,r,t]),{petRef:f}=e,h=e.enabled!==false&&t!=null&&f!==null,[p,g]=l({phase:"idle",petRef:null,page:null,error:null}),b=c(0),m=c(0),y=u(async e=>{let t=++b.current;if(!h||f===null){g(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}g(e=>({phase:"loading",petRef:f,page:e.petRef===f?e.page:null,error:null}));let r=await d(f,e);t===b.current&&(r.ok?g({phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}):vd(r.error)?g({phase:"ready",petRef:f,page:null,error:null,missing:true,readyAt:Date.now()}):g({phase:"failed",petRef:f,page:null,error:r.error}))},[h,f,d]),v=u(()=>y(true),[y]),k=p.phase==="ready"&&p.petRef===f,w=u(async()=>{if(!h||f===null||!k)return;let e=b.current,t=++m.current,r=await d(f,true);e!==b.current||t!==m.current||!r.ok||g(e=>e.phase==="ready"&&e.petRef===f?{phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}:e)},[h,f,k,d]);qh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:k?p.readyAt??null:null,revalidate:()=>{w()},refresh:()=>{k?w():v()}}),n(()=>(y(false),()=>{b.current+=1}),[y]);let C=h&&p.petRef!==f;return a(()=>({phase:C?"loading":p.phase,page:C?null:p.page,error:C?null:p.error,missing:!C&&p.missing===true,refresh:v}),[C,p,v])}var Zh=/* @__PURE__ */Object.freeze({branding:null}),Jh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>Zh});function Xh(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function ep(e){let{runtime:t}=Rd(),r=t?.entitlements??Jh,n=u(()=>r.getSnapshot()?.branding??null,[r]),l=Ed(i(r.subscribe,n,n),t?.sdkConfigHost?.branding),o=Xh(e);return a(()=>{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 tp(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function rp(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function np(e){let t=ft(e);return t===null?null:{reached:Qf.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function lp(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function ip(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=lp(r),n=t==="web",l=np(r);return{tone:"error",title:l!==null?l.reached:e?Qf.turnUnreachableTitle:n?Qf.turnFailedTitleWeb:Qf.turnFailedTitle,body:r.displayMessage,actionLabel:e?Qf.turnStartNewChat:n?Qf.retry:Qf.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:Qf.turnStoppedTitle,body:Qf.turnStoppedBody,actionLabel:Qf.turnRetry,action:"retry"}:null}function op(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var ap=3,sp=/* @__PURE__ */Object.freeze([]);function up(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return sp;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===ap))break}/* @__PURE__ */
|
|
56
|
+
return Object.freeze(n)}var cp=5;function dp(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 fp(e,t){if(t===void 0)return up(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return sp;let n=Math.max(1,Math.min(cp,Math.floor(t.count??ap))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),a=[],s=e=>{let r=e.trim(),l=i(r);a.length>=n||l.length===0||o.has(l)||dp(t.exclude,r)||(o.add(l),a.push(r))};for(let t of e.suggestedPrompts)s(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&s(e);/* @__PURE__ */
|
|
57
|
+
return Object.freeze(a)}function hp(e){return e.sender?.displayName??Qf.senderVet}function pp(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var gp=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 bp(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 mp(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===ap&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>gp.test(e)||bp(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var yp="pet_not_registered";function vp(e){return e!=null&&e.reasonCode===yp}var kp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function wp(e,t,r){let{runtime:i,userRef:o,scopeEpoch:s}=Rd(),d=u((e,t)=>{let r=i.registry.services.authFor(o);return Ni(Ui(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,s]),f=a(()=>t===void 0?null:$i(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=c(0),b=c(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${s}|${e}|${f}`,y=u(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=u(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?kp:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var Cp=/* @__PURE__ */Object.freeze({});function Sp(e){let[t,r]=l(Cp),i=c(null),o=c([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===Cp?e:Cp);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let s=u(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:s}),[t,s])}var xp=/* @__PURE__ */new WeakSet;function _p(){let e=makeEverfurError("internalError",{retryable:true});return xp.add(e),err(e)}function Rp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&xp.has(t)}var Tp=500;function Ip(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,Tp):null}function zp(e,t,r,l){let i=Ip(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=c(e);a.current=e;let s=c(null),u=c(null),d=c(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||u.current===o)return;let e=a.current;if(e===void 0)return;u.current=o;let r=e=>{u.current===o&&(u.current=null),!Rp(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var Pp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Op=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Ep=/* @__PURE__ */Object.freeze({...Pp,markRead:true}),jp=/* @__PURE__ */Object.freeze({...Op,markRead:true});function Fp(e,t){return e?t?Ep:Pp:t?jp:Op}function Ap(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Uh(()=>r()!==!1)===true}function Dp(e,t){let r=c({target:e,isVisible:t});r.current={target:e,isVisible:t};let l=c(e.isStreaming);n(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:n,isVisible:i}=r.current;n.status!=="complete"||n.conversationId===null||n.unreadCount===null||!i()||n.markRead()},[e.isStreaming])}var Mp=3e5;function Lp(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 Bp(e,t,r){let l=c(t);l.current=t;let i=c(null),o=c(null),a=c(false),s=c(0),u=c(0),d=c(3e4),f=()=>e?.isOffline===void 0?false:Uh(()=>e.isOffline?.()===!0)===true,h=f(),p=c(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:c}=l.current,h=Yr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:c===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,Lp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,Mp),u.current=Date.now()+s.current):(s.current=0,u.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=Uh(()=>e(()=>{p.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)Uh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{Date.now()<u.current||Ap(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var Hp=/^efch_[A-Za-z0-9_-]{43}$/,Up="efch";function Np(e){return typeof e=="string"&&Hp.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(`${Up}=`))continue;let e=r.slice(Up.length+1);return Np(e)?e:null}return null}var $p=128,Wp=/[\u0000-\u001f\u007f]/;function Vp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function qp(e){return typeof e!="string"||e.length===0||e.length>$p||Wp.test(e)||e.includes("://")?null:e}function Gp(e){if(e===null)return null;let t=e.conversation_id,r=qp(e.pet_ref);return typeof t!="string"||!Dn(t)||r===null?null:{conversationId:t,petRef:r}}function Kp(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(Gp(Vp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(sn("internalError",false))):Promise.resolve(ok(null))}function Yp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=Np(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return Kp(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function Qp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function Zp(e,t,r){let l=Qp(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=c({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let u=c(null),d=c(null),f=r.petRef;n(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(u.current=l);return}i&&!r.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var Jp=/* @__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 Xp(e){let t=e?.replace(/\s+/g," ").trim();return t||Jp.untitled}function eg(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function tg(e){let t=eg(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Jp.newReply.replace("{date}",t):t}function rg(e,t){return t?`${Jp.countLabel}${Jp.countSeparator}${e}`:Jp.countLabel}function ng(e){return`${e.unreadCount!==null&&e.unreadCount>0?Jp.unreadPrefix:""}${Jp.openConversation} ${Xp(e.title)}`}function lg(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function ig(e,t){let r=lg(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=lg(Xp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function og(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function ag(e){let[t,r]=l(false),[i,o]=l(""),s=e.listConversations,d=c(0),[f,h]=l(()=>og(s)),p=f.scope===s?f:og(s);n(()=>(d.current+=1,r(false),o(""),h(og(s)),()=>{d.current+=1}),[s]);let g=u(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:s,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===s?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:s,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,s]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>ig(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var sg="#111111",ug="#FFFFFF",cg=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:sg,pillColor:ug,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:sg,pillColor:ug,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:sg,pillColor:ug,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:sg,pillColor:ug,showsVetAction:false})});function dg(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function fg(e){return Zf(Qf.urgencyGeneralReason,{petName:e?.trim()||Qf.emptyTitlePetFallback})}function hg(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 l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:pg(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:fg(t)}:null}return null}function pg(e){return typeof e=="string"&&e.trim().length>0?e:null}function gg(e){let t=e===null?null:dg(e),[r,i]=l(null),[o,s]=l(false);n(()=>s(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:cg[e.level],f=e!==null&&!c&&e.level!=="general",h=u(()=>{t!==null&&i(t),s(false)},[t]),p=u(()=>s(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:Zf(Qf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var bg=()=>globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]??={loader:null,lazy:null};var mg=bg;function registerEverfurChatCards(e){let t=mg();t.loader=e;let r=e&&Promise.resolve().then(e).then(e=>typeof e.ServerCards=="function"?e.ServerCards:NONE3,()=>NONE3);t.lazy=r&&s(async()=>({default:await r}))}var NONE3=()=>null,yg=createContext(null);function ServerCardsSlot({message:e}){let t=o(yg),n=mg(),l=e.a2ui??n.frames?.get(e.responseId),i=n.lazy;return l===void 0||t===null||i===null?null:r(g,{fallback:null},r(i,{message:e,a2ui:l,host:t}))}var vg="everfur.com",kg=2048,wg=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Cg(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&&wg.test(e)&&t.add(e)}/* @__PURE__ */
|
|
58
|
+
return Object.freeze([...t])}function Sg(e,t){if(e===vg||e.endsWith(`.${vg}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function xg(e,t){if(typeof e!="string"||e.length===0||e.length>kg||!/^https:\/\//i.test(e))return null;let r=Se(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:Sg(r.hostname,t)?r.href:null}function _g(e){try{Promise.resolve(T.openURL(e)).catch(()=>{})}catch{}}var Rg=createContext(null);function Tg(){return o(Rg)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:t,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=a(()=>{if(l===null)return null;let e=Cg(l===""?[]:l.split(`\n`));/* @__PURE__ */
|
|
59
|
+
return Object.freeze({hosts:e,open:t!==void 0?e=>{Uh(t,e,"message")}:_g})},[l,t]);return r(Rg.Provider,{value:i},n)}var Ig={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function zg(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function Pg(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l={width:e*.82,height:n,borderRadius:n,backgroundColor:t};/* @__PURE__ */
|
|
60
|
+
return W(x,{style:[zg(e),{gap:e*.22}],...Ig,children:[
|
|
61
61
|
/* @__PURE__ */$(x,{style:l}),
|
|
62
62
|
/* @__PURE__ */$(x,{style:l}),
|
|
63
|
-
/* @__PURE__ */$(x,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=
|
|
64
|
-
return W(x,{style:[
|
|
63
|
+
/* @__PURE__ */$(x,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=Pg(e,r),i=e*.78;/* @__PURE__ */
|
|
64
|
+
return W(x,{style:[zg(e),{transform:[{rotate:n}]}],...Ig,children:[
|
|
65
65
|
/* @__PURE__ */$(x,{style:{position:"absolute",width:i,height:l,borderRadius:l,backgroundColor:t}}),
|
|
66
66
|
/* @__PURE__ */$(x,{style:{position:"absolute",width:l,height:i,borderRadius:l,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
|
|
67
67
|
return $(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
|
|
68
|
-
return $(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
69
|
-
return $(x,{style:
|
|
70
|
-
return $(x,{style:
|
|
71
|
-
return W(x,{style:[
|
|
68
|
+
return $(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
69
|
+
return $(x,{style:zg(e),...Ig,children:/* @__PURE__ */$(x,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}var Og={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:r,direction:n}){let l=Pg(e,r),i=e*.46,o=Og[n];/* @__PURE__ */
|
|
70
|
+
return $(x,{style:zg(e),...Ig,children:/* @__PURE__ */$(x,{style:{width:i,height:i,borderRightWidth:l,borderBottomWidth:l,borderColor:t,marginTop:i*o.marginTop,marginLeft:i*o.marginLeft,transform:[{rotate:o.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};/* @__PURE__ */
|
|
71
|
+
return W(x,{style:[zg(e),{flexDirection:"row",gap:1}],...Ig,children:[
|
|
72
72
|
/* @__PURE__ */$(x,{style:[l,{borderTopLeftRadius:e*.2}]}),
|
|
73
|
-
/* @__PURE__ */$(x,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
74
|
-
return W(x,{style:
|
|
73
|
+
/* @__PURE__ */$(x,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e*.5;/* @__PURE__ */
|
|
74
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
75
75
|
/* @__PURE__ */$(x,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
|
|
76
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
77
|
-
return W(x,{style:
|
|
76
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e*.6,i={position:"absolute",width:l,height:l,borderWidth:n,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
|
|
77
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
78
78
|
/* @__PURE__ */$(x,{style:[i,{top:0,left:0}]}),
|
|
79
|
-
/* @__PURE__ */$(x,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=
|
|
80
|
-
return W(x,{style:[
|
|
79
|
+
/* @__PURE__ */$(x,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=Pg(e,r),o=n?t:"transparent";/* @__PURE__ */
|
|
80
|
+
return W(x,{style:[zg(e),{transform:[{rotate:l}]}],...Ig,children:[
|
|
81
81
|
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
|
|
82
82
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
|
|
83
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
84
|
-
return W(x,{style:[
|
|
83
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
84
|
+
return W(x,{style:[zg(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...Ig,children:[
|
|
85
85
|
/* @__PURE__ */$(x,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),
|
|
86
|
-
/* @__PURE__ */$(x,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
87
|
-
return W(x,{style:
|
|
86
|
+
/* @__PURE__ */$(x,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e*.34;/* @__PURE__ */
|
|
87
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
88
88
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.06,width:l,height:l,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),
|
|
89
89
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),
|
|
90
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
91
|
-
return W(x,{style:[
|
|
90
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
91
|
+
return W(x,{style:[zg(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...Ig,children:[
|
|
92
92
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
|
|
93
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
94
|
-
return W(x,{style:
|
|
93
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
94
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
95
95
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),
|
|
96
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */$(x,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
97
|
-
return W(x,{style:
|
|
96
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */$(x,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e/24,i=16*l+n,o=11*l-i/2,a=11+8/Math.SQRT2,s=(21-a)*Math.SQRT2*l,u=(a+21)/2*l;/* @__PURE__ */
|
|
97
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
98
98
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:o,left:o,width:i,height:i,borderRadius:i,borderWidth:n,borderColor:t}}),
|
|
99
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
100
|
-
return W(x,{style:
|
|
99
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
100
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
101
101
|
/* @__PURE__ */$(x,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),
|
|
102
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
103
|
-
return W(x,{style:
|
|
102
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e*.62;/* @__PURE__ */
|
|
103
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
104
104
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:0,width:l,height:l,borderRadius:l,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */$(x,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),
|
|
105
105
|
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.04,width:l*.5,height:l*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:r}){let n=e*.36;/* @__PURE__ */
|
|
106
|
-
return $(x,{style:
|
|
107
|
-
return $(x,{style:
|
|
108
|
-
return W(x,{style:
|
|
106
|
+
return $(x,{style:zg(e),testID:r,...Ig,children:/* @__PURE__ */$(x,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:r}){/* @__PURE__ */
|
|
107
|
+
return $(x,{style:zg(e),testID:r,...Ig,children:/* @__PURE__ */$(x,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=Pg(e,r);/* @__PURE__ */
|
|
108
|
+
return W(x,{style:zg(e),testID:n,...Ig,children:[
|
|
109
109
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:l,borderColor:t,borderRadius:e*.13}}),
|
|
110
110
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
|
|
111
111
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.74,width:l,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:r,children:n}){/* @__PURE__ */
|
|
112
|
-
return $(x,{style:[
|
|
113
|
-
return W(x,{style:
|
|
112
|
+
return $(x,{style:[zg(e),{borderRadius:e/2,borderWidth:t??v.hairlineWidth,borderColor:r}],children:n})}function ArrowUpGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=Pg(e,r),i=e*.46;/* @__PURE__ */
|
|
113
|
+
return W(x,{style:zg(e),testID:n,...Ig,children:[
|
|
114
114
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:l,borderRadius:l,backgroundColor:t}}),
|
|
115
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
116
|
-
return W(x,{style:
|
|
115
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r);/* @__PURE__ */
|
|
116
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
117
117
|
/* @__PURE__ */$(x,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:n,borderColor:t,borderRadius:e*.14}}),
|
|
118
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
119
|
-
return W(x,{style:
|
|
118
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=Pg(e,r),l=e*.72,i=e/2;/* @__PURE__ */
|
|
119
|
+
return W(x,{style:zg(e),...Ig,children:[
|
|
120
120
|
/* @__PURE__ */$(x,{style:{width:l,height:l,borderRadius:l/2,borderWidth:n,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
|
|
121
121
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}}),
|
|
122
122
|
/* @__PURE__ */$(x,{style:{position:"absolute",top:i-e*.2,left:i-n/2,width:n,height:e*.2+n/2,borderRadius:n,backgroundColor:t}}),
|
|
123
|
-
/* @__PURE__ */$(x,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var
|
|
124
|
-
return $(z,{...o,hitSlop:i??
|
|
125
|
-
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
126
|
-
/* @__PURE__ */$(x,{pointerEvents:"box-none",style:[
|
|
123
|
+
/* @__PURE__ */$(x,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var Eg=/* @__PURE__ */Object.freeze({standard:fa.standard,emphasized:fa.emphasized,exit:fa.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var jg=/* @__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}),Fg=/* @__PURE__ */Object.freeze({...jg,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 Ag(e){return e.motion.reducedMotion?Fg:jg}function Dg(e,t){return Math.max(0,t)*e.followUpStaggerMs}function Mg(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 Lg(){let e=useEverfurTheme();return Ag(e)}var Bg=8;function Hg(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function Ug(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function Ng(e){let[t,r,n,l]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let i=e;for(let r=0;r<Bg;r+=1){let r=Ug(i,t,n);if(r===0)break;i-=(Hg(i,t,n)-e)/r}return Hg(Math.min(1,Math.max(0,i)),r,l)}}var $g=Ng(Eg.standard),Wg=Ng(Eg.outQuad),Vg=Ng(Eg.out);function qg(e){let t=c(null);return t.current===null&&(t.current=new M.Value(e)),t.current}function Gg(e,t={}){let r=t.risePx??0,l=t.delayMs??0,i=qg(e>0?0:1);return n(()=>{if(e<=0){i.setValue(1);return}let t=M.timing(i,{toValue:1,duration:e,easing:Wg,useNativeDriver:true}),r=l>0?M.sequence([M.delay(l),t]):t;return r.start(),()=>r.stop()},[i,e,l]),a(()=>({opacity:i,transform:[{translateY:i.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[i,r])}function FadePresence({visible:e,inMs:t,outMs:r,style:i,children:o}){let[a,s]=l(e),u=qg(e&&t<=0?1:0);return n(()=>{if(e){s(true);let e=M.timing(u,{toValue:1,duration:Math.max(0,t),easing:$g,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(r<=0){s(false);return}let n=M.timing(u,{toValue:0,duration:r,easing:$g,useNativeDriver:true});return n.start(({finished:e})=>{e&&s(false)}),()=>n.stop()},[e,a,t,r,u]),!a&&!e?null:/* @__PURE__ */$(M.View,{style:[i,{opacity:u}],children:o})}var Kg=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function Yg(e,t){let[r]=l(()=>e?t.bubbleInMs:0),i=r>0,o=qg(i?0:1);n(()=>{if(r<=0)return;let e=M.timing(o,{toValue:1,duration:r,easing:Vg,useNativeDriver:true});return e.start(),()=>e.stop()},[r,o]);let s=t.bubbleFromScale,u=t.bubbleRisePx;return a(()=>i?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[u,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Kg,[i,o,u,s])}function Qg(e){let t=c(null),r=c(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let l=t.current===null;t.current=new Map(e.map(e=>[e.id,l&&e.pending===true])),r.current=n}let l=t.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return u(e=>l.get(e)===true,[l])}var Zg=12;function PressScale({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:l,hitSlop:i,...o}){let a=Lg(),s=qg(1),c=u(e=>{a.pressMs<=0||a.pressScale===1||M.timing(s,{toValue:e,duration:a.pressMs,easing:$g,useNativeDriver:true}).start()},[s,a.pressMs,a.pressScale]);/* @__PURE__ */
|
|
124
|
+
return $(z,{...o,hitSlop:i??Zg,style:t,onPressIn:e=>{c(a.pressScale),n?.(e)},onPressOut:e=>{c(1),l?.(e)},children:/* @__PURE__ */$(M.View,{style:[e,{transform:[{scale:s}]}],children:r})})}function Jg(e,t,r){let i=t&&r.revealTickMs>0,[o,a]=l(0),s=c(e);return s.current=e,n(()=>{if(!i)return;let e=setInterval(()=>{a(e=>Mg(r,e,s.current.length))},r.revealTickMs);return()=>clearInterval(e)},[i,r]),i?e.slice(0,Math.min(o,e.length)):e}var Xg=false;function eb(e){e.layoutMs<=0||(Xg||(Xg=true,m.OS==="android"&&typeof A.setLayoutAnimationEnabledExperimental=="function"&&A.setLayoutAnimationEnabledExperimental(true)),D.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function tb(e,t){let r=c(e);r.current!==e&&(r.current=e,eb(t))}var rb=36,nb=22,lb=12,ib=12,ob=16,ab="#000",sb="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:r}){let n=useEverfurTheme(),l=U();return e===null?null:/* @__PURE__ */W(O,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[
|
|
125
|
+
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Qf.closePreview,style:ub.backdrop,onPress:r,children:/* @__PURE__ */$(F,{source:{uri:e},style:ub.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
|
|
126
|
+
/* @__PURE__ */$(x,{pointerEvents:"box-none",style:[ub.closeWrap,{top:l.top+ib}],children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.closePreview,hitSlop:lb,style:ub.closeButton,onPress:r,children:/* @__PURE__ */$(CloseGlyph,{size:nb,color:n.color.surface,strokeWidth:2})})})]})}var ub=v.create({backdrop:{flex:1,backgroundColor:ab,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:ob},closeButton:{width:rb,height:rb,borderRadius:rb/2,backgroundColor:sb,alignItems:"center",justifyContent:"center"}});var cb=()=>{};function db(){try{return _.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let r=_.currentState==="background";t=_.addEventListener("change",t=>{t==="background"?r=!0:t==="active"&&r&&(r=!1,e())})}catch{return cb}return()=>t.remove()},isVisible:db}}function fb(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 hb(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function pb(e){return e?.textColor===void 0?{}:{color:e.textColor}}function gb(e){switch(e.code){case"too_large":return Zf(Qf.attachmentTooLarge,{max:formatBytes(bl),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return Zf(Qf.attachmentTooMany,{max:ml});case"unsupported_type":return Zf(Qf.attachmentUnsupported,{filename:e.filename});case"network":return Qf.attachmentNetwork;case"server":return Zf(Qf.attachmentServer,{status:""});case"cancelled":return Qf.attachmentCancelled;case"rate_limited":return Qf.attachmentRateLimited;case"quota_exceeded":return Qf.attachmentQuota;case"idempotency_conflict":return Qf.attachmentConflict;case"unknown":return Qf.attachmentUnknown}}function bb(e,t){return Zf(e>=t?Qf.attachmentsFull:Qf.addAttachment,{used:e,total:t})}var mb=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:t,userRef:r,scopeEpoch:o}=Rd(),s=e.maxPerMessage??ml,d=u(()=>{let{services:n}=t.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:n.authFor(r),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}),transport:e.transport??n.uploadTransport,maxPerMessage:s})},[t,r,o,s,e.transport]),f=a(()=>e.queue??d(),[e.queue,d]),h=c(/* @__PURE__ */new WeakSet),[p,g]=l(null),b=p!==null&&p.of===f?p.queue:f;n(()=>{if(b!==e.queue){if(h.current.has(b)){g({of:f,queue:d()});return}return()=>{b.dispose(),h.current.add(b)}}},[b,f,d,e.queue]);let m=i(b.subscribe,b.getSnapshot,()=>mb),[y,v]=l(null),k=u(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>b.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&v(r.error),t},[b,v]),w=u(e=>b.retry(e),[b]),C=u(e=>b.remove(e),[b]),S=u(()=>b.clear(),[b]),x=u(()=>v(null),[v]),_=m.attachments.some(e=>e.status==="uploading"),R=m.attachments.some(e=>e.status==="failed");return a(()=>({available:b.available,attachments:m.attachments,maxPerMessage:s,uploading:_,failed:R,blocked:_||R,s3Keys:m.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:y,add:k,retry:w,remove:C,clear:S,dismissRejected:x}),[b.available,m,s,_,R,y,k,w,C,S,x])}var yb=6e3;function vb(e,t,r){let n=t.trim();if(!n)return e;let l=e===""||/\s$/.test(e)?"":" ",i=`${e}${l}${n}`;return typeof r=="number"&&r>0?i.slice(0,r):i}function kb(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 wb(e){switch(e){case"permissionDenied":return Qf.micBlocked;case"noSpeech":return Qf.noSpeech;case"unavailable":return Qf.dictationUnavailable}}function Cb(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var Sb=["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 xb(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...Sb]){let e=(n??"").trim();if(!e)continue;let l=e.toLowerCase();if(!t.has(l)&&(t.add(l),r.push(e),r.length>=100))break}return r}function _b(e,t,r){let[i,o]=l({send:e,conversationId:t,text:r??"",seeded:r??null}),a=i.send===e&&(i.conversationId===null||i.conversationId===t);n(()=>{o(n=>{let l=n.send===e&&(n.conversationId===null||n.conversationId===t),i=l?n.text:"",o=l?n.seeded:null,a=r!=null&&r!==o&&i.length===0;return{send:e,conversationId:t,text:a?r:i,seeded:a?r:o}})},[e,t,r]);let s=u(r=>o(n=>({send:e,conversationId:t,text:r,seeded:n.seeded})),[e,t]);return[a?i.text:"",s]}function Rb(e,t,r,i,o=false){let a=c({draft:r,setDraft:i});a.current={draft:r,setDraft:i};let s=c(null),[u,d]=l(null);n(()=>{if(e===void 0)return;let r=`${t??""}`;if(s.current===r)return;s.current=r;let n=true;return(async()=>{let l=await Wh(()=>e.read(t));if(!n)return;let i=l.ok&&typeof l.value=="string"?l.value:"";i.length>0&&a.current.draft.length===0&&a.current.setDraft(i),d(r)})(),()=>{n=false}},[e,t]),n(()=>{e===void 0||o||u!==`${t??""}`||Uh(()=>e.write(t,r))},[e,t,r,u,o])}function Tb(e){if(!(m.OS!=="ios"||e===""))try{let t=k?.announceForAccessibility;typeof t=="function"&&t.call(k,e)}catch{}}function AnnounceLine({line:e}){return n(()=>{Tb(e)},[e]),null}var Ib=12,zb=80,Pb=44,Ob=22,Eb=.14,jb=18,Fb=8,Ab=/* @__PURE__ */Object.freeze({photo:Qf.attachmentPhoto,camera:Qf.attachmentCamera});function AttachmentPickerPopover({sources:e,full:t,onPick:r,onClose:n}){let l=useEverfurTheme(),i=a(()=>Db(l),[l]);/* @__PURE__ */
|
|
127
127
|
return W(x,{style:i.anchor,pointerEvents:"box-none",children:[
|
|
128
|
-
/* @__PURE__ */$(z,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:
|
|
128
|
+
/* @__PURE__ */$(z,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:Qf.closeAttachmentPicker,onPress:n}),
|
|
129
129
|
/* @__PURE__ */W(x,{style:i.bubble,children:[
|
|
130
|
-
/* @__PURE__ */$(x,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
131
|
-
/* @__PURE__ */$(x,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */$(PhotoGlyph,{size:
|
|
132
|
-
/* @__PURE__ */$(Text,{tier:"control",style:i.tileLabel,children:
|
|
130
|
+
/* @__PURE__ */$(x,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:Ab[e],accessibilityState:{disabled:t},disabled:t,containerStyle:i.tile,style:i.tileInner,onPress:()=>r(e),children:[
|
|
131
|
+
/* @__PURE__ */$(x,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */$(PhotoGlyph,{size:Ob,color:l.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */$(CameraGlyph,{size:Ob,color:l.color.brandInk,strokeWidth:1.5})}),
|
|
132
|
+
/* @__PURE__ */$(Text,{tier:"control",style:i.tileLabel,children:Ab[e]})]},e))}),
|
|
133
133
|
/* @__PURE__ */$(x,{style:i.tail}),
|
|
134
|
-
/* @__PURE__ */$(x,{style:i.tailFill})]})]})}function
|
|
135
|
-
/* @__PURE__ */$(z,{accessibilityRole:d?"button":"image",accessibilityLabel:d?
|
|
136
|
-
/* @__PURE__ */$(F,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */$(x,{style:t.uploadingOverlay,children:/* @__PURE__ */$(j,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */$(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),u?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
137
|
-
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
138
|
-
return $(x,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
139
|
-
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(
|
|
140
|
-
/* @__PURE__ */$(z,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?
|
|
134
|
+
/* @__PURE__ */$(x,{style:i.tailFill})]})]})}function Db(e){let t=e.color,r=e.radius;return v.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:Eb,shadowRadius:jb,shadowOffset:{width:0,height:Fb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:zb,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Pb,height:Pb,borderRadius:Pb/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:-Ib/2,width:Ib,height:Ib,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Ib+4,height:2,backgroundColor:t.surfaceCream}})}var Mb=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Lb=56,Bb=12,Hb=14,Ub=10,Nb=.45,$b="rgba(7,193,104,0.55)",Wb="rgba(185,28,28,0.55)",Vb=200,qb=300,Gb=20,Kb=22,Yb=12,Qb="rgba(0,0,0,0.78)",Zb=220,Jb=100,Xb="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:l,onPreview:i,style:o}){let s=useEverfurTheme(),u=a(()=>em(s),[s]);return e.length===0&&t===null?null:/* @__PURE__ */W(x,{style:[u.strip,o],children:[e.length>0?/* @__PURE__ */$(x,{style:u.cards,children:e.map(e=>/* @__PURE__ */$(PreviewCard,{row:e,styles:u,onRetry:n,onRemove:l,onPreview:i},e.id))}):null,r?/* @__PURE__ */$(Text,{style:u.rejected,accessibilityRole:"alert",children:Qf.attachmentsFailedBlocked}):null,t!==null?/* @__PURE__ */$(Text,{style:u.rejected,accessibilityRole:"alert",children:gb(t)}):null]})}function PreviewCard({row:e,styles:t,onRetry:r,onRemove:i,onPreview:o}){let a=useEverfurTheme(),s=e.status==="uploading",u=e.status==="failed",d=e.status==="uploaded",f=c(e.status),[h,p]=l(false);return n(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */W(x,{style:t.card,children:[
|
|
135
|
+
/* @__PURE__ */$(z,{accessibilityRole:d?"button":"image",accessibilityLabel:d?Zf(Qf.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:s,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:/* @__PURE__ */W(x,{style:t.thumb,children:[
|
|
136
|
+
/* @__PURE__ */$(F,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */$(x,{style:t.uploadingOverlay,children:/* @__PURE__ */$(j,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */$(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),u?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Zf(Qf.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:/* @__PURE__ */$(x,{style:t.failedInner,children:/* @__PURE__ */$(CloseGlyph,{size:Gb,color:a.color.surface,strokeWidth:2})})}):null,
|
|
137
|
+
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Zf(Qf.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>i(e.id),children:/* @__PURE__ */$(CloseGlyph,{size:Yb,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:t}){let r=useEverfurTheme(),l=Lg(),i=c(null);i.current===null&&(i.current=new M.Value(0));let o=i.current;return n(()=>{let e=M.sequence([M.timing(o,{toValue:1,duration:Vb,useNativeDriver:true}),M.delay(l.uploadFlashMs),M.timing(o,{toValue:0,duration:qb,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&t()}),()=>e.stop()},[o,l.uploadFlashMs,t]),/* @__PURE__ */$(M.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:o}],children:/* @__PURE__ */$(CheckGlyph,{size:Gb,color:r.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:t}){let r=useEverfurTheme(),n=a(()=>em(r),[r]);if(e.length===0)return null;let l=e.length===1;/* @__PURE__ */
|
|
138
|
+
return $(x,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Zf(Qf.attachedImage,{filename:e.filename}),onPress:()=>t(e),children:/* @__PURE__ */$(F,{source:{uri:e.uri},style:l?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${r}`))})}function em(e){let t=e.color,r=e.type;return v.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Lb,height:Lb,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Bb,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:v.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Mb,alignItems:"center",justifyContent:"center",backgroundColor:wo(e.color.brandInk,Nb)??e.color.brandSofter},successOverlay:{...Mb,alignItems:"center",justifyContent:"center",backgroundColor:$b},failedOverlay:{...Mb,borderRadius:Bb,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Wb},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Kb,height:Kb,borderRadius:Kb/2,backgroundColor:Qb,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Zb,height:Zb,borderRadius:Hb,backgroundColor:Xb},gridImage:{width:Jb,height:Jb,borderRadius:Ub,backgroundColor:Xb}})}var tm="chat attachment upload: the file handle has no uri",rm="chat attachment upload failed";function nm(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(tm));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(rm));return l?.aborted===true?o():De({url:t.upload_url,fields:t.upload_fields,file:nm(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var lm=300,im=3e3,om=120,am=44,sm=120,um="88%",cm=520,dm=2,fm=.5,hm=1.5,pm=1.6,gm=.6,bm=56,mm=1.5,ym=5,vm=5,km=36,wm=20,Cm=14,Sm=am,xm=4,_m=24,Rm=22,Tm=.4,Im=am,zm=20,Pm=.4,Om=480,Em=12,jm=.72,Fm=48,Am=1.5,Dm=1.3,Mm=1,Lm=1,Bm="12%",Hm=14,Um=16,Nm=28,$m=18,Wm="84%",Vm=10,qm=15,Gm=1.42,Km=4,Ym=3,Qm=14,Zm=20;function Jm(){let e=useEverfurTheme(),t=a(()=>Xm(e),[e]);return{theme:e,styles:t}}function Xm(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Math.round(l.size.body*hm),o=Math.round(l.size.body*pm),a=Math.round(wm*l.size.body/Cm),s=t.borderRingCream,u=e.slots;return v.create({container:{flex:1,minHeight:om,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:om,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:Bm,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:Om,gap:r.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:am,minWidth:am,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...fb(u.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...pb(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.md,backgroundColor:t.surfaceCream,borderWidth:Lm,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:am,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:r.xs,paddingVertical:r.md,paddingHorizontal:r.md+r.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:n.md},readingDot:{width:6,height:6,borderRadius:n.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:Ym,minHeight:Qm},readingDotInline:{width:Km,height:Km,borderRadius:n.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:am,justifyContent:"center",paddingHorizontal:r.md+r.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:r.lg,gap:r.xl},listContentCards:{paddingTop:Hm,paddingHorizontal:Um,paddingBottom:Nm,gap:$m},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:um,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:cm,paddingVertical:r.md,paddingHorizontal:r.lg+dm,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:fm,borderColor:t.primaryEdge}:{},borderRadius:n.lg,borderBottomRightRadius:n.xs,...fb(u.userBubble,fm)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...fb(u.assistantBubble,fm)}:{paddingVertical:r.md,paddingHorizontal:r.lg+dm,borderRadius:n.lg,...fb(u.assistantBubble,fm)},bubbleVet:{maxWidth:cm,paddingVertical:r.md,paddingHorizontal:r.lg+dm,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...fb(u.vetBubble,fm)},bubbleCards:{maxWidth:Wm},bubbleUserCards:{paddingVertical:Vm,paddingHorizontal:qm},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*Gm)},bubblePending:{opacity:gm},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:i,...pb(u.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:o,...pb(u.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:i,...pb(u.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:r.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:r.sm,marginBottom:r.xs},assistantAvatar:{width:Zm,height:Zm,borderRadius:Zm/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.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:r.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:Em,textTransform:"uppercase",letterSpacing:jm,paddingBottom:r.sm,borderBottomWidth:Mm,borderBottomColor:s},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Mm,borderTopColor:s},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:Fm,paddingVertical:r.sm+dm,...u.chip?.backgroundColor!==void 0||u.chip?.borderColor!==void 0?{paddingHorizontal:r.md}:{},...fb(u.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...pb(u.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,marginTop:r.md},askChip:{minHeight:am,maxWidth:"100%",justifyContent:"center",paddingVertical:r.sm,paddingHorizontal:r.lg,borderRadius:n.pill,borderWidth:Am,borderColor:t.brandInk,backgroundColor:t.chatGround,...fb(u.chip,Am)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*Dm),...pb(u.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:r.md,marginTop:r.xs},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:bm,justifyContent:"center",paddingLeft:r.sm,paddingRight:ym,paddingVertical:vm,backgroundColor:t.composerFill,borderWidth:mm,borderColor:t.composerBorder,borderRadius:n.pill,...fb(u.composerInput,mm)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:km},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:r.xs},attachControl:{width:Im,height:Im,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:Pm},input:{flex:1,minHeight:km,maxHeight:sm,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...pb(u.composerInput)},sendControl:{minHeight:Sm,minWidth:Sm,alignItems:"center",justifyContent:"center"},sendDisc:{width:Sm,height:Sm,borderRadius:Sm/2,alignItems:"center",justifyContent:"center",...fb(u.sendButton)},sendControlDisabled:{opacity:Tm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:r.xs}})}var ey=18,ty=28,ry=6,ny=1200,ly=.4,iy=.4;function DictationButton({active:e,listening:t,elapsedMs:r,disabled:l=false,onToggle:i}){let o=useEverfurTheme(),s=a(()=>oy(o),[o]);return n(()=>{if(t)try{k.announceForAccessibility(Qf.listening)}catch{}},[t]),/* @__PURE__ */W(x,{style:s.wrap,children:[t?/* @__PURE__ */$(Text,{style:s.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:kb(r)}):null,
|
|
140
|
+
/* @__PURE__ */$(z,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?Qf.stopDictation:Qf.dictate,accessibilityState:{selected:e,disabled:l},style:[s.button,l?s.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */W(V,{children:[
|
|
141
141
|
/* @__PURE__ */$(Pulse,{style:s.pulse,reduced:o.motion.reducedMotion}),
|
|
142
|
-
/* @__PURE__ */$(StopGlyph,{size:Qm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */$(MicGlyph,{size:Ym,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=c(new M.Value(1)).current;return n(()=>{if(t)return;let e=M.loop(M.sequence([M.timing(r,{toValue:Zm,duration:Xm/2,useNativeDriver:true}),M.timing(r,{toValue:1,duration:Xm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */$(M.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function ty(e){let t=e.color,r=e.type.tierSizes.compact.micro;return v.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:rm,height:rm,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:ey},pulse:{position:"absolute",top:Jm,right:Jm,bottom:Jm,left:Jm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var ry=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function ny(){let e=globalThis,t=e[ry];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[ry]=r,r}function registerEverfurDictation(e){let t=ny();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function ly(){return ny().version??0}function iy(e){let t=ny(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function oy(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 ay(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function sy(){let e=ny();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||m.OS!=="ios"&&m.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:ay(t())}),e=>typeof e=="object"&&e!==null&&oy(e.box));return r.available&&(e.memo=r.module.box),e.memo}function uy(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function cy(){try{return Intl.DateTimeFormat().resolvedOptions().locale||fy}catch{return fy}}function dy(e){return e.replace(/_/g,"-").toLowerCase()}var fy="en-US";function hy(e=cy()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return fy;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:fy}function py(e,t){if(t.length===0)return null;let r=e=>t.find(t=>dy(t)===dy(e));return r(e)??r(fy)??t.find(e=>dy(e).startsWith("en-"))??null}async function gy(e,t){if(m.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return py(t,r??[])??t}catch{return t}}async function by(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(m.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=dy(t);return(r??[]).some(e=>dy(e)===n)?"on_device":"network"}catch{return"network"}}function my(){return m.OS!=="android"?true:Number(m.Version)>=yy}var yy=33;function vy(e,t,r){return{lang:t,interimResults:true,continuous:my(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var ky=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),wy=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Cy(e){return wy.has(e)}var Sy=600,xy=3;function _y(e,t,r){if(ky.has(r))return null;let n=Cy(r)?Sy:0;return r==="language-not-supported"&&dy(t)!==dy(fy)?{mode:"network",lang:fy,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Ry(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Ty(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Iy=55e3,zy=3e3,Py=1e3;function Oy(e){return Ey.has(e)||Cy(e)}var Ey=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),jy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function Fy(e){return e.replace(/\s+/g," ").trim()}function Ay(e,t,r){let n=Fy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Dy(e){return Fy([...e.committed,e.interim].join(" "))}function My(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(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,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Dy(e.transcript)===""&&e.launchedAt-o<Py}function d(e){return e.mode??"none"}function f(e,t){mb(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){mb(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=Dy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Oy(n))){h(e,Ry(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),mb(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=Ay(l.transcript,r,e?.isFinal===true),t.onText(Dy(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Cy(t)))return;let r=Dy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<xy?_y(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=jy,t.errorCode=null,g(t);try{e.start(vy(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Ty(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await gy(e,t.lang),a(t.token)===null)return;let n=await by(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Iy),b(t,n))}function y(r){if(!(a(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),zy);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:hy(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:jy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=Dy(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function Ly({enabled:e,input:t,setInput:r,phrases:o,maxLength:s,telemetry:d}){let f=i(iy,ly,ly),h=a(()=>e?sy():null,[e,f]),p=a(()=>uy(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=c(t);w.current=t;let C=c(r);C.current=r;let S=c(d);S.current=d;let x=c(""),R=c(s);R.current=s;let T=c(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:My(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>C.current(pb(x.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>S.current)});let I=h===null?null:T.current?.controller??null,z=u(()=>{I?.cancel()},[I]),P=u(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),x.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},hb);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=_.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var By=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function Hy(){let e=globalThis,t=e[By];if(t!==void 0)return t;let r=createContext(true);return e[By]=r,r}var Uy=Hy();function Ny(){return o(Uy)}var $y=/* @__PURE__ */Object.freeze(["photo"]),Wy=52,Vy=1.5,qy=10,Gy=14,Ky=10,Yy=40,Qy=20,Jy=.3,Xy=2.5,Zy=1,ev=1.5,tv=38,rv=22,nv=3;function lv(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?Kf(Vf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):Kf(Vf.placeholder,t):n==="urgent"?Vf.placeholderUrgentWeb:n==="followUp"?Vf.placeholderFollowUpWeb:Kf(Vf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??ml,transport:r}),l=a(()=>({state:n,sources:e.sources??$y,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
143
|
-
return $(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:s,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:w=false}){let{theme:C,styles:S}=
|
|
144
|
-
return W(x,{style:S.composerOuter,children:[o!==null&&O?/* @__PURE__ */$(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */$(AttachmentStrip,{attachments:
|
|
142
|
+
/* @__PURE__ */$(StopGlyph,{size:ty,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */$(MicGlyph,{size:ey,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=c(new M.Value(1)).current;return n(()=>{if(t)return;let e=M.loop(M.sequence([M.timing(r,{toValue:ly,duration:ny/2,useNativeDriver:true}),M.timing(r,{toValue:1,duration:ny/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */$(M.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function oy(e){let t=e.color,r=e.type.tierSizes.compact.micro;return v.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:am,height:am,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:iy},pulse:{position:"absolute",top:ry,right:ry,bottom:ry,left:ry,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var ay=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function sy(){let e=globalThis,t=e[ay];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[ay]=r,r}function registerEverfurDictation(e){let t=sy();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function uy(){return sy().version??0}function cy(e){let t=sy(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function dy(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 fy(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function hy(){let e=sy();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||m.OS!=="ios"&&m.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:fy(t())}),e=>typeof e=="object"&&e!==null&&dy(e.box));return r.available&&(e.memo=r.module.box),e.memo}function py(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function gy(){try{return Intl.DateTimeFormat().resolvedOptions().locale||my}catch{return my}}function by(e){return e.replace(/_/g,"-").toLowerCase()}var my="en-US";function yy(e=gy()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return my;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:my}function vy(e,t){if(t.length===0)return null;let r=e=>t.find(t=>by(t)===by(e));return r(e)??r(my)??t.find(e=>by(e).startsWith("en-"))??null}async function ky(e,t){if(m.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return vy(t,r??[])??t}catch{return t}}async function wy(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(m.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=by(t);return(r??[]).some(e=>by(e)===n)?"on_device":"network"}catch{return"network"}}function Cy(){return m.OS!=="android"?true:Number(m.Version)>=Sy}var Sy=33;function xy(e,t,r){return{lang:t,interimResults:true,continuous:Cy(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var _y=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),Ry=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Ty(e){return Ry.has(e)}var Iy=600,zy=3;function Py(e,t,r){if(_y.has(r))return null;let n=Ty(r)?Iy:0;return r==="language-not-supported"&&by(t)!==by(my)?{mode:"network",lang:my,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Oy(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Ey(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var jy=55e3,Fy=3e3,Ay=1e3;function Dy(e){return My.has(e)||Ty(e)}var My=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),Ly=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function By(e){return e.replace(/\s+/g," ").trim()}function Hy(e,t,r){let n=By(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Uy(e){return By([...e.committed,e.interim].join(" "))}function Ny(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(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,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Uy(e.transcript)===""&&e.launchedAt-o<Ay}function d(e){return e.mode??"none"}function f(e,t){Cb(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){Cb(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=Uy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Dy(n))){h(e,Oy(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),Cb(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=Hy(l.transcript,r,e?.isFinal===true),t.onText(Uy(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Ty(t)))return;let r=Uy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<zy?Py(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=Ly,t.errorCode=null,g(t);try{e.start(xy(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Ey(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await ky(e,t.lang),a(t.token)===null)return;let n=await wy(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),jy),b(t,n))}function y(r){if(!(a(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),Fy);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:yy(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:Ly,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=Uy(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function $y({enabled:e,input:t,setInput:r,phrases:o,maxLength:s,telemetry:d}){let f=i(cy,uy,uy),h=a(()=>e?hy():null,[e,f]),p=a(()=>py(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=c(t);w.current=t;let C=c(r);C.current=r;let S=c(d);S.current=d;let x=c(""),R=c(s);R.current=s;let T=c(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:Ny(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>C.current(vb(x.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>S.current)});let I=h===null?null:T.current?.controller??null,z=u(()=>{I?.cancel()},[I]),P=u(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),x.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},yb);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=_.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var Wy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function Vy(){let e=globalThis,t=e[Wy];if(t!==void 0)return t;let r=createContext(true);return e[Wy]=r,r}var qy=Vy();function Gy(){return o(qy)}var Ky=/* @__PURE__ */Object.freeze(["photo"]),Yy=52,Qy=1.5,Zy=10,Jy=14,Xy=10,ev=40,tv=20,rv=.3,nv=2.5,lv=1,iv=1.5,ov=38,av=22,sv=3;function uv(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?Xf(Qf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):Xf(Qf.placeholder,t):n==="urgent"?Qf.placeholderUrgentWeb:n==="followUp"?Qf.placeholderFollowUpWeb:Xf(Qf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??ml,transport:r}),l=a(()=>({state:n,sources:e.sources??Ky,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
143
|
+
return $(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:s,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:w=false}){let{theme:C,styles:S}=Jm(),_=a(()=>gv(C),[C]),R=a(()=>bv(C),[C]),T=Lg(),[I,P]=_b(e,i,s),[O,E]=l(false),[j,F]=l(false),A=u(()=>F(true),[]),D=u(()=>F(false),[]),[M,L]=l(false);n(()=>{L(false)},[i]);let B=uv(C.meta.placeholder,p,k,b,C.meta.placeholderFillsPet===true),H=a(()=>xb({name:p,breed:g}),[p,g]),U=$y({enabled:m,input:I,setInput:P,phrases:H,maxLength:Yn,telemetry:y}),N=U.cancel,q=U.active;Rb(d,i===null?null:String(i),I,P,q);let G=c(i);n(()=>{G.current!==i&&(G.current=i,N())},[i,N]);let K=Gy();n(()=>{K||N()},[K,N]);let Y=o?.state.uploading??false,Q=o?.state.failed??false,Z=Y||Q,J=o?.state.attachments??cv;tb(J.length,T);let X=u(()=>{let t=I.trim();if(t.length===0||Z||[...t].length>Yn)return;q&&N();let r=o?.state.s3Keys??dv;o!==null&&r.length>0?(f(o.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),o.state.clear()):e(t),P(""),L(false)},[I,e,Z,q,N,o,f]),ee=u(e=>{q&&N(),P(e)},[q,N,P]),te=u(()=>{t()},[t]),re=u(e=>{E(false),o!==null&&(L(false),o.state.dismissRejected(),Wh(o.pick,e).then(e=>{if(!e.ok){L(true);return}e.value!==null&&o.state.add(e.value)}))},[o]),ne=a(()=>[...I.trim()].length>Yn,[I]),le=ne||Z||I.trim().length===0,ie=ne||Z||w&&I.trim().length===0,oe=o!==null&&J.length>=o.state.maxPerMessage,ae=C.slots.sendButton?.textColor??C.color.brandInk,se=C.slots.sendButton?.textColor??C.color.surface;/* @__PURE__ */
|
|
144
|
+
return W(x,{style:S.composerOuter,children:[o!==null&&O?/* @__PURE__ */$(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */$(AttachmentStrip,{attachments:J,rejected:M?pv:o.state.rejected,uploadFailed:Q,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:e=>h({uri:e.previewUri,label:e.filename}),style:v?_.tray:R.tray}):null,
|
|
145
145
|
/* @__PURE__ */W(x,{style:v?[S.composer,_.bar,j?_.barFocused:null]:S.composer,children:[U.supported&&U.error!==null?/* @__PURE__ */W(V,{children:[
|
|
146
|
-
/* @__PURE__ */$(Text,{style:S.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
147
|
-
/* @__PURE__ */$(AnnounceLine,{line:
|
|
148
|
-
/* @__PURE__ */W(x,{style:S.composerRow,children:[o!==null?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:oe?
|
|
149
|
-
/* @__PURE__ */$(ff,{style:v?[S.input,_.input]:S.input,onFocus:A,onBlur:D,value:I,onChangeText:ee,placeholder:B,placeholderTextColor:C.slots.composerInput?.textColor??C.color.text.placeholder,accessibilityLabel:Vf.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...av,...v?sv:null,blurOnSubmit:false,multiline:true,editable:true}),U.supported?/* @__PURE__ */$(DictationButton,{active:U.active,listening:U.status==="listening",elapsedMs:U.elapsedMs,onToggle:U.toggle}):null,r?/* @__PURE__ */$(z,{onPress:te,accessibilityRole:"button",accessibilityLabel:Vf.stop,style:S.sendControl,children:/* @__PURE__ */$(x,{style:v?_.disc:S.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */$(StopGlyph,{size:v?Qy:wm,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */$(z,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:Vf.send,accessibilityState:{disabled:le,busy:Y},style:[S.sendControl,ie?v?_.dimmed:S.sendControlDisabled:null],children:v?/* @__PURE__ */$(x,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */$(ArrowUpGlyph,{size:Qy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */$(x,{style:S.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */$(SendGlyph,{size:km,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var iv=/* @__PURE__ */Object.freeze([]),ov=/* @__PURE__ */Object.freeze([]),av=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),sv=/* @__PURE__ */Object.freeze(m.OS==="web"?{rows:1}:{}),uv=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function cv(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+Zy;return v.create({bar:{marginTop:qy,marginHorizontal:Gy,marginBottom:Ky,minHeight:Wy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Vy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Xy,paddingLeft:8-(Xy-Vy),paddingRight:6-(Xy-Vy)},input:{fontSize:n,lineHeight:Math.round(n*ev),minHeight:Math.round(n*ev),...m.OS==="web"?{outlineStyle:"none"}:null},add:{width:tv,height:tv,borderRadius:tv/2},disc:{width:Yy,height:Yy,borderRadius:Yy/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...ab(r)},dimmed:{opacity:Jy},tray:{marginHorizontal:Gy,marginTop:qy,paddingBottom:0}})}function dv(e){return v.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=wd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[s,d]=l({repository:o,pets:[],loading:true,error:null}),f=s.repository===o?s:{pets:[],loading:true,error:null},h=c(0),p=u(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Vi(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function fv(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var hv=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var pv=false;function gv(e,t){return t!==void 0?(Dh(t,e),"onStartInApp"):wf(e)==="presented"?"presenter":_f(e)?"experience":(pv||(pv=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var bv=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&bv.includes(e)}var mv="/widget/v1/televet/handoffs",yv="/widget/v1/televet/availability",vv="/widget/v1/televet/chat-entry",kv=/^[a-z0-9][a-z0-9_-]{0,39}$/,wv=/^[A-Za-z0-9_-]{22}$/;var Cv=32,Sv=128,xv=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 _v(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Rv(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Tv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!kv.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>xv)return{ok:false,message:`visitRef must be 1..${xv} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${bv.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Iv(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 zv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Av(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Sv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Sv} characters`}));i=e}let o=Tv(i,l);if(!o.ok){let e=_v(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:mv,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=Pv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!wv.test(d))){let e=Rv("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?Iv(s.value?.visit):null;if(f&&h===null){let e=Rv("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"})):(Av(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Cv)return _v(`state must be at most ${Cv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:yv,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Rv("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:vv},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function Pv(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||!Fv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Ov=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Ev=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,jv=/[\s\u0000-\u001f\u007f]/;function Fv(e){if(jv.test(e))return false;let t=Ev.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&Ov.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function Av(e,t,r){if(e)try{e.track(t,r)}catch{}}var Dv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function Mv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(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&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var Lv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Bv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=wd(),o=useCapability("televet"),s=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return zv({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=c(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=Mv(b,s,{usState:d,chat:f,scope:m}),v=s&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(Dv),S=c(null),x=c({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=c(g);_.current=g;let R=c(v);R.current=v;let T=u((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(Lv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(Dv),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=u((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return gv(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(Dv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=u(e=>p?T(e,null):I(e,null),[p,T,I]),P=u((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=u(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var Hv=e=>T.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??Hv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return Bv(n,r)}var Uv=44,Nv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:u,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>$v(k),[k]),C=c(false);if(!v.available)/* @__PURE__ */
|
|
146
|
+
/* @__PURE__ */$(Text,{style:S.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:wb(U.error)}),
|
|
147
|
+
/* @__PURE__ */$(AnnounceLine,{line:wb(U.error)})]}):null,
|
|
148
|
+
/* @__PURE__ */W(x,{style:S.composerRow,children:[o!==null?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:oe?bb(J.length,o.state.maxPerMessage):Qf.attachPhotoOrFileNative,accessibilityState:{disabled:oe,expanded:O},disabled:oe,style:[S.attachControl,v?_.add:null,oe?S.attachControlDisabled:null],hitSlop:v?sv:void 0,onPress:()=>E(e=>!e),children:/* @__PURE__ */$(UploadGlyph,{size:v?av:zm,color:oe?C.color.text.muted:v?C.color.text.primary:C.color.brandInk,strokeWidth:1.75})}):null,
|
|
149
|
+
/* @__PURE__ */$(mf,{style:v?[S.input,_.input]:S.input,onFocus:A,onBlur:D,value:I,onChangeText:ee,placeholder:B,placeholderTextColor:C.slots.composerInput?.textColor??C.color.text.placeholder,accessibilityLabel:Qf.composerLabel,onSubmitEditing:X,returnKeyType:"send",...fv,...v?hv:null,blurOnSubmit:false,multiline:true,editable:true}),U.supported?/* @__PURE__ */$(DictationButton,{active:U.active,listening:U.status==="listening",elapsedMs:U.elapsedMs,onToggle:U.toggle}):null,r?/* @__PURE__ */$(z,{onPress:te,accessibilityRole:"button",accessibilityLabel:Qf.stop,style:S.sendControl,children:/* @__PURE__ */$(x,{style:v?_.disc:S.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */$(StopGlyph,{size:v?tv:Rm,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */$(z,{onPress:X,disabled:le,accessibilityRole:"button",accessibilityLabel:Qf.send,accessibilityState:{disabled:le,busy:Y},style:[S.sendControl,ie?v?_.dimmed:S.sendControlDisabled:null],children:v?/* @__PURE__ */$(x,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */$(ArrowUpGlyph,{size:tv,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */$(x,{style:S.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */$(SendGlyph,{size:_m,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var cv=/* @__PURE__ */Object.freeze([]),dv=/* @__PURE__ */Object.freeze([]),fv=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),hv=/* @__PURE__ */Object.freeze(m.OS==="web"?{rows:1}:{}),pv=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function gv(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+lv;return v.create({bar:{marginTop:Zy,marginHorizontal:Jy,marginBottom:Xy,minHeight:Yy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Qy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:nv,paddingLeft:8-(nv-Qy),paddingRight:6-(nv-Qy)},input:{fontSize:n,lineHeight:Math.round(n*iv),minHeight:Math.round(n*iv),...m.OS==="web"?{outlineStyle:"none"}:null},add:{width:ov,height:ov,borderRadius:ov/2},disc:{width:ev,height:ev,borderRadius:ev/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...fb(r)},dimmed:{opacity:rv},tray:{marginHorizontal:Jy,marginTop:Zy,paddingBottom:0}})}function bv(e){return v.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=Rd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[s,d]=l({repository:o,pets:[],loading:true,error:null}),f=s.repository===o?s:{pets:[],loading:true,error:null},h=c(0),p=u(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Vi(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function mv(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var yv=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var vv=false;function kv(e,t){return t!==void 0?(Uh(t,e),"onStartInApp"):Rf(e)==="presented"?"presenter":Pf(e)?"experience":(vv||(vv=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var wv=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&wv.includes(e)}var Cv="/widget/v1/televet/handoffs",Sv="/widget/v1/televet/availability",xv="/widget/v1/televet/chat-entry",_v=/^[a-z0-9][a-z0-9_-]{0,39}$/,Rv=/^[A-Za-z0-9_-]{22}$/;var Tv=32,Iv=128,zv=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 Pv(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Ov(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Ev(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!_v.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>zv)return{ok:false,message:`visitRef must be 1..${zv} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${wv.join(", ")}`};r.intent=o}return{ok:true,body:r}}function jv(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 Fv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Hv(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Iv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Iv} characters`}));i=e}let o=Ev(i,l);if(!o.ok){let e=Pv(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:Cv,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=Av(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!Rv.test(d))){let e=Ov("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?jv(s.value?.visit):null;if(f&&h===null){let e=Ov("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"})):(Hv(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Tv)return Pv(`state must be at most ${Tv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:Sv,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Ov("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:xv},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function Av(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||!Bv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Dv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Mv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Lv=/[\s\u0000-\u001f\u007f]/;function Bv(e){if(Lv.test(e))return false;let t=Mv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&Dv.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function Hv(e,t,r){if(e)try{e.track(t,r)}catch{}}var Uv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function Nv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(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&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var $v=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Wv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=Rd(),o=useCapability("televet"),s=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return Fv({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=c(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=Nv(b,s,{usState:d,chat:f,scope:m}),v=s&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(Uv),S=c(null),x=c({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=c(g);_.current=g;let R=c(v);R.current=v;let T=u((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C($v);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(Uv),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=u((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return kv(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(Uv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=u(e=>p?T(e,null):I(e,null),[p,T,I]),P=u((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=u(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var Vv=e=>T.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??Vv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return Wv(n,r)}var qv=44,Gv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:u,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>Kv(k),[k]),C=c(false);if(!v.available)/* @__PURE__ */
|
|
150
150
|
return W(V,{children:[null,
|
|
151
|
-
/* @__PURE__ */$(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??
|
|
151
|
+
/* @__PURE__ */$(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??yv.visitButton;/* @__PURE__ */
|
|
152
152
|
return W(V,{children:[
|
|
153
|
-
/* @__PURE__ */$(z,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};
|
|
154
|
-
/* @__PURE__ */$(TelevetHostOutlet,{})]})}function
|
|
155
|
-
return $(F,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=
|
|
153
|
+
/* @__PURE__ */$(z,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};kv(e,b)===null&&Uh(i,"unavailable",null);return}C.current=true,(p==null?v.open():v.openVisit(p,g??null)).then(e=>{e.opened?Uh(l,e.flowId??null):e.reason!=="cancelled"&&Uh(i,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{busy:S,disabled:S},style:[w.button,S?w.busy:null,o],children:/* @__PURE__ */$(Text,{style:[w.label,s],children:x})}),
|
|
154
|
+
/* @__PURE__ */$(TelevetHostOutlet,{})]})}function Kv(e){let{color:t,space:r,radius:n,type:l,slots:i}=e;return v.create({button:{minHeight:qv,minWidth:qv,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...fb(i.vetVisitButton)},busy:{opacity:Gv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...pb(i.vetVisitButton)}})}function Yv(e){let[t,r]=l(null);return{shown:e!==null&&t!==e,onError:()=>r(e)}}function BrandImage({uri:e,label:t,decorative:r=false,style:n,resizeMode:l="contain",fallback:i=null,onError:o,testID:a}){let s=Yv(e);if(e===null||!s.shown)return i;let u=r?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
|
|
155
|
+
return $(F,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=Yv(e);return e===null||!i.shown?null:/* @__PURE__ */$(x,{style:r,...l===void 0?{}:{testID:l},children:/* @__PURE__ */$(F,{source:{uri:e},style:n,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:i.onError})})}var Qv=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),Zv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Jv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return Zv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return Zv;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?Zv:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function Xv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function ek(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function tk(e){if(e.brightness!=="light")return false;let t=ga.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(ek(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&ek(r).every(e=>l.has(e))}function rk(e){let t=(e.brightness==="dark"?ma:ga).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 nk(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function lk(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function ik(e){let t=lk(e.ageYears),r=nk(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var ak=/* @__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
|
|
162
|
-
return $(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */$(x,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */$(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?
|
|
163
|
-
/* @__PURE__ */$(z,{style:
|
|
164
|
-
/* @__PURE__ */W(x,{style:
|
|
165
|
-
/* @__PURE__ */$(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:
|
|
166
|
-
/* @__PURE__ */$(E,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=
|
|
167
|
-
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
168
|
-
/* @__PURE__ */$(PetDisc,{pet:e,size:
|
|
161
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function sk(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return ak[t%ak.length]}function uk(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function ck(e){return{...sk(e.petRef),initial:uk(e.name)}}function dk(e,t,r){let n=ck(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function fk(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:t,ringStroke:r}){let n=useEverfurTheme(),l=a(()=>hk(n),[n]),i=t-r*2,o=e===null?null:dk(e,tk(n),{fill:n.color.highlight,ink:n.color.onHighlight}),s=fk(i);/* @__PURE__ */
|
|
162
|
+
return $(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */$(x,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */$(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?uk(null):o.initial})})})}function hk(e){return v.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function pk(e,t){let{borderRadius:r,...n}=fb(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function gk(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=fb(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var bk=48,mk=2,yk=320,vk="80%",kk="rgba(17,17,17,0.45)",wk=18,Ck=22,Sk=12,xk=.4,_k=44;function Rk(e){return e?.name?.trim()||Qf.yourPet}function PetSwitcherSheet({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:l=null,onClose:i}){let o=useEverfurTheme(),s=a(()=>Tk(o),[o]),u=Wf();return e?/* @__PURE__ */$(O,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"fade",onRequestClose:i,children:/* @__PURE__ */W(x,{style:s.root,children:[
|
|
163
|
+
/* @__PURE__ */$(z,{style:Mb,onPress:i,accessibilityRole:"button",accessibilityLabel:Qf.close,children:/* @__PURE__ */$(x,{style:s.backdrop})}),
|
|
164
|
+
/* @__PURE__ */W(x,{style:Vf(s.panel,u),accessibilityViewIsModal:true,children:[
|
|
165
|
+
/* @__PURE__ */$(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:Qf.yourPets}),
|
|
166
|
+
/* @__PURE__ */$(E,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=Rk(e),i=ik(e);/* @__PURE__ */
|
|
167
|
+
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:Zf(t?Qf.petCurrentlyActive:Qf.switchToPet,{name:l}),accessibilityState:{selected:t},style:[s.row,t?s.rowActive:null],onPress:()=>n(e.petRef),children:[
|
|
168
|
+
/* @__PURE__ */$(PetDisc,{pet:e,size:bk,ringStroke:mk}),
|
|
169
169
|
/* @__PURE__ */W(x,{style:s.copy,children:[
|
|
170
170
|
/* @__PURE__ */$(Text,{style:s.name,numberOfLines:1,children:l}),
|
|
171
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${
|
|
171
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${Qf.activePrefix}${i}`:i})]}),t?/* @__PURE__ */$(CheckGlyph,{size:wk,color:o.color.brandInk}):null]},e.petRef)})}),l!==null?/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.addAnotherPet,style:s.addRow,onPress:l,children:[
|
|
172
172
|
/* @__PURE__ */$(x,{style:s.addDisc,children:/* @__PURE__ */$(Text,{tier:"control",style:s.addPlus,children:"+"})}),
|
|
173
|
-
/* @__PURE__ */$(Text,{style:s.addLabel,children:
|
|
174
|
-
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
173
|
+
/* @__PURE__ */$(Text,{style:s.addLabel,children:Qf.addAnotherPet})]}):null,
|
|
174
|
+
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.close,containerStyle:s.closeSlot,style:s.closeButton,onPress:i,children:/* @__PURE__ */$(Text,{tier:"control",style:s.closeText,children:Qf.close})})]})]})}):null}function Tk(e){let t=e.color,r=e.radius,n=pb(e.slots.dialog);return v.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:kk},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Ck,borderTopRightRadius:Ck,gap:14,maxHeight:vk,...pk(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...n},list:{maxHeight:yk,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:_k,paddingHorizontal:8},addDisc:{width:bk,height:bk,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:mk,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,...n},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...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:xk},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:Sk,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:xk}})}var Ik=44,zk=36,Pk=22,Ok=20,Ek=9,jk=1.5,Fk=6,Ak=35,Dk=1.75,Mk=12.4,Lk=.5,Bk=8,Hk=28,Uk=160,Nk=16,$k=8;function Wk(e,t){return mv(e,t)}function ChatHeader({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onNewChat:i,onPetChange:o,onAddPet:s,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=a(()=>Vk(f),[f]),[p,g]=l(false),b=Wk(e.pets,t),m=b!==null&&(e.pets.length>=2||s!==void 0),y=t??b?.petRef??null,v=Rk(b),[k,w]=l(Qv),C=u(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>Xv(t,e,r))},[]),S=a(()=>C("row"),[C]),_=a(()=>C("leading"),[C]),R=a(()=>C("trailing"),[C]),T=2*Nk+2*(f.slots.header?.borderColor!==void 0?1:0)+2*$k,I=Jv(k,T,Uk),z=t=>{g(false),e.setActivePet(t),Uh(o,t)},P=s===void 0?null:()=>{g(false),Uh(s)};/* @__PURE__ */
|
|
175
175
|
return W(V,{children:[
|
|
176
176
|
/* @__PURE__ */W(x,{style:h.row,onLayout:S,children:[
|
|
177
|
-
/* @__PURE__ */$(x,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */W(x,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
178
|
-
/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${
|
|
179
|
-
/* @__PURE__ */$(MenuGlyph,{size:
|
|
177
|
+
/* @__PURE__ */$(x,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */W(x,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Jp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:i,children:/* @__PURE__ */$(EditGlyph,{size:Ok,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
|
|
178
|
+
/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${Qf.openHistoryNative}${Qf.newReplySuffix}`:Qf.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:n,children:[
|
|
179
|
+
/* @__PURE__ */$(MenuGlyph,{size:Pk,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),r?/* @__PURE__ */$(x,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
|
|
180
180
|
/* @__PURE__ */$(x,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */$(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
|
|
181
181
|
/* @__PURE__ */$(x,{style:[h.trailing,I.trailing===void 0?null:{minWidth:I.trailing}],children:/* @__PURE__ */W(x,{style:h.trailingContent,onLayout:R,children:[y===null?null:/* @__PURE__ */$(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__ */$(x,{style:h.right,children:m?/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
183
|
-
/* @__PURE__ */$(PetDisc,{pet:b,size:
|
|
184
|
-
/* @__PURE__ */$(x,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */$(PlusGlyph,{size:
|
|
185
|
-
/* @__PURE__ */$(x,{style:h.avatarWrap,accessible:true,accessibilityLabel:
|
|
186
|
-
/* @__PURE__ */$(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */$(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>
|
|
187
|
-
return $(x,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */$(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function
|
|
188
|
-
/* @__PURE__ */Object.freeze({key:"inaccurate",label:
|
|
189
|
-
/* @__PURE__ */Object.freeze({key:"outdated",label:
|
|
190
|
-
/* @__PURE__ */Object.freeze({key:"unsafe",label:
|
|
191
|
-
/* @__PURE__ */Object.freeze({key:"unclear",label:
|
|
192
|
-
/* @__PURE__ */Object.freeze({key:"other",label:
|
|
193
|
-
/* @__PURE__ */Object.freeze({sentiment:"up",label:
|
|
194
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:
|
|
182
|
+
/* @__PURE__ */$(x,{style:h.right,children:m?/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:Zf(Qf.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
|
|
183
|
+
/* @__PURE__ */$(PetDisc,{pet:b,size:Ak,ringStroke:Dk}),
|
|
184
|
+
/* @__PURE__ */$(x,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */$(PlusGlyph,{size:Bk,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&b===null?
|
|
185
|
+
/* @__PURE__ */$(x,{style:h.avatarWrap,accessible:true,accessibilityLabel:Qf.yourPet,children:/* @__PURE__ */$(Ring,{size:Ak,strokeWidth:Dk,color:f.color.mark,children:/* @__PURE__ */$(x,{style:h.placeholderDisc})})}):/* @__PURE__ */$(x,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:b===null?Qf.yourPet:v,children:/* @__PURE__ */$(PetDisc,{pet:b,size:Ak,ringStroke:Dk})})})]})}),
|
|
186
|
+
/* @__PURE__ */$(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */$(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>Vk(r),[r]);/* @__PURE__ */
|
|
187
|
+
return $(x,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */$(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function Vk(e){let t=e.color,r=Ak-Dk*2,n=e.slots.header;return v.create({vetEntry:{minHeight:Ik,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:v.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:Nk,paddingBottom:10,backgroundColor:n?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Nk,paddingTop:e.space.md,paddingBottom:e.space.xs},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:Nk,paddingVertical:10,backgroundColor:t.surface,...fb(n)},iconSlot:{borderRadius:zk/2},iconButton:{width:zk,height:zk,borderRadius:zk/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Fk,right:Fk,width:Ek,height:Ek,borderRadius:Ek,backgroundColor:t.danger,borderWidth:jk,borderColor:n?.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:$k,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:Hk,width:Uk,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Ak/2},avatarWrap:{width:Ak,height:Ak,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Mk,height:Mk,borderRadius:Mk/2,borderWidth:Lk,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var qk=/* @__PURE__ */Object.freeze([
|
|
188
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:Qf.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
189
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:Qf.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
190
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:Qf.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
191
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:Qf.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
192
|
+
/* @__PURE__ */Object.freeze({key:"other",label:Qf.feedbackReasonOther,feedbackType:"not_helpful"})]),Gk=/* @__PURE__ */Object.freeze([
|
|
193
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:Qf.feedbackHelpful}),
|
|
194
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:Qf.feedbackNotHelpful})]);function Kk(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function Yk(e,t){if(e==="down"&&t!==null){let e=qk.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return Kk(e)}var Qk=44,Zk="rgba(17,17,17,0.55)",Jk=26,Xk=36,ew=4,tw=20,rw=38,nw=18,lw=12;function FeedbackReasons({visible:e,onSubmit:t,onSkip:r}){let n=useEverfurTheme(),i=a(()=>iw(n),[n]),o=Wf(),[s,u]=l(null),[c,d]=l(""),[f,h]=l(false),[p,g]=l(false),b=()=>{u(null),d(""),h(false),g(false)},y=()=>{f||(b(),r())},v=async()=>{if(f)return;h(true),g(false);let e=c.trim();await t(s,e.length>0?e:null)?b():(h(false),g(true))};if(!e)return null;let k=[...c].length>Kn;/* @__PURE__ */
|
|
195
195
|
return $(O,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:/* @__PURE__ */W(I,{behavior:m.OS==="ios"?"padding":void 0,style:i.root,children:[
|
|
196
|
-
/* @__PURE__ */$(z,{style:i.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:
|
|
197
|
-
/* @__PURE__ */W(x,{style:
|
|
196
|
+
/* @__PURE__ */$(z,{style:i.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:Qf.feedbackSkipA11y}),
|
|
197
|
+
/* @__PURE__ */W(x,{style:Vf(i.sheet,o),accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
198
198
|
/* @__PURE__ */$(x,{style:i.handle}),
|
|
199
199
|
/* @__PURE__ */W(x,{style:i.header,children:[
|
|
200
|
-
/* @__PURE__ */$(x,{style:i.iconBadge,children:/* @__PURE__ */$(ThumbGlyph,{size:
|
|
200
|
+
/* @__PURE__ */$(x,{style:i.iconBadge,children:/* @__PURE__ */$(ThumbGlyph,{size:nw,color:n.color.brandInk,active:false,rotate:"180deg"})}),
|
|
201
201
|
/* @__PURE__ */W(x,{style:i.headerText,children:[
|
|
202
|
-
/* @__PURE__ */$(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:
|
|
203
|
-
/* @__PURE__ */$(Text,{style:i.subtitle,children:
|
|
204
|
-
/* @__PURE__ */$(x,{style:i.options,children:
|
|
202
|
+
/* @__PURE__ */$(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:Qf.feedbackTitle}),
|
|
203
|
+
/* @__PURE__ */$(Text,{style:i.subtitle,children:Qf.feedbackSubtitle})]})]}),
|
|
204
|
+
/* @__PURE__ */$(x,{style:i.options,children:qk.map(e=>{let t=s===e.key;/* @__PURE__ */
|
|
205
205
|
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[i.option,t?i.optionSelected:null],onPress:()=>u(t=>t===e.key?null:e.key),children:[
|
|
206
206
|
/* @__PURE__ */$(Text,{style:[i.optionLabel,t?i.optionLabelSelected:null],children:e.label}),
|
|
207
|
-
/* @__PURE__ */$(x,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */$(CheckGlyph,{size:
|
|
207
|
+
/* @__PURE__ */$(x,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */$(CheckGlyph,{size:lw,color:n.color.surface,strokeWidth:2}):null})]},e.key)})}),
|
|
208
208
|
/* @__PURE__ */W(x,{style:i.inputWrap,children:[
|
|
209
|
-
/* @__PURE__ */$(
|
|
209
|
+
/* @__PURE__ */$(mf,{style:i.input,placeholder:Qf.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Qf.feedbackNotesPlaceholder,value:c,onChangeText:d,multiline:true,editable:!f}),c.length>0?/* @__PURE__ */$(Text,{tier:"compact",style:[i.counter,k?i.counterOver:null],children:`${[...c].length}/${Kn}`}):null]}),p?/* @__PURE__ */$(Text,{style:i.failed,accessibilityRole:"alert",children:Qf.feedbackFailed}):null,
|
|
210
210
|
/* @__PURE__ */W(x,{style:i.actions,children:[
|
|
211
|
-
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
212
|
-
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
211
|
+
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.feedbackSubmit,accessibilityState:{busy:f,disabled:f||k},disabled:f||k,style:[i.submit,f||k?i.submitDisabled:null],onPress:()=>{v()},children:/* @__PURE__ */$(Text,{tier:"control",style:i.submitLabel,children:Qf.feedbackSubmit})}),
|
|
212
|
+
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Qf.feedbackSkipA11y,hitSlop:8,onPress:y,style:i.skip,children:/* @__PURE__ */$(Text,{tier:"control",style:i.skipLabel,children:Qf.feedbackSkip})})]})]})]})})}function iw(e){let t=e.color,r=e.type,n=e.radius,l=e.slots,i=pb(l.dialog);return v.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Mb,backgroundColor:Zk},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Jk,borderTopRightRadius:Jk,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...pk(l.dialog)},handle:{alignSelf:"center",width:Xk,height:ew,borderRadius:ew/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:rw,height:rw,borderRadius:rw/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:r.letterSpacing.tight,...i},subtitle:{...face(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted,...i},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:v.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...fb(l.chip,v.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.primary,...pb(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:tw,height:tw,borderRadius:tw/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top",...fb(l.input,1),...pb(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:Qk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...fb(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...pb(l.primaryButton)},skip:{minHeight:Qk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}var ow=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function aw(){let e=globalThis,t=e[ow];if(t!==void 0)return t;let r={factory:createContext(null),home:createContext(null)};return e[ow]=r,r}var sw=aw().factory,uw=aw().home;function cw(){return o(sw)}function dw(){return o(uw)?.kit??null}function fw(){return o(uw)}var hw=15,pw=8;function HistoryBar({bar:e,history:t,empty:r,unread:n,extra:l}){let i=useEverfurTheme(),o=dw(),s=a(()=>o!==null?mw(i,o):yw(i),[i,o]),u=t.cursor===null?t.rows.length:0,c=t=>{let r=e.renderIcon;if(r!==void 0)/* @__PURE__ */return $(HostRender,{render:()=>r(t),fallback:null});if(o===null)return null;let n=String(v.flatten(s.label).color??i.color.linkInk);return t==="history"?/* @__PURE__ */$(HistoryGlyph,{size:bw,color:n,strokeWidth:1.8}):/* @__PURE__ */$(EditGlyph,{size:bw,color:n,strokeWidth:1.8})};/* @__PURE__ */
|
|
213
213
|
return W(x,{style:s.bar,testID:"everfur-history-bar",children:[
|
|
214
|
-
/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?
|
|
214
|
+
/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?gw:void 0,children:[c("history"),
|
|
215
215
|
/* @__PURE__ */$(Text,{tier:"control",style:s.label,children:e.chats}),u>0?/* @__PURE__ */$(x,{style:s.count,children:/* @__PURE__ */$(Text,{tier:"badge",style:s.countText,children:String(u)})}):null,n?/* @__PURE__ */$(x,{style:s.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,l??null,
|
|
216
|
-
/* @__PURE__ */$(x,{style:s.spacer}),r?null:/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?
|
|
217
|
-
/* @__PURE__ */$(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var
|
|
216
|
+
/* @__PURE__ */$(x,{style:s.spacer}),r?null:/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?gw:void 0,children:[c("edit"),
|
|
217
|
+
/* @__PURE__ */$(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var gw=4,bw=18;function mw(e,t){return{...yw(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 yw(e){let t=e.color,r=e.space;return v.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:am},label:{...face(e,"bold"),fontSize:hw,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:pw,height:pw,borderRadius:pw/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var vw=.88,kw=420,ww=58,Cw="rgba(17,17,17,0.28)",Sw=.15,xw=14,_w=12,Rw=44,Tw=16,Iw=14,zw=12,Pw=14,Ow=8,Ew=2,jw=.5,Fw=Ng(Eg.standard);function Aw(e){return Math.min(Math.round(e*vw),kw)}function HistoryDrawer({chat:e,history:t}){let[r,n]=l(t.open),i=u(()=>n(false),[]);return t.open&&!r&&n(true),r?/* @__PURE__ */$(DrawerModal,{chat:e,history:t,onHidden:i}):null}function DrawerModal({chat:e,history:t,onHidden:r}){let l=useEverfurTheme(),i=a(()=>Dw(l),[l]),o=Lg(),s=U(),{width:u}=L(),d=Aw(u),f=t.open,h=c(null);h.current===null&&(h.current=new M.Value(o.drawerMs<=0&&f?1:0));let p=h.current;n(()=>{if(!f&&o.drawerMs<=0){r();return}let e=M.timing(p,{toValue:f?1:0,duration:o.drawerMs,easing:Fw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!f&&r()}),()=>e.stop()},[f,p,o.drawerMs,r]);let g=p.interpolate({inputRange:[0,1],outputRange:[-d,0]}),b=t.filtered,y=t.rows.length===0,v=t.cursor===null&&!t.loading&&t.error===null,k=y&&t.loading?/* @__PURE__ */W(x,{style:i.emptyCard,accessibilityLabel:Jp.loading,accessibilityState:{busy:true},children:[
|
|
218
218
|
/* @__PURE__ */$(j,{color:i.emptyTitle.color}),
|
|
219
|
-
/* @__PURE__ */$(Text,{style:i.emptyBody,children:
|
|
220
|
-
/* @__PURE__ */$(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:
|
|
219
|
+
/* @__PURE__ */$(Text,{style:i.emptyBody,children:Jp.loading})]}):y&&t.error!==null?/* @__PURE__ */W(x,{style:i.emptyCard,children:[
|
|
220
|
+
/* @__PURE__ */$(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:Jp.loadFailed}),
|
|
221
221
|
/* @__PURE__ */$(Text,{style:i.emptyBody,children:t.error}),
|
|
222
|
-
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
223
|
-
/* @__PURE__ */$(Text,{style:i.emptyTitle,children:
|
|
224
|
-
/* @__PURE__ */$(Text,{style:i.emptyBody,children:
|
|
225
|
-
/* @__PURE__ */$(Text,{style:i.noMatch,children:
|
|
222
|
+
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Jp.retry,containerStyle:i.retrySlot,style:i.retryButton,onPress:()=>{t.load()},children:/* @__PURE__ */$(Text,{tier:"control",style:i.retryText,children:Jp.retry})})]}):t.emptyKind==="empty"?/* @__PURE__ */W(x,{style:i.emptyCard,children:[
|
|
223
|
+
/* @__PURE__ */$(Text,{style:i.emptyTitle,children:Jp.empty}),
|
|
224
|
+
/* @__PURE__ */$(Text,{style:i.emptyBody,children:Jp.emptyBody})]}):
|
|
225
|
+
/* @__PURE__ */$(Text,{style:i.noMatch,children:Jp.noMatch}),w=!t.searching&&t.loadingMore?/* @__PURE__ */$(x,{style:i.loadMoreFooter,children:/* @__PURE__ */$(Text,{style:i.loadMoreLabel,children:Jp.loadingMore})}):null;/* @__PURE__ */
|
|
226
226
|
return $(O,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:/* @__PURE__ */W(x,{style:i.root,children:[
|
|
227
|
-
/* @__PURE__ */$(z,{style:
|
|
228
|
-
/* @__PURE__ */$(M.View,{style:[i.panel,{width:d,paddingTop:Math.max(
|
|
227
|
+
/* @__PURE__ */$(z,{style:Mb,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Jp.closeA11y,children:/* @__PURE__ */$(M.View,{style:[i.backdrop,{opacity:p}]})}),
|
|
228
|
+
/* @__PURE__ */$(M.View,{style:[i.panel,{width:d,paddingTop:Math.max(ww,s.top+l.space.md),transform:[{translateX:g}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */W(I,{style:i.keyboardAvoider,behavior:m.OS==="ios"?"padding":"height",children:[
|
|
229
229
|
/* @__PURE__ */W(x,{style:i.header,children:[
|
|
230
|
-
/* @__PURE__ */$(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:
|
|
231
|
-
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
232
|
-
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
230
|
+
/* @__PURE__ */$(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:Jp.heading}),
|
|
231
|
+
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Jp.newChat,style:i.newChat,onPress:t.newConversation,children:/* @__PURE__ */$(Text,{tier:"control",style:i.newChatLabel,children:Jp.newChat})}),
|
|
232
|
+
/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Jp.close,hitSlop:0,style:i.closeButton,onPress:t.close,children:/* @__PURE__ */$(CloseGlyph,{size:Tw,color:l.color.text.muted,strokeWidth:1.75})})]}),
|
|
233
233
|
/* @__PURE__ */W(x,{style:i.searchPill,children:[
|
|
234
|
-
/* @__PURE__ */$(SearchGlyph,{size:
|
|
235
|
-
/* @__PURE__ */$(
|
|
236
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:i.countLabel,children:
|
|
237
|
-
/* @__PURE__ */$(B,{data:b,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */$(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:b.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:w,onEndReached:t.loadMore,onEndReachedThreshold:
|
|
238
|
-
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
234
|
+
/* @__PURE__ */$(SearchGlyph,{size:Pw,color:l.color.text.muted,strokeWidth:1.5}),
|
|
235
|
+
/* @__PURE__ */$(mf,{value:t.query,onChangeText:e=>t.setQuery(e.replace(/^\s+/,"")),style:i.searchInput,placeholder:Jp.searchPlaceholder,placeholderTextColor:l.color.text.placeholder,accessibilityLabel:Jp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
236
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:i.countLabel,children:rg(t.rows.length,v)}),t.error!==null&&!y?/* @__PURE__ */$(x,{style:i.errorCard,children:/* @__PURE__ */$(Text,{style:i.errorText,accessibilityRole:"alert",children:t.error})}):null,
|
|
237
|
+
/* @__PURE__ */$(B,{data:b,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */$(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:b.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:w,onEndReached:t.loadMore,onEndReachedThreshold:jw})]})})]})})}function Row({row:e,active:t,disabled:r,styles:n,onPress:l}){let i=e.unreadCount!==null&&e.unreadCount>0,o=tg(e);/* @__PURE__ */
|
|
238
|
+
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:ng(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:l,children:[
|
|
239
239
|
/* @__PURE__ */W(x,{style:n.itemRow,children:[
|
|
240
|
-
/* @__PURE__ */$(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:
|
|
240
|
+
/* @__PURE__ */$(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:Xp(e.title)}),i?/* @__PURE__ */$(x,{style:n.unreadDot}):null]}),o!==null?/* @__PURE__ */$(Text,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:o}):null]})}function Dw(e){let t=e.color,r=e.space,n=e.type,l=e.slots,i=t.text.primary,o=pb(l.card);return v.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Cw},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:v.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md,...gk(l.dialog,v.hairlineWidth)},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:n.size.subtitle,color:i,...pb(l.dialog)},newChat:{minHeight:Rw,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...face(e,"bold"),fontSize:xw,color:t.brandInk},closeButton:{width:Rw,height:Rw,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+Ew,paddingVertical:r.sm+Ew,borderWidth:1,borderColor:t.borderRingCream,...fb(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0,...pb(l.input)},countLabel:{...face(e,"mono"),fontSize:_w,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+Ew,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:Ew},itemActive:{backgroundColor:wo(t.highlight,Sw)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:i},itemMeta:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:Ow,height:Ow,borderRadius:Ow/2,backgroundColor:t.danger},errorCard:{borderRadius:zw,borderWidth:v.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...face(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:Iw,padding:r.md+Ew,gap:r.xs+Ew,backgroundColor:t.surfaceSubtle,borderWidth:v.hairlineWidth,borderColor:t.borderRingCream,...fb(l.card,v.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:n.size.bodyTight,color:i,...o},emptyBody:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.secondary,...o},noMatch:{...face(e,"regular"),fontSize:n.size.bodyTight,color:t.text.muted,paddingVertical:r.sm},retrySlot:{marginTop:r.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:r.md+Ew,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...fb(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...pb(l.primaryButton)},loadMoreFooter:{paddingVertical:r.md+Ew,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}function Mw(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let l=new Date(t);l.setHours(0,0,0,0);let i=new Date(n);i.setHours(0,0,0,0);let o=Math.round((l.getTime()-i.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 Lw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function Bw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=Mw(n.updatedAt,t)??"",l=r[r.length-1];l!==void 0&&l.day===e?l.rows.push(n):r.push({day:e,rows:[n]})}return r}var Hw="rgba(38,37,35,0.38)",Uw=28,Nw=40,$w=5,Ww=11,Vw=10.5,qw=36,Gw=11,Kw=14,Yw=15,Qw=13.5,Zw=48,Jw=2,Xw=1.3,eC=.12,tC=16,rC=8,nC="80%";function lC(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */$(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:t,sheet:r}){let n=useEverfurTheme(),l=a(()=>iC(n),[n]),i=U(),o=a(()=>Bw(t.rows),[t.rows]),s=Wf();if(!t.open)return null;let u=n.color,c=r?.title?.trim(),d=c!==void 0&&c!==""?c:Jp.heading;/* @__PURE__ */
|
|
241
241
|
return $(O,{visible:true,transparent:true,animationType:"slide",onRequestClose:t.close,children:/* @__PURE__ */W(x,{style:l.root,children:[
|
|
242
|
-
/* @__PURE__ */$(z,{style:[
|
|
243
|
-
/* @__PURE__ */W(x,{style:
|
|
242
|
+
/* @__PURE__ */$(z,{style:[Mb,l.scrim],onPress:t.close,accessibilityRole:"button",accessibilityLabel:Jp.closeA11y}),
|
|
243
|
+
/* @__PURE__ */W(x,{style:Vf([l.sheet,{paddingBottom:Math.max(40,i.bottom+n.space.lg)}],s),accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
|
|
244
244
|
/* @__PURE__ */$(x,{style:l.grab}),
|
|
245
245
|
/* @__PURE__ */W(x,{style:l.top,children:[
|
|
246
246
|
/* @__PURE__ */$(Text,{tier:"compact",style:l.kicker,accessibilityRole:"header",children:d}),
|
|
247
|
-
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
248
|
-
/* @__PURE__ */W(E,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */W(x,{style:l.state,accessibilityLabel:
|
|
247
|
+
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Jp.closeA11y,onPress:t.close,style:l.close,children:lC(r,"close",/* @__PURE__ */$(CloseGlyph,{size:22,color:u.text.primary,strokeWidth:2}))})]}),
|
|
248
|
+
/* @__PURE__ */W(E,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */W(x,{style:l.state,accessibilityLabel:Jp.loading,accessibilityState:{busy:true},children:[
|
|
249
249
|
/* @__PURE__ */$(j,{color:u.brandInk}),
|
|
250
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:l.mono,children:
|
|
251
|
-
/* @__PURE__ */$(Text,{style:l.stateText,accessibilityRole:"alert",children:
|
|
252
|
-
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
253
|
-
return W(z,{accessibilityRole:"button",accessibilityLabel:
|
|
254
|
-
/* @__PURE__ */$(x,{style:l.icon,children:
|
|
250
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:l.mono,children:Jp.loading})]}):null,t.error!==null?/* @__PURE__ */W(x,{style:l.state,children:[
|
|
251
|
+
/* @__PURE__ */$(Text,{style:l.stateText,accessibilityRole:"alert",children:Jp.loadFailed}),
|
|
252
|
+
/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Jp.retry,onPress:()=>{t.load()},style:l.link,children:/* @__PURE__ */$(Text,{tier:"control",style:l.linkText,children:Jp.retry})})]}):null,!t.loading&&t.error===null&&t.rows.length===0?/* @__PURE__ */$(Text,{style:[l.stateText,l.state],children:Jp.empty}):null,o.map((n,i)=>/* @__PURE__ */W(p,{children:[n.day?/* @__PURE__ */$(Text,{tier:"compact",style:[l.mono,l.day,i===0?l.dayFirst:null],children:n.day}):null,n.rows.map(n=>{let i=n.id===e.conversationId,o=n.unreadCount!==null&&n.unreadCount>0,a=Lw(n.updatedAt);/* @__PURE__ */
|
|
253
|
+
return W(z,{accessibilityRole:"button",accessibilityLabel:ng(n),accessibilityState:{selected:i},onPress:()=>{t.resume(n.id)},style:[l.row,i?l.rowCurrent:null],children:[
|
|
254
|
+
/* @__PURE__ */$(x,{style:l.icon,children:lC(r,"chat",/* @__PURE__ */$(ChatBubbleGlyph,{size:19,color:u.linkInk,strokeWidth:1.75}))}),
|
|
255
255
|
/* @__PURE__ */W(x,{style:l.rowWords,children:[
|
|
256
|
-
/* @__PURE__ */$(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:
|
|
257
|
-
/* @__PURE__ */W(x,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */$(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */$(x,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:
|
|
258
|
-
/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:
|
|
259
|
-
/* @__PURE__ */$(Text,{tier:"control",style:l.newChatText,children:
|
|
256
|
+
/* @__PURE__ */$(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:Xp(n.title)}),n.preview!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:l.preview,numberOfLines:1,children:n.preview}):null]}),
|
|
257
|
+
/* @__PURE__ */W(x,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */$(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */$(x,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Jp.more,onPress:t.loadMore,style:l.link,children:/* @__PURE__ */$(Text,{tier:"control",style:l.linkText,children:Jp.more})}):null]}),
|
|
258
|
+
/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:Jp.newChat,onPress:t.newConversation,style:l.newChat,children:[lC(r,"edit",/* @__PURE__ */$(EditGlyph,{size:18,color:n.slots.primaryButton?.textColor??u.onPrimary,strokeWidth:1.75})),
|
|
259
|
+
/* @__PURE__ */$(Text,{tier:"control",style:l.newChatText,children:Jp.newChat})]})]})]})})}function iC(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:Vw,letterSpacing:Vw*.06,textTransform:"uppercase",color:t.text.muted};return v.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:Hw},sheet:{maxHeight:nC,backgroundColor:t.surface,borderTopLeftRadius:Uw,borderTopRightRadius:Uw,paddingTop:10,paddingHorizontal:20},grab:{width:Nw,height:$w,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...n,fontSize:Ww,letterSpacing:Ww*.08,flexShrink:1},close:{width:am,height:am,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:am/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:r.xs},mono:n,day:{marginTop:r.lg,marginBottom:r.xs},dayFirst:{marginTop:Jw},state:{marginVertical:r.md,gap:r.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:am,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:r.md,paddingVertical:10,paddingHorizontal:r.sm,borderRadius:Kw,minHeight:am},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:qw,height:qw,borderRadius:Gw,backgroundColor:wo(t.linkInk,eC)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:Yw,lineHeight:Yw*Xw,color:t.text.primary},preview:{...face(e,"regular"),fontSize:Qw,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:Vw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:rC,height:rC,borderRadius:rC/2,backgroundColor:t.danger},newChat:{marginTop:r.lg,minHeight:Zw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...fb(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:tC,color:t.onPrimary,...pb(e.slots.primaryButton)}})}var oC="Close",aC=/* @__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:`${sC(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function sC(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={...aC,...t.copy},l={pet:e.pet,possessive:healthPlanPossessive(e.pet)},i=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,a=o===void 0?null:n.action(l),s=n.close(l),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(l)?.trim()||r.kicker,s=n.resultsClose(l),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,...i===void 0?{}:{badge:i},title:r.title,results:[f,...c.rows??[]],...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?oC:s,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...i===void 0?{}:{badge:i},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?oC:s,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function uC(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function cC(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var dC=20,fC=14,hC=16,pC=18,gC=22,bC=15,mC=12,yC=24,vC=15,kC=14.5,wC=21,CC=14.5,SC=18,xC=9,_C=36,RC=14,TC=15,IC=8,zC=40;function TopCard({card:e,open:t,onOpenChange:r,ask:n}){let l=useEverfurTheme(),i=dw(),o=a(()=>i!==null?OC(i):EC(l),[l,i]),s=a(()=>fb(l.slots.card),[l.slots.card]);if(!t)return null;let u=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:Qf.close,c=e.action,d=e.ask,f=/* @__PURE__ */$(CloseGlyph,{size:i!==null?HOME_CLOSE_GLYPH(i):SC,color:i!==null?String(i.text(".ask-focus__x").color):l.color.text.primary,strokeWidth:2});/* @__PURE__ */
|
|
260
260
|
return W(x,{style:[o.card,s],testID:"everfur-top-card",children:[
|
|
261
261
|
/* @__PURE__ */W(x,{style:o.kickerRow,children:[
|
|
262
|
-
/* @__PURE__ */$(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */$(x,{style:o.badge,children:/* @__PURE__ */$(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */$(z,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?
|
|
262
|
+
/* @__PURE__ */$(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */$(x,{style:o.badge,children:/* @__PURE__ */$(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */$(z,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?PC:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */$(HostRender,{render:()=>e.renderIcon?.("close"),fallback:f}):f}):null]}),
|
|
263
263
|
/* @__PURE__ */$(Text,{tier:"heading",style:o.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */W(x,{style:o.finding,children:[
|
|
264
264
|
/* @__PURE__ */$(x,{style:o.dot}),
|
|
265
|
-
/* @__PURE__ */W(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */$(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */W(x,{style:o.actions,children:[c!==void 0?/* @__PURE__ */$(z,{onPress:()=>{
|
|
266
|
-
return W(z,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?
|
|
265
|
+
/* @__PURE__ */W(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */$(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */W(x,{style:o.actions,children:[c!==void 0?/* @__PURE__ */$(z,{onPress:()=>{Uh(c.onPress)},accessibilityRole:"button",accessibilityLabel:c.label,style:o.action,hitSlop:i!==null?PC:void 0,children:/* @__PURE__ */$(Text,{tier:"control",style:o.actionText,children:c.label})}):null,d!==void 0?/* @__PURE__ */$(z,{onPress:()=>n(d.prompt),accessibilityRole:"button",accessibilityLabel:d.label,style:o.ask,hitSlop:i!==null?PC:void 0,children:/* @__PURE__ */$(Text,{tier:"control",style:o.askText,children:d.label})}):null]}):null]})}function TopCardPill({card:e,open:t,onOpenChange:r}){let n=useEverfurTheme(),l=dw(),i=a(()=>l!==null?OC(l):EC(n),[n,l]);if(t||e.closeLabel===void 0)return null;let o=e.pill??e.kicker;/* @__PURE__ */
|
|
266
|
+
return W(z,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?PC:void 0,testID:"everfur-top-card-pill",children:[
|
|
267
267
|
/* @__PURE__ */$(x,{style:i.pillDot}),
|
|
268
|
-
/* @__PURE__ */$(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var _C=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:yC};function RC(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"),l=typeof n.height=="number"?n.height:vC;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-l)/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 TC(e){let t=e.color,r=e.space;return v.create({card:{paddingTop:aC,paddingHorizontal:sC,paddingBottom:sC,borderRadius:oC,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:rm-8},kicker:{...iC(e),fontSize:dC,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:hC,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:fC,color:t.text.secondary},close:{width:rm,height:rm,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:rm/2},title:{...iC(e),fontSize:uC,lineHeight:cC,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:vC,height:vC,borderRadius:vC/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:gC,lineHeight:bC,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(xC,rm),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:pC,color:t.onPrimary},ask:{minHeight:rm,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:mC,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(kC,rm),paddingHorizontal:wC,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:SC,height:SC,borderRadius:SC/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:CC,color:t.danger,flexShrink:1}})}var IC=/* @__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"}),zC=/* @__PURE__ */new WeakMap;function PC(e){let t=zC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=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,...IC},i=(e,t)=>yo(e,t,uo(t),OC),o=(e,t)=>contrastRatio(e,t)>=OC?e:so(t,OC),a=[l.card,l.paper].map(e=>go(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return zC.set(e,u),u}var OC=4.5;function EC(e,t){for(let r of t)if(contrastRatio(r,e)>=OC)return r;return so(e,OC)}function jC(e,t,r){let n=bo(e,t);return(n===null?null:go(n,r))??r}function FC(e){let t=PC(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:EC(t.accent,[t.ink,t.onAccent]),accent2:jC(t.accent,.75,n),accent4:jC(t.accent,.17,n),accentChip:jC(t.accent,.47,n),link:t.link,linkChip:jC(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 AC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),DC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),MC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],LC=17,BC=1.5,HC=400,UC=700;function NC(e){return e<=450?"regular":e<=650?"medium":"bold"}function $C(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function WC(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:$C(r)}}let n=t==="$serif"?headingFace(e,NC(r)):face(e,NC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:$C(r)}}function VC(e,t,r={}){let n=FC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?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},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;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]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,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=s(e),l={};for(let[e,t]of Object.entries(n))AC.has(e)||DC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of MC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:LC,u=typeof o.lh=="number"?o.lh:BC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...WC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*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(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(HC,e),strong:(...e)=>f(UC,e),icon:(...e)=>{let t=s(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=s([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 l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(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)=>s(t)[e]}}var qC={".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"]}},GC=16;var KC=4e3,YC=.5;function QC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function JC(e,t,r){if(e.length===0)return r;let n=QC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=YC*e.length+1;for(let o of l)if(QC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=v.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=c({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[u,d]=l(null),f=u!==null&&u.key===o?u.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=JC(t,l,(e.ch+YC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
269
|
-
return W(x,{style:
|
|
268
|
+
/* @__PURE__ */$(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var PC=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:SC};function OC(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"),l=typeof n.height=="number"?n.height:xC;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-l)/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 EC(e){let t=e.color,r=e.space;return v.create({card:{paddingTop:fC,paddingHorizontal:hC,paddingBottom:hC,borderRadius:dC,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:am-8},kicker:{...cC(e),fontSize:bC,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:yC,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:mC,color:t.text.secondary},close:{width:am,height:am,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:am/2},title:{...cC(e),fontSize:pC,lineHeight:gC,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:xC,height:xC,borderRadius:xC/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:kC,lineHeight:wC,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(zC,am),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:vC,color:t.onPrimary},ask:{minHeight:am,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:CC,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(_C,am),paddingHorizontal:RC,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:IC,height:IC,borderRadius:IC/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:TC,color:t.danger,flexShrink:1}})}var jC=/* @__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"}),FC=/* @__PURE__ */new WeakMap;function AC(e){let t=FC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=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,...jC},i=(e,t)=>So(e,t,go(t),DC),o=(e,t)=>contrastRatio(e,t)>=DC?e:po(t,DC),a=[l.card,l.paper].map(e=>ko(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return FC.set(e,u),u}var DC=4.5;function MC(e,t){for(let r of t)if(contrastRatio(r,e)>=DC)return r;return po(e,DC)}function LC(e,t,r){let n=wo(e,t);return(n===null?null:ko(n,r))??r}function BC(e){let t=AC(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:MC(t.accent,[t.ink,t.onAccent]),accent2:LC(t.accent,.75,n),accent4:LC(t.accent,.17,n),accentChip:LC(t.accent,.47,n),link:t.link,linkChip:LC(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 HC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),UC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),NC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],$C=17,WC=1.5,VC=400,qC=700;function GC(e){return e<=450?"regular":e<=650?"medium":"bold"}function KC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function YC(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:KC(r)}}let n=t==="$serif"?headingFace(e,GC(r)):face(e,GC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:KC(r)}}function QC(e,t,r={}){let n=BC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?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},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;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]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,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=s(e),l={};for(let[e,t]of Object.entries(n))HC.has(e)||UC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of NC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:$C,u=typeof o.lh=="number"?o.lh:WC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...YC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*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(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(VC,e),strong:(...e)=>f(qC,e),icon:(...e)=>{let t=s(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=s([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 l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(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)=>s(t)[e]}}var ZC={".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"]}},JC=16;var XC=4e3,eS=.5;function tS(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function rS(e,t,r){if(e.length===0)return r;let n=tS(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=eS*e.length+1;for(let o of l)if(tS(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=v.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=c({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[u,d]=l(null),f=u!==null&&u.key===o?u.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=rS(t,l,(e.ch+eS)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
269
|
+
return W(x,{style:nS.wrap,children:[
|
|
270
270
|
/* @__PURE__ */$(Text,{tier:"heading",style:f===null?t:[t,{maxWidth:f}],accessibilityRole:"header",children:e}),
|
|
271
|
-
/* @__PURE__ */$(x,{style:
|
|
271
|
+
/* @__PURE__ */$(x,{style:nS.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */W(x,{style:nS.probeRow,children:[
|
|
272
272
|
/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
|
|
273
|
-
/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var
|
|
274
|
-
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:
|
|
273
|
+
/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var nS=v.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:XC,flexDirection:"row",alignItems:"flex-start"}});function lS(e){return{kit:QC(e,ZC),Title:BalancedTitle,titleCh:JC}}var iS=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function oS(){let e=globalThis,t=e[iS];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[iS]=r,r}var aS=e=>{let t=oS();return t.listeners.add(e),()=>t.listeners.delete(e)},sS=()=>oS().count>0;function useHostPoweredBy(){return i(aS,sS,sS)}var uS=/* @__PURE__ */Object.freeze({}),cS=100,dS=20;function fS(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 hS(e,t){let r=typeof e=="number"&&Number.isFinite(e),i=c(null),[o,s]=l(null),d=c(null),f=c(null),h=c(true),p=u(()=>{f.current!==null&&clearTimeout(f.current),f.current=null},[]);n(()=>(h.current=true,()=>{h.current=false,p()}),[p]);let g=u(function e(t){i.current?.measureInWindow((r,n)=>{let l=d.current;if(!h.current||l===null)return;let i=fS(n,l.y,l.height,C.get("window").height);if(i!==null){s(e=>e!==null&&e.chatTop===i.chatTop&&e.parentTop===i.parentTop?e:i);return}t>=dS||(f.current=setTimeout(()=>{f.current=null,e(t+1)},cS))})},[]),b=u(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current={y:t,height:r},p(),g(0)},[g,p]);return a(()=>{if(!t)return{avoidingProps:r?{keyboardVerticalOffset:e}:uS,probeRef:null,topInWindow:null};let n=o?.parentTop??0;return{avoidingProps:r?{keyboardVerticalOffset:e,onLayout:b}:n>0?{keyboardVerticalOffset:n,onLayout:b}:{onLayout:b},probeRef:i,topInWindow:o?.chatTop??null}},[t,r,e,o,b])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */$(x,{ref:e,collapsable:false,pointerEvents:"none",style:pS})}var pS=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function gS(){let[e,t]=l(false);return n(()=>{let e=P;if(typeof e?.addListener!="function")return;let r=m.OS==="ios",n=e.addListener(r?"keyboardWillShow":"keyboardDidShow",()=>t(true)),l=e.addListener(r?"keyboardWillHide":"keyboardDidHide",()=>t(false));return()=>{n.remove(),l.remove()}},[]),e}function bS(e,t,r){return So(e,t,go(t),r)}function mS(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=rk(t),l=r?n.warning:n.info,i=tk(t)&&!l?e:yS(e,t,r);return vS(i,t.slots.banner)}function yS(e,t,r){let n=t.color,l=ko(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=bS(ko(i,n.surface)??i,[n.surface,n.chatGround],Lo),a=bS(r?n.warningStrong:n.info,[l,n.surface],Po);/* @__PURE__ */
|
|
274
|
+
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:bS(n.text.primary,[l],Po),pillColor:n.surface})}function vS(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 kS(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 wS=.75,CS=1.5,SS=.4,xS=4,_S=1.5,RS=22,TS=14,IS=8,zS=20,PS=10,OS=13,ES=12,jS=15,FS=44,AS=14,DS=1.25,MS=14,LS=6,BS=2;function HS(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:wo(r.danger,SS)??r.danger,borderWidth:CS},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:wS,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,compact:i=false}){let o=useEverfurTheme(),s=a(()=>US(o),[o]),u=Lg(),c=e.tier===null?null:mS(e.tier,o),d=e.source;/* @__PURE__ */
|
|
275
275
|
return W(V,{children:[
|
|
276
276
|
/* @__PURE__ */$(FadePresence,{visible:e.showBanner&&c!==null,inMs:u.bannerInMs,outMs:u.bannerOutMs,style:s.pinned,children:c!==null&&d!==null?/* @__PURE__ */$(BannerCard,{tier:c,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,styles:s,compact:i}):null}),
|
|
277
|
-
/* @__PURE__ */$(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
277
|
+
/* @__PURE__ */$(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.showLatestVetAlert,hitSlop:PS,onPress:e.expand,children:/* @__PURE__ */$(InfoGlyph,{size:zS,color:o.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:r,petRef:n,renderVetAction:l,onFindVet:i,vet:o,styles:a,compact:s}){let u=useEverfurTheme(),c=HS(u,e),d=/* @__PURE__ */$(VetAction,{tier:e,paint:c,petRef:n,onFindVet:i,vet:o,styles:a}),f=r.showVetAction?l!==void 0?/* @__PURE__ */$(HostRender,{render:()=>l(e.level),fallback:d,resetKey:e.level}):d:null,h=c.action!==null?/* @__PURE__ */$(PoisonControl,{paint:c.action,styles:a}):null,p=e.level==="emergency"&&i===void 0,g=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
|
|
278
278
|
return W(x,{...g?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[a.card,c.card,s?a.cardCompact:null],testID:s?"chat-urgency-compact":void 0,children:[
|
|
279
|
-
/* @__PURE__ */$(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */$(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?
|
|
280
|
-
return $(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
281
|
-
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:u?
|
|
282
|
-
/* @__PURE__ */$(MapPinGlyph,{size:
|
|
283
|
-
/* @__PURE__ */$(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=
|
|
284
|
-
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
285
|
-
/* @__PURE__ */$(MapPinGlyph,{size:
|
|
286
|
-
/* @__PURE__ */$(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:
|
|
287
|
-
/* @__PURE__ */$(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */$(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:
|
|
288
|
-
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:
|
|
279
|
+
/* @__PURE__ */$(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */$(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?BS:void 0,accessibilityLabel:s?t:void 0,children:t}):null,p?/* @__PURE__ */$(Text,{style:[a.reason,a.erLine,{color:c.reason}],children:Qf.goToNearestEmergencyVet}):null,f!==null||h!==null?/* @__PURE__ */W(x,{style:a.actions,children:[f,h]}):null,r.dismissLabel!==null?/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:IS,containerStyle:a.closeSlot,style:a.closeButton,onPress:r.dismiss,children:/* @__PURE__ */$(CloseGlyph,{size:TS,color:c.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let r=()=>{try{T.openURL(eh).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
280
|
+
return $(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:/* @__PURE__ */$(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:Qf.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:i}){let o=useEverfurTheme(),a=useVetVisit(kS(r,l)),s=a.status==="opening",u=!a.available&&n!==void 0,c=a.available?()=>{a.open()}:n!==void 0?()=>{Uh(n,e.level)}:null;if(c===null)return null;let d=t.action;if(d!==null){let e=u?Qf.nearestEmergencyVet:Qf.findVet,t=hb(o.slots.vetVisitButton)?.textColor??d.ink;/* @__PURE__ */
|
|
281
|
+
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:u?Qf.nearestEmergencyVet:Qf.findVetA11y,accessibilityState:{busy:s},hitSlop:0,style:[i.action,{backgroundColor:d.fill,borderColor:d.edge},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
282
|
+
/* @__PURE__ */$(MapPinGlyph,{size:OS,color:t,strokeWidth:1.5}),
|
|
283
|
+
/* @__PURE__ */$(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=hb(o.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
|
|
284
|
+
return W(PressScale,{accessibilityRole:"button",accessibilityLabel:Qf.findVetA11y,accessibilityState:{busy:s},style:[i.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
285
|
+
/* @__PURE__ */$(MapPinGlyph,{size:OS,color:f,strokeWidth:1.5}),
|
|
286
|
+
/* @__PURE__ */$(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:Qf.findVet})]})}function US(e){let t=hb(e.slots.vetVisitButton),r=e.space,n=e.type;return v.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+xS,paddingVertical:r.lg,gap:r.sm},cardCompact:{paddingVertical:r.md,gap:r.xs},label:{...face(e,"bold"),fontSize:n.size.body,paddingRight:RS},reason:{...face(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*_S),paddingRight:RS},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:LS,minHeight:FS,paddingHorizontal:AS,borderRadius:e.radius.pill,borderWidth:DS},actionLabel:{...face(e,"bold"),fontSize:MS},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...fb(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:ES,lineHeight:jS},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:RS,height:RS,borderRadius:RS/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}function NS(e,t,r,i){let[o,a]=l({pet:r,user:t}),s=o.pet!==r||o.user===null&&t!==null;s&&a({pet:r,user:t});let u=s?{user:t}:o,c=r!==null&&u.user!==null&&u.user!==t;return n(()=>{if(!c||t===null||r===null)return;let n=true,l=createPetsRepository(e.registry.services.authFor(t)),i=async()=>{let e=await l.list();n&&e.ok&&e.value.some(e=>e.petRef===r)&&a({pet:r,user:t})};i();let o=Vi(e,()=>{i()});return()=>{n=false,o()}},[c,e,t,r,i]),c}var $S=/* @__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:t,userRef:r,activePet:o,scopeEpoch:s}=Rd(),d=e?.petRef??o??null,f=e?.conversationId??null,h=NS(t,r,d,s),p=a(()=>({runtime:t,userRef:r,petRef:d,conversationId:f,scopeEpoch:s,held:h}),[t,r,d,f,s,h]),[g,b]=l(null),m=h?null:g?.scope===p?g.controller:t.registry.peekChat({userRef:r,petRef:d,conversationId:f}),y=c(null);n(()=>{if(h)return;let e=t.registry.acquireChat({userRef:r,petRef:d,conversationId:f});return y.current=e,b({scope:p,controller:e}),()=>{y.current=null,b(t=>t?.controller===e?null:t),t.registry.releaseChat(e)}},[t,r,d,f,s,h,p]);let v=u(e=>m?m.subscribe(e):NOOP_UNSUBSCRIBE,[m]),k=u(()=>m?m.getSnapshot():$S,[m]),w=i(v,k,k),C=u((e,t)=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?VS(m,m.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>y.current===m):Promise.resolve(GS()),[m]),S=u(e=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?VS(m,m.askEverfur(e),()=>y.current===m):Promise.resolve(GS()),[m]),x=u(()=>m&&y.current===m?VS(m,m.retryLast(),()=>y.current===m):Promise.resolve(GS()),[m]),_=u(()=>{m&&y.current===m&&m.stop()},[m]),R=u(()=>{m&&y.current===m&&m.newConversation()},[m]),[T,I]=l({controller:null,byMessage:{}}),z=T.controller===m?T.byMessage:WS,P=u(async(e,t,r,n)=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let l=String(e),i=T.controller===m?T.byMessage[l]:void 0;if(i===t&&r==null)return I(e=>{let t={...e.controller===m?e.byMessage:{}};return delete t[l],{controller:m,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));I(e=>({controller:m,byMessage:{...e.controller===m?e.byMessage:{},[l]:t}}));let o=await m.submitFeedback(e,Yk(t,r??null),n??null);return y.current!==m?err(makeEverfurError("accessDenied")):(o.ok||I(e=>{let t={...e.controller===m?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:m,byMessage:t}}),o)},[m,T]),O=a(()=>{let e=async e=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let t=await e(m);return y.current===m?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...d?{petRef:d}:{},...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))}},[m,d]);return a(()=>({status:w.status,messages:w.messages,conversationId:w.conversationId,petRef:d,error:w.error,isStreaming:w.isStreaming,isBootstrapping:w.isBootstrapping,historyCursor:w.historyCursor??null,isLoadingHistory:w.isLoadingHistory??false,stopped:w.stopped??false,reconnecting:w.reconnecting??false,...O,suggestedPrompts:w.suggestedPrompts,unreadCount:w.unreadCount,hasUnreadThreads:w.hasUnreadThreads??false,pendingCheckin:w.pendingCheckin??null,newConversation:R,sentimentByMessage:z,feedback:P,send:C,askEverfur:S,retryLast:x,stop:_}),[w,d,C,S,x,_,O,R,z,P])}var NOOP_UNSUBSCRIBE=()=>{},WS=/* @__PURE__ */Object.freeze({});async function VS(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(qS(n.messages))}function qS(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 GS(){return _p()}function KS(){let e=useEverfurPets(),{handle:t}=Rd(),r=u(e=>t.setActivePet(e),[t]);return a(()=>({...e,setActivePet:r}),[e,r])}function YS(){try{let e=k?.announceForAccessibility;typeof e=="function"&&e.call(k,Qf.answered)}catch{}}function QS(e){let t=c(false),r=c({send:e.send,id:e.conversationId});n(()=>{let n=r.current;if((n.send!==e.send||n.id!==null&&n.id!==e.conversationId)&&(t.current=false),r.current={send:e.send,id:e.conversationId},t.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&YS()}t.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var ZS=/* @__PURE__ */Object.freeze({kind:"live"}),JS=/* @__PURE__ */Object.freeze({kind:"folded"});function XS(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=jn(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function ex(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=XS(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 l of e){let e=XS(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,ZS),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,JS);continue}let i=[e.dueDay];n={id:l.id,caseId:e.caseId,days:i},t.set(l.id,{kind:"past",runDueDays:i})}return t}function tx(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var rx=864e5,nx=365;function lx(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 l=Math.floor(n/rx)-Math.floor(r/rx);return l<1||l>nx?null:l}function ix(e){return XS(e)?.dueDay||null}function ox(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:r}){let n=Yv(e);return n.shown?/* @__PURE__ */W(x,{style:r.assistantSender,testID:"everfur-assistant-sender",children:[
|
|
287
|
+
/* @__PURE__ */$(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */$(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:Qf.assistantName}):null]}):t?/* @__PURE__ */$(Text,{tier:"control",style:r.assistantName,children:Qf.assistantName}):null}var ax=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),sx="#C8BEB4";function ux(e){return e?ax[e.toUpperCase()]??sx:sx}function cx(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function dx(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function fx(e){let t=dx(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function hx(e,t){let r=dx(e.source_name)??dx(e.sourceName),n=dx(e.section),l=dx(e.authority_tier)??dx(e.authorityTier),i=cx(l),o=r??dx(e.title)??`Source ${t+1}`,a=dx(e.monograph_chunk_id)??dx(e.chunkId),s=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
|
|
288
|
+
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:fx(e.url),excerpt:dx(e.excerpt),tierColor:ux(l),key:`${o}-${a??"none"}-${t}`})}function px(e){return e===void 0||e.length===0?gx:/* @__PURE__ */Object.freeze(e.map((e,t)=>hx(e,t)))}var gx=/* @__PURE__ */Object.freeze([]);function bx(e){return e===1?`1 ${Qf.sourceSingular}`:`${e} ${Qf.sourcePlural}`}function mx(e,t){return`${t?Qf.hideSources:Qf.showSources} ${bx(e)}`}function yx(e){return[e.url!==null?`${Qf.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function vx(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var kx=/^\s*[-*]\s+(\S.*)$/,wx=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function Cx(e){let t=[],r=[],n=null,l=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},i=()=>{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=kx.exec(t),o=e===null?wx.exec(t):null,a=e?.[1]??o?.[2];if(a===void 0){i(),r.push(t);continue}let s=o!==null;l(),n!==null&&n.ordered!==s&&i(),n===null&&(n={ordered:s,start:o===null?1:Number(o[1]),items:[]}),n.items.push(a.trim())}return l(),i(),t}function Sx(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 xx(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function _x(e){return hardenHttpsUrl(e.trim())}function Rx(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?[]:xx(t.followUpActions,{answer:r.text,question:Sx(e.messages,r.id),messageId:r.id})}var Tx=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,Ix=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${kg}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${kg}})`,"gi"),zx=/https:\/\//i,Px=`.,;:!?'"`;function Ox(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&zx.test(e)}function Ex(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):Ax(r,e,t)},l=0;Tx.lastIndex=0;for(let t=Tx.exec(e);t!==null;t=Tx.exec(e)){t.index>l&&n(e.slice(l,t.index));let i=t[1],o=t[2],a=t[3];i!==void 0?r.push({kind:"bold",text:i}):o!==void 0?r.push({kind:"italic",text:o}):a!==void 0&&r.push({kind:"code",text:a}),l=t.index+t[0].length}return l<e.length&&n(e.slice(l)),r}function jx(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(Px.includes(r))t-=1;else if(r===")"&&Fx(e,"(",t)<Fx(e,")",t))t-=1;else break}return e.slice(0,t)}function Fx(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function Ax(e,t,r){if(!zx.test(t)){e.push({kind:"text",text:t});return}let n=0;Ix.lastIndex=0;for(let l=Ix.exec(t);l!==null;l=Ix.exec(t)){let i=l[1],o=l[2],a=l[3],s,u,c;if(i!==void 0&&o!==void 0)s=i.trim(),u=s.length>0?xg(o,r):null,c=l[0].length;else if(a!==void 0)s=jx(a),u=xg(s,r),c=s.length;else continue;u!==null&&(l.index>n&&e.push({kind:"text",text:t.slice(n,l.index)}),e.push({kind:"link",text:s,href:u}),n=l.index+c,Ix.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var Dx=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function Mx(e,t){return t===void 0||!Ox(e,t.hosts)?false:Ex(e,t.hosts).some(e=>e.kind==="link")}function Lx(e,t,r){let n=r?.hosts;return Ox(e,n)?Ex(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
|
|
289
289
|
return $(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */$(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */$(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 $(Text,{style:
|
|
291
|
-
return $(x,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */$(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?
|
|
290
|
+
return $(Text,{style:Dx,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var Bx=10.5,Hx=16,Ux=12,Nx=38,$x=11,Wx=15,Vx=22,qx=32,Gx=13.5,Kx=14,Yx=15,Qx=16,Zx=13,Jx=13,Xx=26,e_=21,t_=42,r_=1,n_=.06,l_=.07,i_=.12,o_="45%";function a_(){let e=useEverfurTheme(),t=a(()=>s_(e),[e]);return{theme:e,styles:t}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */$(ChevronGlyph,{size:Qx,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */$(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:r,styles:n}=a_();if(e.render!==void 0){let r=e.render;/* @__PURE__ */
|
|
291
|
+
return $(x,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */$(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?_x(e.tile.imageUrl):null,c=/* @__PURE__ */W(V,{children:[l?null:/* @__PURE__ */$(x,{style:[n.tile,a!==void 0?i?.tileTone?.[a]:null],children:u!==null?/* @__PURE__ */$(F,{source:{uri:u},style:n.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
|
|
292
292
|
/* @__PURE__ */W(x,{style:n.cardWords,children:[
|
|
293
293
|
/* @__PURE__ */$(Text,{tier:"control",style:n.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:n.cardMeta,children:e.meta}):null]}),l?/* @__PURE__ */W(Text,{tier:"control",style:n.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */$(Text,{style:n.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */W(V,{children:[e.pill!==void 0?/* @__PURE__ */$(x,{style:[n.pill,s!==void 0?i?.pillTone?.[s]:null],children:/* @__PURE__ */$(Text,{tier:"badge",style:[n.pillText,s!==void 0?i?.pillToneText?.[s]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */$(Chevron,{options:t,color:r.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
|
|
294
|
-
return $(z,{onPress:()=>{
|
|
295
|
-
return $(x,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=
|
|
294
|
+
return $(z,{onPress:()=>{Uh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:o,children:c})}/* @__PURE__ */
|
|
295
|
+
return $(x,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=a_(),f=a(()=>({answer:e.text,question:Sx(n,e.id),messageId:e.id}),[e.text,e.id,n]),h=!r&&e.pending!==true,p=h?xx(l?.cards,f):[],g=a(()=>h?px(e.citations):[],[h,e.citations]),b=l?.byline,m=l?.feedback!==void 0&&e.responseId!==void 0&&o!==void 0?l.feedback:null,y={bold:d.bold,italic:d.italic,code:d.code},v=Tg(),k=h?v:void 0;/* @__PURE__ */
|
|
296
296
|
return W(x,{style:d.answer,testID:"everfur-answer-cards",children:[b!==void 0?/* @__PURE__ */W(x,{style:d.byline,children:[b.icon??null,
|
|
297
297
|
/* @__PURE__ */$(Text,{tier:"compact",style:d.bylineText,children:b.label})]}):s,
|
|
298
|
-
/* @__PURE__ */$(x,{style:d.body,children:
|
|
298
|
+
/* @__PURE__ */$(x,{style:d.body,children:vx(t).flatMap((e,t)=>Cx(e).map((e,r)=>{let n=`${t}-${r}`;return e.kind==="text"?/* @__PURE__ */$(Text,{style:d.paragraph,children:Lx(e.text,y,k)},n):/* @__PURE__ */$(x,{style:d.list,children:e.items.map((t,r)=>/* @__PURE__ */W(x,{style:d.listItem,children:[
|
|
299
299
|
/* @__PURE__ */$(Text,{style:d.paragraph,children:e.ordered?`${e.start+r}.`:"•"}),
|
|
300
|
-
/* @__PURE__ */$(Text,{style:[d.paragraph,d.listText],children:
|
|
301
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:d.label,children:
|
|
300
|
+
/* @__PURE__ */$(Text,{style:[d.paragraph,d.listText],children:Lx(t,y,k)})]},r))},n)}))}),p.length>0?/* @__PURE__ */$(x,{style:d.cards,children:p.map(e=>/* @__PURE__ */$(AnswerCard,{card:e,options:l},e.key))}):null,h?/* @__PURE__ */$(ServerCardsSlot,{message:e}):null,g.length>0?/* @__PURE__ */W(x,{style:d.cards,accessibilityLabel:bx(g.length),children:[
|
|
301
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:d.label,children:Qf.sourcesHeading}),g.map(e=>{let t=e.url;/* @__PURE__ */
|
|
302
302
|
return $(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */$(SourceTileGlyph,{})},...c!==void 0&&t!==null?{onPress:()=>c(t)}:{}},options:l},e.key)})]}):null,h&&m!==null&&o!==void 0?/* @__PURE__ */W(x,{style:[d.feedback,l?.styles?.feedback],children:[
|
|
303
303
|
/* @__PURE__ */$(FeedbackChip,{label:m.helpful,on:i==="up",onPress:()=>o("up"),styles:d,host:l?.styles}),
|
|
304
304
|
/* @__PURE__ */$(FeedbackChip,{label:m.notHelpful,on:i==="down",onPress:()=>o("down"),styles:d,host:l?.styles})]}):null,h?u(m===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
|
|
305
|
-
return $(BookGlyph,{size:
|
|
306
|
-
return $(z,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(
|
|
305
|
+
return $(BookGlyph,{size:e_,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:r,styles:n,host:l}){/* @__PURE__ */
|
|
306
|
+
return $(z,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(am-qx)/2,children:/* @__PURE__ */$(Text,{tier:"control",style:[n.chipText,l?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:r,actions:n,options:l}){let{theme:i,styles:o}=a_();if(e.length===0&&n.length===0)return null;let a=l?.styles,s=r??Qf.followUpsHeadingNative;/* @__PURE__ */
|
|
307
307
|
return W(x,{style:[o.followUps,a?.followUps],accessibilityLabel:s,testID:"everfur-cards-follow-ups",children:[
|
|
308
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */W(z,{onPress:()=>{
|
|
308
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */W(z,{onPress:()=>{Uh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:r_,style:[o.row,o.rowAction,a?.followUp,a?.followUpAction],children:[e.icon??null,
|
|
309
309
|
/* @__PURE__ */$(Text,{tier:"control",style:[o.rowText,o.rowTextAction,a?.followUpText,a?.followUpActionText],children:e.label}),
|
|
310
|
-
/* @__PURE__ */$(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */W(z,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:
|
|
310
|
+
/* @__PURE__ */$(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */W(z,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:r_,style:[o.row,a?.followUp],children:[
|
|
311
311
|
/* @__PURE__ */$(Text,{tier:"control",style:[o.rowText,a?.followUpText],children:e}),
|
|
312
|
-
/* @__PURE__ */$(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=
|
|
313
|
-
return $(x,{style:t.byline,children:/* @__PURE__ */$(Text,{tier:"compact",style:t.bylineText,children:e})})}function
|
|
314
|
-
return W(x,{style:c.card,accessibilityLabel:
|
|
312
|
+
/* @__PURE__ */$(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=a_();/* @__PURE__ */
|
|
313
|
+
return $(x,{style:t.byline,children:/* @__PURE__ */$(Text,{tier:"compact",style:t.bylineText,children:e})})}function s_(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:Bx,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},i={borderWidth:1,borderColor:wo(t.text.primary,n_)??t.borderRingCream},o={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:l_,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=pb(e.slots.chip);return v.create({answer:{gap:r.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...n,letterSpacing:Bx*.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:r.sm,paddingLeft:r.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:r.sm},card:{flexDirection:"row",alignItems:"center",gap:r.md,padding:Ux,borderRadius:Hx,backgroundColor:t.surface,...i,...o,minHeight:am,...fb(e.slots.card)},tile:{width:Nx,height:Nx,borderRadius:$x,backgroundColor:wo(t.linkInk,i_)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:Nx,height:Nx},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:Wx,lineHeight:Math.round(Wx*1.25),color:t.text.primary,...pb(e.slots.card)},cardMeta:{...n,letterSpacing:Bx*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:Vx,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:Bx+2,color:t.text.muted},pill:{minHeight:Xx,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:o_},pillText:{...face(e,"bold"),fontSize:Jx,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,alignItems:"center"},chip:{minHeight:qx,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...uC(e),fontSize:Gx,color:t.text.primary,...chipInk},followUps:{gap:r.sm,alignSelf:"stretch",marginTop:r.xs},label:{...face(e,"bold"),fontSize:Zx,lineHeight:Math.round(Zx*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:t_,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:Kx,backgroundColor:t.surface,...i},rowAction:{},rowText:{...uC(e),flex:1,fontSize:Yx,lineHeight:Math.round(Yx*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var u_=/* @__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"})}),c_=/* @__PURE__ */Object.freeze(Br.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:u_.answers[e]})));function d_(e,t){let[r,n]=l(null),[i,o]=l(null),[a,s]=l(null),c=u(r=>{t!==null&&(n(r),o(null),t(e.caseId,r).then(e=>{n(null),e.ok?s(r):o(e.error)}))},[t,e.caseId]),d=a??e.answer;return{answer:d,answerable:!isCheckinSettled(e),escalated:d==="worse",pending:r,error:i,choose:c}}var f_=44,h_=.6,p_=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:l,vet:i,onLayout:o,onOpen:s}){let u=useEverfurTheme(),c=a(()=>g_(u),[u]),d=d_(t??p_,t===null?null:r),f=d.answer!==null||d.pending!==null,h=t!==null&&r!==null&&d.answerable,p=t===null?null:lx(t.openedAt,ix(e));/* @__PURE__ */
|
|
314
|
+
return W(x,{style:c.card,accessibilityLabel:u_.eyebrow,onLayout:o,children:[
|
|
315
315
|
/* @__PURE__ */W(x,{style:c.head,children:[
|
|
316
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:c.eyebrow,children:
|
|
317
|
-
return $(z,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */$(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */$(Text,{style:c.logged,children:
|
|
316
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:c.eyebrow,children:u_.eyebrow}),p!==null?/* @__PURE__ */$(Text,{tier:"compact",style:c.headDay,children:Zf(u_.day,{day:p})}):null]}),s?/* @__PURE__ */$(z,{onPress:s,accessibilityRole:"button",accessibilityLabel:e.text,style:c.open,children:/* @__PURE__ */$(Text,{style:[c.question,c.openText],children:e.text})}):/* @__PURE__ */$(Text,{style:c.question,accessibilityRole:"text",children:e.text}),h?/* @__PURE__ */$(x,{style:[c.row,d.pending?c.rowPending:null],children:c_.map(({answer:e,label:t})=>{let r=(d.pending??d.answer)===e;/* @__PURE__ */
|
|
317
|
+
return $(z,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */$(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */$(Text,{style:c.logged,children:u_.logged}):null,d.escalated?/* @__PURE__ */$(CheckinFindVet,{petRef:n??null,onFindVet:l,vet:i,styles:c}):null,t?.resolutionText?/* @__PURE__ */$(Text,{style:c.resolution,children:t.resolutionText}):null,d.error?/* @__PURE__ */$(Text,{style:c.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:r,styles:n}){return useVetVisit(kS(e,r)).available&&e!==null?/* @__PURE__ */$(VetVisitButtonCore,{entry:"chat",petRef:e,label:u_.findVet,...r?.returnTo!==void 0?{returnTo:r.returnTo}:{},...r?.usState!==void 0?{usState:r.usState}:{},...r?.prefer!==void 0?{prefer:r.prefer}:{},style:n.findVet,labelStyle:n.findVetLabel}):t===void 0?null:/* @__PURE__ */$(z,{onPress:t,accessibilityRole:"button",accessibilityLabel:u_.findVet,style:n.findVet,children:/* @__PURE__ */$(Text,{tier:"control",style:n.findVetLabel,children:u_.findVet})})}function g_(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=hb(e.slots.card),o=pb(i);return v.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:v.hairlineWidth,borderColor:t.brandBorder,...fb(i,v.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},open:{minHeight:f_,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:h_},pill:{flex:1,minHeight:f_,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.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,...o},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:f_,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var b_=244,m_=8,y_=13,v_=14,k_=.3,w_=-.24,C_=22,S_=10,x_=15;function CitationCards({citations:e,onOpenUrl:t}){let r=useEverfurTheme(),n=a(()=>__(r),[r]),i=a(()=>px(e),[e]),[o,s]=l(false);if(i.length===0)return null;let u=i.length;/* @__PURE__ */
|
|
318
318
|
return W(x,{style:n.block,children:[
|
|
319
|
-
/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
320
|
-
/* @__PURE__ */$(BookGlyph,{size:
|
|
321
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:n.toggleLabel,children:
|
|
322
|
-
/* @__PURE__ */$(ChevronGlyph,{size:
|
|
323
|
-
return $(M.View,{style:l,children:/* @__PURE__ */$(E,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */$(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=
|
|
319
|
+
/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:mx(u,o),accessibilityState:{expanded:o},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>s(e=>!e),children:[
|
|
320
|
+
/* @__PURE__ */$(BookGlyph,{size:y_,color:r.color.brandInk,strokeWidth:1.5}),
|
|
321
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:n.toggleLabel,children:bx(u)}),
|
|
322
|
+
/* @__PURE__ */$(ChevronGlyph,{size:y_,color:r.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?/* @__PURE__ */$(Deck,{cards:i,styles:n,open:t}):null]})}function Deck({cards:e,styles:t,open:r}){let n=Lg(),l=Gg(n.citationsInMs,{risePx:n.citationsRisePx});/* @__PURE__ */
|
|
323
|
+
return $(M.View,{style:l,children:/* @__PURE__ */$(E,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */$(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=yx(l?e:{...e,url:null}),o=/* @__PURE__ */W(V,{children:[
|
|
324
324
|
/* @__PURE__ */W(x,{style:t.cardHeader,children:[
|
|
325
325
|
/* @__PURE__ */$(x,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
|
|
326
|
-
/* @__PURE__ */$(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */$(ArrowUpRightGlyph,{size:
|
|
326
|
+
/* @__PURE__ */$(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */$(ArrowUpRightGlyph,{size:v_,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */$(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */$(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let n=e.url;/* @__PURE__ */
|
|
327
327
|
return $(PressScale,{accessibilityRole:"link",accessibilityLabel:i,style:t.card,onPress:()=>r(n),children:o})}/* @__PURE__ */
|
|
328
|
-
return $(x,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function
|
|
329
|
-
/* @__PURE__ */W(x,{style:[u.row,f?u.rowUser:u.rowAssistant],children:[h!==null?/* @__PURE__ */$(Text,{tier:"compact",style:u.timestamp,children:h}):null,p?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:b?
|
|
330
|
-
/* @__PURE__ */$(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
331
|
-
/* @__PURE__ */$(AnnounceLine,{line:
|
|
328
|
+
return $(x,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function __(e){let t=e.color,r=e.space,n=e.radius,l=e.type.size,i=pb(e.slots.card);return v.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:k_,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:b_,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2,...fb(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:m_,height:m_,borderRadius:n.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:C_,color:t.text.primary,letterSpacing:w_,...i},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:S_,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...i},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:x_,color:t.text.muted,...i}})}var R_=15,T_=44,I_=16,z_=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:t,sentiment:r=null,onSentiment:i,note:o=null}){let s=useEverfurTheme(),u=a(()=>P_(s),[s]),d=Lg(),f=e.role==="user",h=a(()=>ox(e.createdAt),[e.createdAt]),p=t!==void 0&&e.role!=="vet"&&e.text.length>0,g=e.role==="assistant"&&i!==void 0&&e.responseId!==void 0,[b,m]=l(false),y=c(null);n(()=>()=>{y.current&&clearTimeout(y.current)},[]);let v=()=>{t!==void 0&&(Wh(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null},d.copiedMs))};return h===null&&!p&&!g?null:/* @__PURE__ */W(x,{style:u.wrap,children:[
|
|
329
|
+
/* @__PURE__ */W(x,{style:[u.row,f?u.rowUser:u.rowAssistant],children:[h!==null?/* @__PURE__ */$(Text,{tier:"compact",style:u.timestamp,children:h}):null,p?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:b?Qf.copied:f?Qf.copyUserMessage:Qf.copyAssistantMessage,onPress:v,style:u.iconHit,children:b?/* @__PURE__ */$(CheckGlyph,{size:R_,color:s.color.success,strokeWidth:2}):/* @__PURE__ */$(CopyGlyph,{size:R_,color:s.color.text.timestamp,strokeWidth:1.5})}):null,g?Gk.map(({sentiment:e,label:t})=>/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r===e},onPress:()=>i?.(e),style:u.iconHit,children:/* @__PURE__ */$(ThumbGlyph,{size:R_,color:r===e?s.color.sentiment[e]:s.color.text.timestamp,active:r===e,rotate:z_[e],strokeWidth:1.5})},e)):null]}),o==="thanks"?/* @__PURE__ */$(Text,{style:u.thanks,accessibilityLiveRegion:"polite",children:Qf.feedbackThanks}):null,o==="failed"?/* @__PURE__ */W(V,{children:[
|
|
330
|
+
/* @__PURE__ */$(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Qf.feedbackFailed}),
|
|
331
|
+
/* @__PURE__ */$(AnnounceLine,{line:Qf.feedbackFailed})]}):null]})}function P_(e){let t=e.type;return v.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:I_,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:T_,height:T_,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 O_=16,E_=10,j_=12,F_=10,A_=2,D_=.06,M_=34,L_=9,B_=10.5,H_=.06,U_=15,N_=19.5,$_=14,W_=19.6;function OpeningCard({card:e,onLayout:t}){let r=useEverfurTheme(),n=a(()=>V_(r),[r]),l=e.styles;/* @__PURE__ */
|
|
332
332
|
return W(x,{testID:"everfur-opening-card",onLayout:t,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[n.card,l?.card],children:[e.icon!==void 0?/* @__PURE__ */$(x,{style:[n.icon,l?.icon],children:e.icon}):null,
|
|
333
333
|
/* @__PURE__ */W(x,{style:n.words,children:[
|
|
334
334
|
/* @__PURE__ */$(Text,{tier:"compact",style:[n.kicker,l?.kicker],children:e.kicker}),
|
|
335
|
-
/* @__PURE__ */$(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */$(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function
|
|
335
|
+
/* @__PURE__ */$(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */$(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function V_(e){let t=e.color;return v.create({card:{flexDirection:"row",alignItems:"flex-start",gap:F_,paddingVertical:E_,paddingHorizontal:j_,alignSelf:"stretch",borderRadius:O_,backgroundColor:t.surface,borderWidth:1,borderColor:wo(t.text.primary,D_)??t.borderRingCream},icon:{flexShrink:0,width:M_,height:M_,borderRadius:L_,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:A_},kicker:{...face(e,"mono"),fontSize:B_,letterSpacing:B_*H_,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:U_,lineHeight:N_,color:t.text.primary},body:{...face(e,"regular"),fontSize:$_,lineHeight:W_,color:t.text.secondary}})}var q_="#10462E",G_="Book a video visit",K_="#000000",Y_="#83E0B4",Q_=/* @__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:
|
|
338
|
-
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:
|
|
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
|
|
340
|
-
return 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:Y_,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:q_,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 Z_(e,t){return e?null:{fill:t.fill,ink:t.ink}}var J_=8;function X_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function eR(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=J_)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,l=X_(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:X_(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var tR=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function rR(e){return e==null?e:e.replace(tR,"").trim()}var nR=/* @__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 lR(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return nR.has(t)}function iR(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function oR(e,t){let r=e?.trim();if(r===void 0||r==="")return aR(t);let n=t?.name?.trim()||Qf.emptyTitlePetFallback,l=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?l:n)}function aR(e){let t=e?.name?.trim()||Qf.emptyTitlePetFallback;return Zf(Qf.emptyTitle,{petName:t})}function sR(e){let t=e.toLowerCase();return t===iR("dog").toLowerCase()||t===iR("cat").toLowerCase()}function uR(e){let t=rR(e);if(lR(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return sR(r)?null:r}function cR(e,t=q_,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=uR(e?.breed),o=lk(e?.ageYears),a=o===null?null:String(o),s=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
|
|
340
|
+
return Object.freeze(Q_.flatMap(e=>{let r=e.intent==="vet_report"&&s!==null?s:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!i||u&&!a)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&i===null||c.includes("{ageYears}")&&a===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&l===null))return[];let d=Zf(c,{petName:l??(n==="cat"?"my cat":"my dog"),breed:i??"",species:n??"",ageYears:a??""}),f=!l&&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 dR=44,fR=0,hR={top:3,bottom:3},pR=1,gR=.28,bR=2,mR=2,yR=1.3,vR=-.015,kR=/* @__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:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>
|
|
344
|
+
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>wR(u),[u]),d=a(()=>eR(i),[i]),f=a(()=>d!==null?d.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??u.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??u.color.text.primary}})):cR(e,u.color.brandInk,{vetPrepLabel:G_}).map(e=>({prompt:e,send:e.label,paint:null})),[d,e,u.color.brandInk,u.color.highlight,u.color.text.primary]),h=o?.chipTints!==void 0,p=a(()=>(o?.chipTints??(u.brightness==="light"?kR:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[o?.chipTints,u.brightness]),g=a(()=>p.length===0?f:f.map((e,t)=>{if(e.paint!==null)return e;let r=p[t%p.length];return{...e,paint:{fill:r.tint,ink:r.ink??u.color.text.primary},...h?{}:{cycleDefault:true}}}),[f,p,h,u.color.text.primary]),b=a(()=>Z_(tk(u),{fill:u.color.highlight,ink:u.color.onHighlight}),[u]),m=a(()=>({fill:u.color.highlight,ink:u.color.onHighlight}),[u.color.highlight,u.color.onHighlight]),y=oR(o?.title,e),v=dw(),k=fw(),w=v!==null&&k!==null?/* @__PURE__ */$(k.Title,{text:y,style:[c.title,v.text(".serif",".ask-empty h2"),c.centerText],measureCh:k.titleCh}):/* @__PURE__ */$(Text,{tier:"heading",style:s?[c.title,c.centerText]:c.title,accessibilityRole:"header",children:y});/* @__PURE__ */
|
|
345
345
|
return W(x,{style:v!==null?c.homeBlock:c.block,children:[w,
|
|
346
|
-
/* @__PURE__ */$(x,{style:v!==null?[c.list,c.listCentered,v.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:
|
|
346
|
+
/* @__PURE__ */$(x,{style:v!==null?[c.list,c.listCentered,v.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:Qf.suggestions,children:g.map(({prompt:i,send:o,paint:a,cycleDefault:u},f)=>/* @__PURE__ */$(Chip,{prompt:i,send:o,themed:a??(d!==null?m:b),index:f,petRef:t,onSend:r,onVetPrep:n,vet:l,pet:e,styles:c,tinted:a!==null&&u!==true,soft:a!==null,centered:s},i.id))})]})}function Chip({prompt:e,send:t,themed:r,index:n,pet:l,petRef:i,onSend:o,onVetPrep:a,vet:s,styles:u,tinted:c,soft:d,centered:f}){let h=Lg(),p=Gg(h.followUpInMs,{delayMs:Dg(h,n),risePx:h.promptRisePx}),g=dw(),b=g!==null?[u.chipHome,g.view(".chip")]:f&&d?u.chipNoEdge:u.chipEdge,m={backgroundColor:r?.fill??e.background},y=u.chipSlot===null?m:c?{...u.chipSlot,...m}:{...m,...u.chipSlot},v=g!==null?[u.chipLabel,g.text(".chip")]:f?[u.chipLabel,u.centerText]:[u.chipLabel],k=g!==null?hR:fR,w=r===null?u.chipSlotLabel===null?v:[...v,u.chipSlotLabel]:c?[...v,...u.chipSlotLabel===null?[]:[u.chipSlotLabel],{color:r.ink}]:[...v,{color:r.ink},...u.chipSlotLabel===null?[]:[u.chipSlotLabel]];return e.intent==="vet_report"?a!==void 0?/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>{Uh(a,l)},children:/* @__PURE__ */$(Text,{tier:"compact",style:w,children:e.label})})}):i===null?null:/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(VetVisitButtonCore,{entry:"chat",petRef:i,label:e.label,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:[u.chip,b,y],labelStyle:w})}):/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>o(t),children:/* @__PURE__ */$(Text,{tier:"compact",style:w,children:e.label})})})}function wR(e){let t=hb(e.slots.chip),r=pb(t);return{chipSlot:t===void 0?null:fb(t,pR),chipSlotLabel:r.color===void 0?null:r,...CR(e)}}function CR(e){let t=e.color,r=e.space,n=e.type;return v.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*vR,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+bR},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:pR,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+mR,paddingVertical:r.sm,minHeight:dR,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:pR,borderColor:wo(t.brandInk,gR)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*yR),color:K_,textAlign:"left"}})}var SR=1e3,xR=150,_R=.25,RR=.5,TR=3;function TypingIndicator({petName:e=null,inline:t=false}){let{theme:r,styles:l}=Jm(),i=r.motion.reducedMotion,o=Xf(Qf.reading,e),a=c(Array.from({length:TR},()=>new M.Value(0))).current;return n(()=>{if(i)return;let e=a.map((e,t)=>M.loop(M.sequence([M.delay(t*xR),M.timing(e,{toValue:1,duration:SR*.4,useNativeDriver:true}),M.timing(e,{toValue:0,duration:SR*.6,useNativeDriver:true}),M.delay((TR-t-1)*xR)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[i,a]),/* @__PURE__ */$(x,{style:t?l.readingInline:l.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:o,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:a.map((e,r)=>/* @__PURE__ */$(M.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[t?l.readingDotInline:l.readingDot,i?{opacity:RR}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[_R,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},r))})}function IR(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function zR(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 PR(e,t,r){let n=Math.max(0,r),l=e===null?n:Math.min(Math.max(0,e),n);return l>t+1?l:null}var OR=16;function ER(e,t,r=null){let l=c(null),i=c(true),o=c(t),a=c(0),s=c(0),d=c(0),f=c(/* @__PURE__ */new Map),h=c(null),p=c(false),g=e[0]?.id??null,b=c(g),m=c(null);n(()=>{let t=b.current;if(b.current=g,t===null||t===g||(m.current=null,i.current||!e.some(e=>e.id===t)))return;let r=f.current.get(t);r!==void 0&&(m.current={id:t,top:r,offset:a.current})},[g,e]);let y=zR(e),v=y===null?null:e[y.assistantIndex]?.id??null,k=y===null||y.userIndex===null?null:e[y.userIndex]?.id??null,w=u(()=>{let e=l.current;if(e===null||!i.current||s.current===0)return;let t=null;if(v!==null){let e=f.current.get(v);if(e===void 0)return;let r=k===null?null:f.current.get(k)??null;t=IR(e,r,96)}let r=PR(t,a.current,d.current-s.current);if(r!==null&&(a.current=r,e.scrollTo({y:r,animated:false})),!p.current||h.current===null)return;let n=PR(h.current+OR-s.current,a.current,d.current-s.current);n!==null&&(a.current=n,e.scrollTo({y:n,animated:false}))},[v,k]);n(()=>{p.current=r!==null,r===null&&(h.current=null),w()},[r,w]),n(()=>{t&&!o.current&&(i.current=true,p.current=false),o.current=t,w()},[e,t,w]);let C=u(e=>{s.current=e.nativeEvent.layout.height,w()},[w]),S=u((e,t)=>{d.current=t,s.current>0&&(a.current=Math.min(a.current,Math.max(0,t-s.current))),w()},[w]),x=u(e=>{a.current=e.nativeEvent.contentOffset.y},[]),_=u(()=>{i.current=false,p.current=false},[]),R=u(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;a.current=t.y,i.current=r.height-t.y-n.height<=24},[]),T=u(e=>t=>{let r=t.nativeEvent.layout.y;f.current.set(e,r);let n=m.current;if(n!==null&&n.id===e&&r!==n.top){m.current=null;let e=Math.max(0,n.offset+r-n.top);a.current=e,l.current?.scrollTo({y:e,animated:false})}(e===v||e===k)&&w()},[v,k,w]),I=u(e=>{let{y:t,height:r}=e.nativeEvent.layout;h.current=t+r,w()},[w]);return{ref:l,onLayout:C,onContentSizeChange:S,onScroll:x,onScrollBeginDrag:_,onScrollEnd:R,rowLayout:T,asideLayout:I}}function jR(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */$(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */$(LoadingState,{})}):/* @__PURE__ */$(LoadingState,{});case"empty":/* @__PURE__ */
|
|
347
347
|
return $(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 $(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
|
|
349
|
-
return $(PopulatedState,{messages:t.messages,prompts:
|
|
350
|
-
return W(E,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:
|
|
349
|
+
return $(PopulatedState,{messages:t.messages,prompts:fp(t,r.followUpPolicy),actions:r.answerCards?Rx(t,r.answerCards):AR,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:t}=Jm(),[r,i]=l(false);return n(()=>{let e=setTimeout(()=>i(true),lm);return()=>clearTimeout(e)},[]),/* @__PURE__ */$(x,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:Qf.loading,children:r?/* @__PURE__ */$(j,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:l,top:i,topCard:o,pendingCheckin:a,starterPrompts:s,emptyState:u,centered:c,renderEmptyHeader:d}){let{styles:f}=Jm(),h=dw(),p=d===void 0?null:/* @__PURE__ */$(x,{testID:"everfur-empty-header",children:/* @__PURE__ */$(HostRender,{render:()=>d({ask:r}),fallback:null})});if(h!==null){let{minHeight:c,...d}=h.view(".ask-empty");/* @__PURE__ */
|
|
350
|
+
return W(E,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:MR,nestedScrollEnabled:true,accessibilityLabel:Qf.empty,children:[i!=null?/* @__PURE__ */$(x,{style:h.view(".ask-top"),children:i}):null,a,o??null,p,
|
|
351
351
|
/* @__PURE__ */$(x,{style:h.view(".ask-start"),children:/* @__PURE__ */$(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:true})})]})}
|
|
352
352
|
/* @__PURE__ */
|
|
353
|
-
return W(E,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:
|
|
354
|
-
/* @__PURE__ */$(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=
|
|
355
|
-
/* @__PURE__ */$(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??
|
|
353
|
+
return W(E,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:MR,nestedScrollEnabled:true,accessibilityLabel:Qf.empty,children:[i??null,a,o??null,p,
|
|
354
|
+
/* @__PURE__ */$(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=Jm();return e.length===0?null:/* @__PURE__ */W(x,{style:n.followUps,children:[
|
|
355
|
+
/* @__PURE__ */$(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??Qf.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */$(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:l}=Jm(),i=Lg(),o=Gg(i.followUpInMs,{delayMs:Dg(i,t)});/* @__PURE__ */
|
|
356
356
|
return $(M.View,{style:o,children:/* @__PURE__ */W(PressScale,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[l.followUpSlot,t>0?l.followUpSlotRuled:null],style:l.followUpRow,children:[
|
|
357
357
|
/* @__PURE__ */$(Text,{tier:"control",style:l.followUpText,children:e}),
|
|
358
|
-
/* @__PURE__ */$(PlusGlyph,{size:
|
|
358
|
+
/* @__PURE__ */$(PlusGlyph,{size:LR,color:n.slots.chip?.textColor??n.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Jm(),l=vp(e)?$h(r):void 0,i=np(e);/* @__PURE__ */
|
|
359
359
|
return W(x,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[i!==null?/* @__PURE__ */$(Text,{style:n.errorText,testID:"everfur-chat-cap-reached",children:i.reached}):null,
|
|
360
|
-
/* @__PURE__ */$(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */$(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */$(z,{onPress:l,accessibilityRole:"button",accessibilityLabel:
|
|
361
|
-
return W(E,{ref:B.ref,style:j.list,contentContainerStyle:C!==null?j.listContentCards:j.listContent,accessibilityLabel:
|
|
360
|
+
/* @__PURE__ */$(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */$(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */$(z,{onPress:l,accessibilityRole:"button",accessibilityLabel:Qf.addPet,style:n.retryButton,children:/* @__PURE__ */$(Text,{tier:"control",style:n.retryLabel,children:Qf.addPet})}):null,e.retryable?/* @__PURE__ */$(z,{onPress:t,accessibilityRole:"button",accessibilityLabel:Qf.retry,style:n.retryButton,children:/* @__PURE__ */$(Text,{tier:"control",style:n.retryLabel,children:Qf.retry})}):null]})}function PopulatedState({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:l,onCopy:i,sentimentByMessage:o,onSentiment:s,feedbackNote:u,imagesByMessage:c,onPreview:d,notice:f,reconnecting:h,onRetry:p,onStartNew:g,petRef:b,onFindVet:m,vet:y,onOpenUrl:v,petName:k,actions:w,answerCards:C,threadTop:S,pendingCheckin:_,threadAside:R,threadAsideKey:T,followUpLabel:I,openingCard:P,earlier:O}){let{styles:j}=Jm(),F=Lg();tb(e.length,F);let A=a(()=>tx(ex(e)),[e]),D=op(e,n),M=e[e.length-1],L=R??null,B=ER(e,n,L===null?null:T??"shown"),H=Qg(e),U=e[0],N=P!==void 0&&U!==void 0&&U.role==="user"&&U.text.trim()===P.prompt?U.id:null;/* @__PURE__ */
|
|
361
|
+
return W(E,{ref:B.ref,style:j.list,contentContainerStyle:C!==null?j.listContentCards:j.listContent,accessibilityLabel:Qf.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:MR,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:DR,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[S??null,_,O!==null?/* @__PURE__ */$(z,{onPress:()=>{O.load()},disabled:O.loading,accessibilityRole:"button",accessibilityLabel:O.loading?Jp.loadingEarlier:Jp.earlier,accessibilityState:{disabled:O.loading,busy:O.loading},hitSlop:xm,style:j.earlierButton,children:/* @__PURE__ */$(Text,{tier:"compact",style:j.earlierLabel,children:O.loading?Jp.loadingEarlier:Jp.earlier})}):null,e.map(t=>t.id===N&&P!==void 0?/* @__PURE__ */$(OpeningCard,{card:P.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */$(CheckinCard,{message:t,checkin:t.checkin,onAnswer:l,petRef:b,onFindVet:m,vet:y,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */$(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:n&&t===M&&t.role==="assistant",onCopy:i,sentiment:t.responseId===void 0?null:o[String(t.responseId)]??null,onSentiment:s,note:t.responseId!==void 0&&u?.responseId===String(t.responseId)?u.kind:null,images:c[t.id]??FR,onPreview:d,onOpenUrl:v,entering:H(t.id),answerCards:C,messages:e},t.id)),h?/* @__PURE__ */$(Text,{tier:"compact",style:j.reconnectingCaption,accessibilityRole:"text",children:Qf.reconnecting}):null,D?/* @__PURE__ */$(TypingIndicator,{petName:k,inline:C!==null}):null,f!==null?/* @__PURE__ */$(TurnNoticeCard,{notice:f,onRetry:p,onStartNew:g}):null,C!==null?/* @__PURE__ */$(CardsFollowUps,{prompts:t,onSelectPrompt:r,label:I,actions:w,options:C}):/* @__PURE__ */$(FollowUps,{prompts:t,onSelectPrompt:r,label:I}),L!==null?/* @__PURE__ */$(x,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Jm(),l=e.tone==="error";/* @__PURE__ */
|
|
362
362
|
return W(x,{style:[n.turnNotice,l?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
363
363
|
/* @__PURE__ */$(Text,{tier:"control",style:[n.turnNoticeTitle,l?n.turnNoticeTitleError:null],children:e.title}),
|
|
364
364
|
/* @__PURE__ */$(Text,{tier:"compact",style:n.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:n.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
|
|
365
|
-
/* @__PURE__ */$(z,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:
|
|
365
|
+
/* @__PURE__ */$(z,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:xm,style:n.turnNoticeAction,children:/* @__PURE__ */$(Text,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}var FR=/* @__PURE__ */Object.freeze([]),AR=/* @__PURE__ */Object.freeze([]),DR=16,MR=m.OS==="ios"?"interactive":"on-drag",LR=18;function MessageRow({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:l,note:i,images:o,onPreview:a,onOpenUrl:s,onLayout:c,entering:d,answerCards:f,messages:h}){let{theme:p,styles:g}=Jm(),b=Lg(),m=Yg(d,b),y=Jg(e.text,t,b),v=e.role==="user",k=e.role==="vet",w=e.role==="assistant",C=Tg(),S=w&&!t?C:void 0,_=S!==void 0&&Mx(e.text,S),R=w&&!p.meta.hidePoweredBy,T=v?Qf.senderUser:k?hp(e):R?Qf.assistantName:Qf.senderAssistant,I=k?ox(e.createdAt):null,z=u(t=>l(e,t),[l,e]),P=e.pending!==true,O=w&&p.meta.assistantAvatarUrl!==null?/* @__PURE__ */$(AssistantSender,{avatarUrl:p.meta.assistantAvatarUrl,named:R,styles:g}):R?f!==null?/* @__PURE__ */$(CardsByline,{label:Qf.assistantName}):/* @__PURE__ */$(Text,{tier:"control",style:g.assistantName,children:Qf.assistantName}):null,E=f!==null;return w&&f!==null?/* @__PURE__ */$(M.View,{style:[g.rowBlock,m],onLayout:c,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */$(CardsAnswer,{message:e,text:y,streaming:t,messages:h,options:f,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,sender:O,onOpenUrl:s,footer:t=>/* @__PURE__ */$(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:t&&e.responseId!==void 0?z:void 0,note:i})})}):/* @__PURE__ */W(x,{style:[g.rowBlock,v?g.rowBlockUser:g.rowBlockAssistant],onLayout:c,children:[
|
|
366
366
|
/* @__PURE__ */$(x,{style:[g.row,v?g.rowUser:g.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */W(M.View,{style:[g.bubble,E?g.bubbleCards:null,v?g.bubbleSideUser:null,m],children:[O,k?/* @__PURE__ */W(x,{style:g.vetHeader,children:[
|
|
367
367
|
/* @__PURE__ */$(Text,{tier:"control",style:g.vetSender,children:T}),I!==null?/* @__PURE__ */$(Text,{tier:"compact",style:g.vetTime,children:I}):null]}):null,
|
|
368
368
|
/* @__PURE__ */W(x,{style:[v?g.bubbleUser:k?g.bubbleVet:g.bubbleAssistant,v&&E?g.bubbleUserCards:null,e.pending?g.bubblePending:null],children:[v&&o.length>0?/* @__PURE__ */$(SentImages,{images:o,onPreview:e=>a({uri:e.uri,label:e.filename})}):null,
|
|
369
|
-
/* @__PURE__ */$(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:w?
|
|
369
|
+
/* @__PURE__ */$(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:w?Lx(y,{bold:g.bubbleBold,italic:g.bubbleItalic,code:g.bubbleCode},S):e.text})]})]})}),w&&!t?/* @__PURE__ */$(ServerCardsSlot,{message:e}):null,w&&!t?/* @__PURE__ */$(CitationCards,{citations:e.citations,onOpenUrl:s}):null,P&&!(v&&f!==null)?/* @__PURE__ */$(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,note:i}):null]})}var BR=/* @__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"&&BR.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function HR(){let{runtime:e}=Rd(),t=e.entitlements??null,r=u(e=>t===null?()=>{}:t.subscribe(e),[t]),n=t===null?NO_SNAPSHOT2:t.getSnapshot,l=i(r,n,n);return a(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var UR=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function NR(e,t,r=false){let[n,i]=l(null);if(!e)return UR;let o=/* @__PURE__ */$(AskRunner,{ready:textingAskThreadReady(t),onAsk:i,entry:r}),a=r&&n!==null&&n.canOpen?{label:G.textingAskLines(n).accept,onOpen:n.open}:null;if(n===null||n.stage==="hidden"||n.stage==="dismissed")return{runner:o,line:null,entry:null,stage:null,headerEntry:a};let s=G.textingAskLines(n),u=/* @__PURE__ */$(AskLine,{stage:n.stage,text:n.stage==="verified"?s.verified:s.line,accept:s.accept,dismiss:s.dismiss,onAccept:n.accept,onDismiss:n.dismiss}),c=n.stage==="enrolling"?/* @__PURE__ */$(G.ChatTextingAskComposer,{ask:n}):null;return{runner:o,line:u,entry:c,stage:n.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:t,entry:r}){let{userRef:l}=Rd(),i=HR(),o=l!==null&&i;return n(()=>{o||t(null)},[o,t]),o?/* @__PURE__ */$(G.ChatTextingAskController,{enabled:true,ready:e,onAsk:t,entry:r}):null}function AskLine({stage:e,text:t,accept:r,dismiss:n,onAccept:l,onDismiss:i}){let{theme:o,styles:a}=Jm(),s=!o.meta.hidePoweredBy,u=s?Qf.assistantName:Qf.senderAssistant,c=o.meta.assistantAvatarUrl!==null?/* @__PURE__ */$(AssistantSender,{avatarUrl:o.meta.assistantAvatarUrl,named:s,styles:a}):s?/* @__PURE__ */$(Text,{tier:"control",style:a.assistantName,children:Qf.assistantName}):null;/* @__PURE__ */
|
|
370
370
|
return W(x,{style:[a.rowBlock,a.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
|
|
371
371
|
/* @__PURE__ */$(x,{style:[a.row,a.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${u}: ${t}`,children:/* @__PURE__ */W(x,{style:a.bubble,children:[c,
|
|
372
|
-
/* @__PURE__ */$(x,{style:a.bubbleAssistant,children:/* @__PURE__ */$(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */$(x,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */$(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */$(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function
|
|
373
|
-
return $(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */$(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */$(ChatBody,{...e})})})}function
|
|
374
|
-
return $(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=
|
|
375
|
-
return $(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:s,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:p,attachments:g,pet:b,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:w,initialAskKey:C,composerSeed:S,lifecycle:_,refreshIntervalMs:R,refreshesBlankThread:T,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:L,historySheet:B,historyBar:H,starterPrompts:N,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:
|
|
376
|
-
/* @__PURE__ */$(TopCard,{card:et,open:tt,onOpenChange:rt,ask:nt}),ct===void 0?ut:null]}),pt=ct!==void 0,gt=he.load,bt=he.open;n(()=>{pt&&!bt&>()},[pt,bt,ce.conversationId,gt]);let mt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:_e,draftStore:P,onStage:Ee.stage,onPreview:Fe,petName:ye?.name??null,petBreed:ye?.breed??null,compact:
|
|
372
|
+
/* @__PURE__ */$(x,{style:a.bubbleAssistant,children:/* @__PURE__ */$(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */$(x,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */$(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */$(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function $R(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),t=globalThis;return t[e]??(t[e]=createContext(null))}var WR=/* @__PURE__ */$R();function VR(e){return typeof e=="object"&&e!==null&&e.ok===true}function qR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ft(t.error)}function GR(e){let t=o(WR),r=t?.onMessageSent,n=t?.onFreeCapReached,l=u((...t)=>{let l=e(...t);return Promise.resolve(l).then(e=>{try{if(VR(e)){r?.();return}let t=n===void 0?null:qR(e);t!==null&&n?.(t)}catch{}},()=>{}),l},[e,r,n]);return r===void 0&&n===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
|
|
373
|
+
return $(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */$(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */$(ChatBody,{...e})})})}function KR(){try{return Rd()}catch{return null}}function YR(e){return tp({...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=KR();return t===null?/* @__PURE__ */$(ChatBodyAlone,{...e}):/* @__PURE__ */$(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let t=YR(e),r=JSON.stringify(t),n=e.petRef??null,l=a(()=>({presentation:resolvePresentation({server:null,locked:null,client:t}),isLocked:()=>false,planPage:null,planPetRef:n,inProvider:false,telemetry:null}),[r,n]);/* @__PURE__ */
|
|
374
|
+
return $(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=ep(YR(r)),l=cf("healthPlan"),i=n.chatTopCard==="focus"&&r.topCard===void 0&&l,o=r.petRef??e??null,s=useHealthPlanPage({petRef:o,enabled:i}),u=i&&s.phase==="ready"?s.page:null,c=a(()=>({presentation:n,isLocked:isLocked,planPage:u,planPetRef:o,inProvider:true,telemetry:t}),[n,isLocked,u,o,t]);/* @__PURE__ */
|
|
375
|
+
return $(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:s,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:p,attachments:g,pet:b,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:w,initialAskKey:C,composerSeed:S,lifecycle:_,refreshIntervalMs:R,refreshesBlankThread:T,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:L,historySheet:B,historyBar:H,starterPrompts:N,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:Z}){let{presentation:J,isLocked:isLocked,planPage:X,planPetRef:ee}=e,{theme:te,styles:re}=Jm(),ne=cw()??(J.chatAnswerStyle==="cards"?lS:null),le=a(()=>ne===null?null:ne(te),[ne,te]),ie=useHostPoweredBy(),oe=Lg(),ae=a(()=>pp(t,r),[t,r]),se=useEverfurChat(ae),ue=GR(se.send),ce=a(()=>ue===se.send?se:{...se,send:ue},[se,ue]),de=rp(ce),fe=KS(),he=ag(ce),pe=U(),ge=ip(ce,"web"),be=a(()=>h===void 0?void 0:()=>{Uh(h,"emergency")},[h]),me=a(()=>O===void 0&&E===void 0&&j===void 0?void 0:{returnTo:O,usState:E,prefer:j},[O,E,j]),ye=Wk(fe.pets,ce.petRef),[ve,ke]=l(null),we=a(()=>{let e=hg(ce.messages,ye?.name??null);return e?.level==="schedule_soon"&&e.messageId===ve?null:e},[ce.messages,ye?.name,ve]),Ce=gg(we);QS(ce),tb(Ce.showBanner,oe);let Se=KR(),xe=Yp(k,Se);Zp(ce.openCheckin,v??xe,{petRef:ce.petRef,pinned:t!==void 0,ready:!ce.isBootstrapping,selectPet:e=>{fe.setActivePet(e),Uh(d,e)}}),zp(ce.askEverfur,ce.isBootstrapping,w,C);let _e=a(()=>Ip(S),[S]),Re=a(()=>Ip(w),[w]),Te=a(()=>Z!==void 0&&Re!==null?{card:Z,prompt:Re}:void 0,[Z,Re]),Ie=a(()=>_===void 0?createAppStateLifecycle():_??void 0,[_]);Bp(Ie,{conversationId:ce.conversationId===null?null:String(ce.conversationId),isTurnInFlight:ce.isStreaming,refreshesBlankThread:T===true||z===true,refresh:ce.refreshActiveThread===void 0?void 0:()=>ce.refreshActiveThread?.(Fp(z===true,Ap(Ie,db)))??Promise.resolve()},{intervalMs:R===void 0?3e4:R,isVisibleFallback:db}),Dp({isStreaming:ce.isStreaming,status:ce.status,conversationId:ce.conversationId===null?null:String(ce.conversationId),unreadCount:ce.unreadCount,markRead:ce.markRead},()=>Ap(Ie,db));let ze=ce.pendingCheckin??null,Pe=ze===null?null:/* @__PURE__ */$(x,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */$(CheckinCard,{message:ze.message,checkin:ze.checkin,onAnswer:ce.petRef?ce.answerCheckin:null,petRef:ce.petRef,onFindVet:be,vet:me,onOpen:()=>{ce.resumeConversation(ze.conversationId)}})}),Oe=(ce.hasUnreadThreads??false)||he.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ce.unreadCount??0)>0,Ee=Sp(ce.messages),[je,Fe]=l(null),Ae=u(()=>Fe(null),[]),[De,Me]=l(null),[Le,Be]=l(null),He=c(null);n(()=>()=>{He.current&&clearTimeout(He.current)},[]);let Ue=u((e,t)=>{Be({responseId:String(e),kind:t}),He.current&&clearTimeout(He.current),He.current=t==="thanks"?setTimeout(()=>{Be(null),He.current=null},im):null},[]),Ne=u((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=ce.sentimentByMessage[String(r)];Be(e=>e?.responseId===String(r)?null:e),ce.feedback(r,t).then(e=>{e.ok||Ue(r,"failed")}),t==="down"&&n!=="down"&&Me(r)},[ce,Ue]),$e=u(async(e,t)=>De===null||!(e==null&&t===null?{ok:true}:await ce.feedback(De,"down",e??"other",t)).ok?false:(Me(null),Ue(De,"thanks"),true),[ce,De,Ue]),We=u(()=>Me(null),[]),Ve=u(e=>{ce.send(e)},[ce.send]),qe=a(()=>F===void 0?void 0:e=>{Uh(F,e,"citation")},[F]),Ge=m.OS==="ios"?"padding":void 0,Ke=hS(A,Ge!==void 0),Ye=Ke.topInWindow===null?pe.top:Math.max(0,pe.top-Ke.topInWindow),Qe=gS(),Ze=a(()=>M===void 0?void 0:()=>{Uh(M,ee)},[M,ee]),Je=a(()=>({petRef:ce.petRef,vet:me,cover:ke}),[ce.petRef,me]),Xe=a(()=>D===void 0?healthPlanTopCard(X,{onOpenPlan:Ze}):void 0,[D,X,Ze]),et=J.chatTopCard==="focus"?D??Xe:void 0,[tt,rt]=l(true),nt=u(e=>{ce.send(e)},[ce.send]),lt=a(()=>mp(Q,J,isLocked("chatFollowUpCount")),[Q,J,isLocked]),it=J.chatAnswerStyle==="cards",ot=a(()=>it&&ce.messages.length===0?JR(ce.suggestedPrompts):void 0,[it,ce.messages.length,ce.suggestedPrompts]),at=J.chatHistoryStyle==="sheet",st=ce.messages.length===0,ut=et!==void 0?/* @__PURE__ */$(TopCardPill,{card:et,open:tt,onOpenChange:rt}):null,ct=H??(G?void 0:XR),dt=ct!==void 0?/* @__PURE__ */$(HistoryBar,{bar:ct,history:he,empty:st,unread:Oe,extra:ut}):null,ft=J.chatHistoryBar==="scroll"&&(de==="empty"||de==="populated"),ht=et===void 0?null:/* @__PURE__ */W(V,{children:[
|
|
376
|
+
/* @__PURE__ */$(TopCard,{card:et,open:tt,onOpenChange:rt,ask:nt}),ct===void 0?ut:null]}),pt=ct!==void 0,gt=he.load,bt=he.open;n(()=>{pt&&!bt&>()},[pt,bt,ce.conversationId,gt]);let mt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:_e,draftStore:P,onStage:Ee.stage,onPreview:Fe,petName:ye?.name??null,petBreed:ye?.breed??null,compact:J.chatComposerStyle==="compact",petPlaceholder:J.chatComposerPlaceholder==="pet_name",dimEmptySend:J.chatSendButton==="dim_when_empty",mood:eT(de,Ce.source?.level??null),dictation:J.chatComposerMic,telemetry:e.telemetry},yt=NR(J.chatTextingAsk&&e.inProvider,ce,K),vt=g!==void 0&&J.chatComposerUpload,kt=!J.chatGeneralBanner&&Ce.source?.level==="general";
|
|
377
377
|
/* @__PURE__ */
|
|
378
|
-
return $(
|
|
378
|
+
return $(uw.Provider,{value:le,children:/* @__PURE__ */W(I,{style:[re.container,{paddingTop:Ye},i],behavior:Ge,...Ke.avoidingProps,children:[
|
|
379
379
|
/* @__PURE__ */$(KeyboardOffsetProbe,{probeRef:Ke.probeRef}),
|
|
380
380
|
/* @__PURE__ */W(SdkTabletColumn,{children:[G?/* @__PURE__ */$(ChatHeader,{pets:fe,petRef:ce.petRef,historyUnread:Oe,onOpenHistory:he.show,onNewChat:he.newConversation,onPetChange:d,onAddPet:y,vet:me,textingEntry:yt.headerEntry}):null,b!==void 0?/* @__PURE__ */$(PetSetupNotice,{petRef:t??null,pet:b,onRegistered:fe.refresh}):null,!G&&yt.headerEntry!==null?/* @__PURE__ */$(TextingEntryRow,{entry:yt.headerEntry,place:"thread"}):null,ft?null:dt,kt?null:/* @__PURE__ */$(UrgencyBanner,{surface:Ce,petRef:ce.petRef,renderVetAction:p,onFindVet:h,vet:me,compact:Qe}),
|
|
381
|
-
/* @__PURE__ */$(x,{style:re.body,children:/* @__PURE__ */$(
|
|
381
|
+
/* @__PURE__ */$(x,{style:re.body,children:/* @__PURE__ */$(yg.Provider,{value:Je,children:jR(de,ce,{notice:ge,vet:me,onCheckinFindVet:be,onSelectPrompt:Ve,renderPending:o,shownPet:ye,onVetPrep:f,onCopy:s,onSentiment:Ne,feedbackNote:Le,imagesByMessage:Ee.byMessage,onPreview:Fe,onAddPet:y,onOpenUrl:qe,threadTop:ft?dt:null,pendingCheckin:Pe,topCard:ht,starterPrompts:N??ot,emptyState:q,emptyCentered:J.chatAnswerStyle==="cards",followUpPolicy:lt,answerCards:J.chatAnswerStyle==="cards"?L??QR:null,threadAside:yt.line,threadAsideKey:yt.stage,renderEmptyHeader:Y,openingCard:Te})})}),yt.runner,yt.entry!==null?/* @__PURE__ */$(x,{style:re.composerOuter,children:/* @__PURE__ */$(x,{style:re.askEntry,children:yt.entry})}):vt&&g!==void 0?/* @__PURE__ */$(ComposerWithAttachments,{...mt,attachments:g}):/* @__PURE__ */$(Composer,{...mt,attachments:null}),te.meta.hidePoweredBy||ie?null:/* @__PURE__ */$(Text,{tier:"compact",style:re.poweredBy,accessibilityRole:"text",accessibilityLabel:Qf.poweredBy,children:Qf.poweredBy})]}),at?/* @__PURE__ */$(HistorySheet,{chat:ce,history:he,sheet:B}):/* @__PURE__ */$(HistoryDrawer,{chat:ce,history:he}),
|
|
382
382
|
/* @__PURE__ */$(FeedbackReasons,{visible:De!==null,onSubmit:$e,onSkip:We}),
|
|
383
383
|
/* @__PURE__ */$(AttachmentImageLightbox,{uri:je?.uri??null,label:je?.label??"",onClose:Ae}),
|
|
384
|
-
/* @__PURE__ */$(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=
|
|
384
|
+
/* @__PURE__ */$(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Jm(),l=wp(e,t,r);return l.status!=="failed"||l.error===null?null:/* @__PURE__ */W(x,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
385
385
|
/* @__PURE__ */$(Text,{tier:"compact",style:n.setupNoticeText,children:l.error.displayMessage}),
|
|
386
|
-
/* @__PURE__ */$(z,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:
|
|
387
|
-
return $(
|
|
386
|
+
/* @__PURE__ */$(z,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:Qf.retry,hitSlop:xm,children:/* @__PURE__ */$(Text,{tier:"control",style:n.setupNoticeAction,children:Qf.retry})})]})}var QR=/* @__PURE__ */Object.freeze({}),ZR=3;function JR(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===ZR)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var XR=/* @__PURE__ */Object.freeze({chats:Jp.heading,newChat:Jp.newChat});function eT(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
|
|
387
|
+
return $(Cf.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */$(EverfurChatCore,{...e})})}var tT=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function rT(e,t){let{runtime:r,userRef:l,activePet:o,scopeEpoch:s}=Rd(),c=r.unread??null,d=e===void 0?o:e,f=u(e=>c===null?NO_SUBSCRIPTION():c.subscribe(e),[c]),h=u(()=>c===null||l===null?tT:c.get(d),[c,l,d]),p=i(f,h,h),g=u(()=>c===null||l===null?Promise.resolve():c.refresh(d),[c,l,d]);return n(()=>{g()},[g,s]),Bp(t,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:g}),a(()=>({...p,refresh:g}),[p,g])}function useEverfurUnread(e={}){let{lifecycle:t}=e,r=a(()=>t===void 0?createAppStateLifecycle():t??void 0,[t]);return rT(e.petRef,r)}function useEverfurPetProfile(e){let{runtime:t,userRef:r,scopeEpoch:i}=Rd(),o=a(()=>createPetsRepository(t.registry.services.authFor(r)),[t,r,i]),s=a(()=>({repository:o,petRef:e}),[o,e]),[d,f]=l({key:s,profile:null,loading:e!==null,error:null}),h=d.key===s?d:{profile:null,loading:e!==null,error:null},p=c(0),g=u(async()=>{let e=++p.current;if(s.petRef===null){f({key:s,profile:null,loading:false,error:null});return}f(e=>({key:s,profile:e.key===s?e.profile:null,loading:true,error:null}));let t=await s.repository.getPetProfile(s.petRef);e===p.current&&f(t.ok?{key:s,profile:t.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:t.error})},[s]);return n(()=>(g(),()=>{p.current+=1}),[g]),a(()=>({profile:h.profile,loading:h.loading,error:h.error,refresh:g}),[h.profile,h.loading,h.error,g])}function EverfurThemeProvider(e){return r(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:af,children:e.children})}export{Ss as APPEARANCE_PRESETS,Cs as APPEARANCE_PRESET_NAMES,xs as APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,Z as EverfurConfigError,EverfurProvider,EverfurThemeProvider,Q as EverfurThrownError,Zo as PHONE_TEXT_SCALE_CAPS,Io as THEME_SLOT_KEYS,zo as THEME_SLOT_KEYS_BY_SLOT,To as THEME_SLOT_NAMES,Ko as TYPE_ROLE_DEFAULTS,Go as TYPE_ROLE_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurChatCards,registerEverfurDictation,textRole,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,useEverfurUnread,userFacingError,userRef};
|